blob: 4443de05380aff56935730f8ff3b257f862ad19a [file] [log] [blame]
Douglas Gregor5251f1b2008-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 McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000020#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000022#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000024#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000025#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000026#include <algorithm>
Torok Edwindb714922009-08-24 13:25:12 +000027#include <cstdio>
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-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 Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor5251f1b2008-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 Gregor40cb9ad2009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000082 ICR_Conversion,
Douglas Gregor5251f1b2008-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 Gregor40cb9ad2009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor26bee0b2008-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 Redlf69a94a2009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000126}
127
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-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 Gregor033f56d2008-12-23 00:53:59 +0000155 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor5251f1b2008-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 Gregor5c407d92008-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 Stump11289f42009-09-09 15:08:12 +0000166bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000167StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000168isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregor5c407d92008-10-23 00:40:37 +0000169 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
170 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
171
172 // Note that FromType has not necessarily been transformed by the
173 // array-to-pointer implicit conversion, so check for its presence
174 // and redo the conversion to get a pointer.
175 if (First == ICK_Array_To_Pointer)
176 FromType = Context.getArrayDecayedType(FromType);
177
178 if (Second == ICK_Pointer_Conversion)
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000179 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000180 return ToPtrType->getPointeeType()->isVoidType();
181
182 return false;
183}
184
Douglas Gregor5251f1b2008-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 Gregor2fe98832008-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 Gregor5251f1b2008-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 Lattnerf3d3fae2008-11-24 05:29:24 +0000230 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor5251f1b2008-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 McCall3d988d92009-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 McCalldaa3d6b2009-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 Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +0000276// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000277//
John McCall3d988d92009-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 Gregor5251f1b2008-10-21 16:13:35 +0000282//
John McCall3d988d92009-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 Gregor5251f1b2008-10-21 16:13:35 +0000287// signature), IsOverload returns false and MatchedDecl will be set to
288// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000289Sema::OverloadKind
290Sema::CheckOverload(FunctionDecl *New, LookupResult &Old, NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000291 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000292 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000293 NamedDecl *OldD = (*I)->getUnderlyingDecl();
294 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000295 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000296 Match = *I;
297 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000298 }
John McCall3d988d92009-12-02 08:47:38 +0000299 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000300 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000301 Match = *I;
302 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000303 }
John McCalldaa3d6b2009-12-09 03:35:25 +0000304 } else if (!isa<UnresolvedUsingValueDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000305 // (C++ 13p1):
306 // Only function declarations can be overloaded; object and type
307 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000308 // But we permit unresolved using value decls and diagnose the error
309 // during template instantiation.
310 Match = *I;
311 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000312 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000313 }
John McCall1f82f242009-11-18 22:49:29 +0000314
John McCalldaa3d6b2009-12-09 03:35:25 +0000315 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000316}
317
318bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
319 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
320 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
321
322 // C++ [temp.fct]p2:
323 // A function template can be overloaded with other function templates
324 // and with normal (non-template) functions.
325 if ((OldTemplate == 0) != (NewTemplate == 0))
326 return true;
327
328 // Is the function New an overload of the function Old?
329 QualType OldQType = Context.getCanonicalType(Old->getType());
330 QualType NewQType = Context.getCanonicalType(New->getType());
331
332 // Compare the signatures (C++ 1.3.10) of the two functions to
333 // determine whether they are overloads. If we find any mismatch
334 // in the signature, they are overloads.
335
336 // If either of these functions is a K&R-style function (no
337 // prototype), then we consider them to have matching signatures.
338 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
339 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
340 return false;
341
342 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
343 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
344
345 // The signature of a function includes the types of its
346 // parameters (C++ 1.3.10), which includes the presence or absence
347 // of the ellipsis; see C++ DR 357).
348 if (OldQType != NewQType &&
349 (OldType->getNumArgs() != NewType->getNumArgs() ||
350 OldType->isVariadic() != NewType->isVariadic() ||
351 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
352 NewType->arg_type_begin())))
353 return true;
354
355 // C++ [temp.over.link]p4:
356 // The signature of a function template consists of its function
357 // signature, its return type and its template parameter list. The names
358 // of the template parameters are significant only for establishing the
359 // relationship between the template parameters and the rest of the
360 // signature.
361 //
362 // We check the return type and template parameter lists for function
363 // templates first; the remaining checks follow.
364 if (NewTemplate &&
365 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
366 OldTemplate->getTemplateParameters(),
367 false, TPL_TemplateMatch) ||
368 OldType->getResultType() != NewType->getResultType()))
369 return true;
370
371 // If the function is a class member, its signature includes the
372 // cv-qualifiers (if any) on the function itself.
373 //
374 // As part of this, also check whether one of the member functions
375 // is static, in which case they are not overloads (C++
376 // 13.1p2). While not part of the definition of the signature,
377 // this check is important to determine whether these functions
378 // can be overloaded.
379 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
380 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
381 if (OldMethod && NewMethod &&
382 !OldMethod->isStatic() && !NewMethod->isStatic() &&
383 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
384 return true;
385
386 // The signatures match; this is not an overload.
387 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000388}
389
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000390/// TryImplicitConversion - Attempt to perform an implicit conversion
391/// from the given expression (Expr) to the given type (ToType). This
392/// function returns an implicit conversion sequence that can be used
393/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000394///
395/// void f(float f);
396/// void g(int i) { f(i); }
397///
398/// this routine would produce an implicit conversion sequence to
399/// describe the initialization of f from i, which will be a standard
400/// conversion sequence containing an lvalue-to-rvalue conversion (C++
401/// 4.1) followed by a floating-integral conversion (C++ 4.9).
402//
403/// Note that this routine only determines how the conversion can be
404/// performed; it does not actually perform the conversion. As such,
405/// it will not produce any diagnostics if no conversion is available,
406/// but will instead return an implicit conversion sequence of kind
407/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000408///
409/// If @p SuppressUserConversions, then user-defined conversions are
410/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000411/// If @p AllowExplicit, then explicit user-defined conversions are
412/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000413/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
414/// no matter its actual lvalueness.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000415/// If @p UserCast, the implicit conversion is being done for a user-specified
416/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000417ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000418Sema::TryImplicitConversion(Expr* From, QualType ToType,
419 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000420 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000421 bool InOverloadResolution,
422 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000423 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000424 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000425 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000426 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000427 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000428 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000429 (UserDefResult = IsUserDefinedConversion(From, ToType,
430 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000431 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000432 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000433 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000434 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000435 // C++ [over.ics.user]p4:
436 // A conversion of an expression of class type to the same class
437 // type is given Exact Match rank, and a conversion of an
438 // expression of class type to a base class of that type is
439 // given Conversion rank, in spite of the fact that a copy
440 // constructor (i.e., a user-defined conversion function) is
441 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000442 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000443 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000444 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000445 = Context.getCanonicalType(From->getType().getUnqualifiedType());
446 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
447 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000448 // Turn this into a "standard" conversion sequence, so that it
449 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000450 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
451 ICS.Standard.setAsIdentityConversion();
452 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
453 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000454 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000455 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000456 ICS.Standard.Second = ICK_Derived_To_Base;
457 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000458 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000459
460 // C++ [over.best.ics]p4:
461 // However, when considering the argument of a user-defined
462 // conversion function that is a candidate by 13.3.1.3 when
463 // invoked for the copying of the temporary in the second step
464 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
465 // 13.3.1.6 in all cases, only standard conversion sequences and
466 // ellipsis conversion sequences are allowed.
467 if (SuppressUserConversions &&
468 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
469 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000470 } else {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000471 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000472 if (UserDefResult == OR_Ambiguous) {
473 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
474 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian574de2c2009-10-12 17:51:19 +0000475 if (Cand->Viable)
476 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000477 }
478 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000479
480 return ICS;
481}
482
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000483/// \brief Determine whether the conversion from FromType to ToType is a valid
484/// conversion that strips "noreturn" off the nested function type.
485static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
486 QualType ToType, QualType &ResultTy) {
487 if (Context.hasSameUnqualifiedType(FromType, ToType))
488 return false;
489
490 // Strip the noreturn off the type we're converting from; noreturn can
491 // safely be removed.
492 FromType = Context.getNoReturnType(FromType, false);
493 if (!Context.hasSameUnqualifiedType(FromType, ToType))
494 return false;
495
496 ResultTy = FromType;
497 return true;
498}
499
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000500/// IsStandardConversion - Determines whether there is a standard
501/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
502/// expression From to the type ToType. Standard conversion sequences
503/// only consider non-class types; for conversions that involve class
504/// types, use TryImplicitConversion. If a conversion exists, SCS will
505/// contain the standard conversion sequence required to perform this
506/// conversion and this routine will return true. Otherwise, this
507/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000508bool
509Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000510 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000511 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000512 QualType FromType = From->getType();
513
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000514 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000515 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000516 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000517 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000518 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000519 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000521 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000522 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000523 if (FromType->isRecordType() || ToType->isRecordType()) {
524 if (getLangOptions().CPlusPlus)
525 return false;
526
Mike Stump11289f42009-09-09 15:08:12 +0000527 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000528 }
529
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000530 // The first conversion can be an lvalue-to-rvalue conversion,
531 // array-to-pointer conversion, or function-to-pointer conversion
532 // (C++ 4p1).
533
Mike Stump11289f42009-09-09 15:08:12 +0000534 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000535 // An lvalue (3.10) of a non-function, non-array type T can be
536 // converted to an rvalue.
537 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000538 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000539 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000540 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000541 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542
543 // If T is a non-class type, the type of the rvalue is the
544 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000545 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
546 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000547 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000548 } else if (FromType->isArrayType()) {
549 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000550 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000551
552 // An lvalue or rvalue of type "array of N T" or "array of unknown
553 // bound of T" can be converted to an rvalue of type "pointer to
554 // T" (C++ 4.2p1).
555 FromType = Context.getArrayDecayedType(FromType);
556
557 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
558 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000559 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000560
561 // For the purpose of ranking in overload resolution
562 // (13.3.3.1.1), this conversion is considered an
563 // array-to-pointer conversion followed by a qualification
564 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000565 SCS.Second = ICK_Identity;
566 SCS.Third = ICK_Qualification;
567 SCS.ToTypePtr = ToType.getAsOpaquePtr();
568 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000569 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000570 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
571 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000572 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000573
574 // An lvalue of function type T can be converted to an rvalue of
575 // type "pointer to T." The result is a pointer to the
576 // function. (C++ 4.3p1).
577 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000578 } else if (FunctionDecl *Fn
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000579 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000580 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000581 SCS.First = ICK_Function_To_Pointer;
582
583 // We were able to resolve the address of the overloaded function,
584 // so we can convert to the type of that function.
585 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000586 if (ToType->isLValueReferenceType())
587 FromType = Context.getLValueReferenceType(FromType);
588 else if (ToType->isRValueReferenceType())
589 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000590 else if (ToType->isMemberPointerType()) {
591 // Resolve address only succeeds if both sides are member pointers,
592 // but it doesn't have to be the same class. See DR 247.
593 // Note that this means that the type of &Derived::fn can be
594 // Ret (Base::*)(Args) if the fn overload actually found is from the
595 // base class, even if it was brought into the derived class via a
596 // using declaration. The standard isn't clear on this issue at all.
597 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
598 FromType = Context.getMemberPointerType(FromType,
599 Context.getTypeDeclType(M->getParent()).getTypePtr());
600 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000601 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000602 } else {
603 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000604 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000605 }
606
607 // The second conversion can be an integral promotion, floating
608 // point promotion, integral conversion, floating point conversion,
609 // floating-integral conversion, pointer conversion,
610 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000611 // For overloading in C, this can also be a "compatible-type"
612 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000613 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000614 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000615 // The unqualified versions of the types are the same: there's no
616 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000617 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000618 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000619 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000620 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000621 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000622 } else if (IsFloatingPointPromotion(FromType, ToType)) {
623 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000624 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000625 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000626 } else if (IsComplexPromotion(FromType, ToType)) {
627 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000628 SCS.Second = ICK_Complex_Promotion;
629 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000630 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000631 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000632 // Integral conversions (C++ 4.7).
633 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000634 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000635 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000636 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
637 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000638 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000639 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000640 } else if (FromType->isComplexType() && ToType->isComplexType()) {
641 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000642 SCS.Second = ICK_Complex_Conversion;
643 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000644 } else if ((FromType->isFloatingType() &&
645 ToType->isIntegralType() && (!ToType->isBooleanType() &&
646 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000647 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000648 ToType->isFloatingType())) {
649 // Floating-integral conversions (C++ 4.9).
650 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000651 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000652 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000653 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
654 (ToType->isComplexType() && FromType->isArithmeticType())) {
655 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000656 SCS.Second = ICK_Complex_Real;
657 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000658 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
659 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000660 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000661 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000662 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000663 } else if (IsMemberPointerConversion(From, FromType, ToType,
664 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000665 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000666 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000667 } else if (ToType->isBooleanType() &&
668 (FromType->isArithmeticType() ||
669 FromType->isEnumeralType() ||
670 FromType->isPointerType() ||
671 FromType->isBlockPointerType() ||
672 FromType->isMemberPointerType() ||
673 FromType->isNullPtrType())) {
674 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000675 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000676 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000677 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000678 Context.typesAreCompatible(ToType, FromType)) {
679 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000680 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000681 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
682 // Treat a conversion that strips "noreturn" as an identity conversion.
683 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000684 } else {
685 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000686 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000687 }
688
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000689 QualType CanonFrom;
690 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000691 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000692 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000693 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000694 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000695 CanonFrom = Context.getCanonicalType(FromType);
696 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000697 } else {
698 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000699 SCS.Third = ICK_Identity;
700
Mike Stump11289f42009-09-09 15:08:12 +0000701 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000702 // [...] Any difference in top-level cv-qualification is
703 // subsumed by the initialization itself and does not constitute
704 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000705 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000706 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000707 if (CanonFrom.getLocalUnqualifiedType()
708 == CanonTo.getLocalUnqualifiedType() &&
709 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000710 FromType = ToType;
711 CanonFrom = CanonTo;
712 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000713 }
714
715 // If we have not converted the argument type to the parameter type,
716 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000717 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000718 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000719
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000720 SCS.ToTypePtr = FromType.getAsOpaquePtr();
721 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000722}
723
724/// IsIntegralPromotion - Determines whether the conversion from the
725/// expression From (whose potentially-adjusted type is FromType) to
726/// ToType is an integral promotion (C++ 4.5). If so, returns true and
727/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000728bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000729 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000730 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000731 if (!To) {
732 return false;
733 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000734
735 // An rvalue of type char, signed char, unsigned char, short int, or
736 // unsigned short int can be converted to an rvalue of type int if
737 // int can represent all the values of the source type; otherwise,
738 // the source rvalue can be converted to an rvalue of type unsigned
739 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000740 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000741 if (// We can promote any signed, promotable integer type to an int
742 (FromType->isSignedIntegerType() ||
743 // We can promote any unsigned integer type whose size is
744 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000745 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000746 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000747 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000748 }
749
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000750 return To->getKind() == BuiltinType::UInt;
751 }
752
753 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
754 // can be converted to an rvalue of the first of the following types
755 // that can represent all the values of its underlying type: int,
756 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000757
758 // We pre-calculate the promotion type for enum types.
759 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
760 if (ToType->isIntegerType())
761 return Context.hasSameUnqualifiedType(ToType,
762 FromEnumType->getDecl()->getPromotionType());
763
764 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000765 // Determine whether the type we're converting from is signed or
766 // unsigned.
767 bool FromIsSigned;
768 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000769
770 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
771 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000772
773 // The types we'll try to promote to, in the appropriate
774 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000775 QualType PromoteTypes[6] = {
776 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000777 Context.LongTy, Context.UnsignedLongTy ,
778 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000779 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000780 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000781 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
782 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000783 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000784 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
785 // We found the type that we can promote to. If this is the
786 // type we wanted, we have a promotion. Otherwise, no
787 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000788 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000789 }
790 }
791 }
792
793 // An rvalue for an integral bit-field (9.6) can be converted to an
794 // rvalue of type int if int can represent all the values of the
795 // bit-field; otherwise, it can be converted to unsigned int if
796 // unsigned int can represent all the values of the bit-field. If
797 // the bit-field is larger yet, no integral promotion applies to
798 // it. If the bit-field has an enumerated type, it is treated as any
799 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000800 // FIXME: We should delay checking of bit-fields until we actually perform the
801 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000802 using llvm::APSInt;
803 if (From)
804 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000805 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000806 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
807 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
808 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
809 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000810
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000811 // Are we promoting to an int from a bitfield that fits in an int?
812 if (BitWidth < ToSize ||
813 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
814 return To->getKind() == BuiltinType::Int;
815 }
Mike Stump11289f42009-09-09 15:08:12 +0000816
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000817 // Are we promoting to an unsigned int from an unsigned bitfield
818 // that fits into an unsigned int?
819 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
820 return To->getKind() == BuiltinType::UInt;
821 }
Mike Stump11289f42009-09-09 15:08:12 +0000822
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000823 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000824 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000825 }
Mike Stump11289f42009-09-09 15:08:12 +0000826
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000827 // An rvalue of type bool can be converted to an rvalue of type int,
828 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000829 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000830 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000831 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000832
833 return false;
834}
835
836/// IsFloatingPointPromotion - Determines whether the conversion from
837/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
838/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000839bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000840 /// An rvalue of type float can be converted to an rvalue of type
841 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000842 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
843 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000844 if (FromBuiltin->getKind() == BuiltinType::Float &&
845 ToBuiltin->getKind() == BuiltinType::Double)
846 return true;
847
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000848 // C99 6.3.1.5p1:
849 // When a float is promoted to double or long double, or a
850 // double is promoted to long double [...].
851 if (!getLangOptions().CPlusPlus &&
852 (FromBuiltin->getKind() == BuiltinType::Float ||
853 FromBuiltin->getKind() == BuiltinType::Double) &&
854 (ToBuiltin->getKind() == BuiltinType::LongDouble))
855 return true;
856 }
857
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000858 return false;
859}
860
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000861/// \brief Determine if a conversion is a complex promotion.
862///
863/// A complex promotion is defined as a complex -> complex conversion
864/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000865/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000866bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000867 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000868 if (!FromComplex)
869 return false;
870
John McCall9dd450b2009-09-21 23:43:11 +0000871 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000872 if (!ToComplex)
873 return false;
874
875 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000876 ToComplex->getElementType()) ||
877 IsIntegralPromotion(0, FromComplex->getElementType(),
878 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000879}
880
Douglas Gregor237f96c2008-11-26 23:31:11 +0000881/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
882/// the pointer type FromPtr to a pointer to type ToPointee, with the
883/// same type qualifiers as FromPtr has on its pointee type. ToType,
884/// if non-empty, will be a pointer to ToType that may or may not have
885/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000886static QualType
887BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000888 QualType ToPointee, QualType ToType,
889 ASTContext &Context) {
890 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
891 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000892 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000893
894 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000895 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000896 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000897 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000898 return ToType;
899
900 // Build a pointer to ToPointee. It has the right qualifiers
901 // already.
902 return Context.getPointerType(ToPointee);
903 }
904
905 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000906 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000907 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
908 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000909}
910
Mike Stump11289f42009-09-09 15:08:12 +0000911static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000912 bool InOverloadResolution,
913 ASTContext &Context) {
914 // Handle value-dependent integral null pointer constants correctly.
915 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
916 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
917 Expr->getType()->isIntegralType())
918 return !InOverloadResolution;
919
Douglas Gregor56751b52009-09-25 04:25:58 +0000920 return Expr->isNullPointerConstant(Context,
921 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
922 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000923}
Mike Stump11289f42009-09-09 15:08:12 +0000924
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000925/// IsPointerConversion - Determines whether the conversion of the
926/// expression From, which has the (possibly adjusted) type FromType,
927/// can be converted to the type ToType via a pointer conversion (C++
928/// 4.10). If so, returns true and places the converted type (that
929/// might differ from ToType in its cv-qualifiers at some level) into
930/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000931///
Douglas Gregora29dc052008-11-27 01:19:21 +0000932/// This routine also supports conversions to and from block pointers
933/// and conversions with Objective-C's 'id', 'id<protocols...>', and
934/// pointers to interfaces. FIXME: Once we've determined the
935/// appropriate overloading rules for Objective-C, we may want to
936/// split the Objective-C checks into a different routine; however,
937/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000938/// conversions, so for now they live here. IncompatibleObjC will be
939/// set if the conversion is an allowed Objective-C conversion that
940/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000941bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000942 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000943 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000944 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000945 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000946 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
947 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000948
Mike Stump11289f42009-09-09 15:08:12 +0000949 // Conversion from a null pointer constant to any Objective-C pointer type.
950 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000951 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000952 ConvertedType = ToType;
953 return true;
954 }
955
Douglas Gregor231d1c62008-11-27 00:15:41 +0000956 // Blocks: Block pointers can be converted to void*.
957 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000958 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000959 ConvertedType = ToType;
960 return true;
961 }
962 // Blocks: A null pointer constant can be converted to a block
963 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000964 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000965 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000966 ConvertedType = ToType;
967 return true;
968 }
969
Sebastian Redl576fd422009-05-10 18:38:11 +0000970 // If the left-hand-side is nullptr_t, the right side can be a null
971 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000972 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000973 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000974 ConvertedType = ToType;
975 return true;
976 }
977
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000978 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000979 if (!ToTypePtr)
980 return false;
981
982 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000983 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000984 ConvertedType = ToType;
985 return true;
986 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000987
Douglas Gregor237f96c2008-11-26 23:31:11 +0000988 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000989 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000990 if (!FromTypePtr)
991 return false;
992
993 QualType FromPointeeType = FromTypePtr->getPointeeType();
994 QualType ToPointeeType = ToTypePtr->getPointeeType();
995
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000996 // An rvalue of type "pointer to cv T," where T is an object type,
997 // can be converted to an rvalue of type "pointer to cv void" (C++
998 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000999 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001000 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001001 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001002 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001003 return true;
1004 }
1005
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001006 // When we're overloading in C, we allow a special kind of pointer
1007 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001008 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001009 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001010 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001011 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001012 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001013 return true;
1014 }
1015
Douglas Gregor5c407d92008-10-23 00:40:37 +00001016 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001017 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001018 // An rvalue of type "pointer to cv D," where D is a class type,
1019 // can be converted to an rvalue of type "pointer to cv B," where
1020 // B is a base class (clause 10) of D. If B is an inaccessible
1021 // (clause 11) or ambiguous (10.2) base class of D, a program that
1022 // necessitates this conversion is ill-formed. The result of the
1023 // conversion is a pointer to the base class sub-object of the
1024 // derived class object. The null pointer value is converted to
1025 // the null pointer value of the destination type.
1026 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001027 // Note that we do not check for ambiguity or inaccessibility
1028 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001029 if (getLangOptions().CPlusPlus &&
1030 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001031 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001032 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001033 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001034 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001035 ToType, Context);
1036 return true;
1037 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001038
Douglas Gregora119f102008-12-19 19:13:09 +00001039 return false;
1040}
1041
1042/// isObjCPointerConversion - Determines whether this is an
1043/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1044/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001045bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001046 QualType& ConvertedType,
1047 bool &IncompatibleObjC) {
1048 if (!getLangOptions().ObjC1)
1049 return false;
1050
Steve Naroff7cae42b2009-07-10 23:34:53 +00001051 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001052 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001053 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001054 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001055
Steve Naroff7cae42b2009-07-10 23:34:53 +00001056 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001057 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001058 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001059 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001060 ConvertedType = ToType;
1061 return true;
1062 }
1063 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001064 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001065 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001066 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001067 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001068 ConvertedType = ToType;
1069 return true;
1070 }
1071 // Objective C++: We're able to convert from a pointer to an
1072 // interface to a pointer to a different interface.
1073 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1074 ConvertedType = ToType;
1075 return true;
1076 }
1077
1078 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1079 // Okay: this is some kind of implicit downcast of Objective-C
1080 // interfaces, which is permitted. However, we're going to
1081 // complain about it.
1082 IncompatibleObjC = true;
1083 ConvertedType = FromType;
1084 return true;
1085 }
Mike Stump11289f42009-09-09 15:08:12 +00001086 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001087 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001088 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001089 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001090 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001091 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001092 ToPointeeType = ToBlockPtr->getPointeeType();
1093 else
Douglas Gregora119f102008-12-19 19:13:09 +00001094 return false;
1095
Douglas Gregor033f56d2008-12-23 00:53:59 +00001096 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001097 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001098 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001099 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001100 FromPointeeType = FromBlockPtr->getPointeeType();
1101 else
Douglas Gregora119f102008-12-19 19:13:09 +00001102 return false;
1103
Douglas Gregora119f102008-12-19 19:13:09 +00001104 // If we have pointers to pointers, recursively check whether this
1105 // is an Objective-C conversion.
1106 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1107 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1108 IncompatibleObjC)) {
1109 // We always complain about this conversion.
1110 IncompatibleObjC = true;
1111 ConvertedType = ToType;
1112 return true;
1113 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001114 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001115 // differences in the argument and result types are in Objective-C
1116 // pointer conversions. If so, we permit the conversion (but
1117 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001118 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001119 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001120 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001121 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001122 if (FromFunctionType && ToFunctionType) {
1123 // If the function types are exactly the same, this isn't an
1124 // Objective-C pointer conversion.
1125 if (Context.getCanonicalType(FromPointeeType)
1126 == Context.getCanonicalType(ToPointeeType))
1127 return false;
1128
1129 // Perform the quick checks that will tell us whether these
1130 // function types are obviously different.
1131 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1132 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1133 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1134 return false;
1135
1136 bool HasObjCConversion = false;
1137 if (Context.getCanonicalType(FromFunctionType->getResultType())
1138 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1139 // Okay, the types match exactly. Nothing to do.
1140 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1141 ToFunctionType->getResultType(),
1142 ConvertedType, IncompatibleObjC)) {
1143 // Okay, we have an Objective-C pointer conversion.
1144 HasObjCConversion = true;
1145 } else {
1146 // Function types are too different. Abort.
1147 return false;
1148 }
Mike Stump11289f42009-09-09 15:08:12 +00001149
Douglas Gregora119f102008-12-19 19:13:09 +00001150 // Check argument types.
1151 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1152 ArgIdx != NumArgs; ++ArgIdx) {
1153 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1154 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1155 if (Context.getCanonicalType(FromArgType)
1156 == Context.getCanonicalType(ToArgType)) {
1157 // Okay, the types match exactly. Nothing to do.
1158 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1159 ConvertedType, IncompatibleObjC)) {
1160 // Okay, we have an Objective-C pointer conversion.
1161 HasObjCConversion = true;
1162 } else {
1163 // Argument types are too different. Abort.
1164 return false;
1165 }
1166 }
1167
1168 if (HasObjCConversion) {
1169 // We had an Objective-C conversion. Allow this pointer
1170 // conversion, but complain about it.
1171 ConvertedType = ToType;
1172 IncompatibleObjC = true;
1173 return true;
1174 }
1175 }
1176
Sebastian Redl72b597d2009-01-25 19:43:20 +00001177 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001178}
1179
Douglas Gregor39c16d42008-10-24 04:54:22 +00001180/// CheckPointerConversion - Check the pointer conversion from the
1181/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001182/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001183/// conversions for which IsPointerConversion has already returned
1184/// true. It returns true and produces a diagnostic if there was an
1185/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001186bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001187 CastExpr::CastKind &Kind,
1188 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001189 QualType FromType = From->getType();
1190
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001191 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1192 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001193 QualType FromPointeeType = FromPtrType->getPointeeType(),
1194 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001195
Douglas Gregor39c16d42008-10-24 04:54:22 +00001196 if (FromPointeeType->isRecordType() &&
1197 ToPointeeType->isRecordType()) {
1198 // We must have a derived-to-base conversion. Check an
1199 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001200 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1201 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001202 From->getSourceRange(),
1203 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001204 return true;
1205
1206 // The conversion was successful.
1207 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001208 }
1209 }
Mike Stump11289f42009-09-09 15:08:12 +00001210 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001211 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001212 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001213 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001214 // Objective-C++ conversions are always okay.
1215 // FIXME: We should have a different class of conversions for the
1216 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001217 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001218 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001219
Steve Naroff7cae42b2009-07-10 23:34:53 +00001220 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001221 return false;
1222}
1223
Sebastian Redl72b597d2009-01-25 19:43:20 +00001224/// IsMemberPointerConversion - Determines whether the conversion of the
1225/// expression From, which has the (possibly adjusted) type FromType, can be
1226/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1227/// If so, returns true and places the converted type (that might differ from
1228/// ToType in its cv-qualifiers at some level) into ConvertedType.
1229bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001230 QualType ToType,
1231 bool InOverloadResolution,
1232 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001233 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001234 if (!ToTypePtr)
1235 return false;
1236
1237 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001238 if (From->isNullPointerConstant(Context,
1239 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1240 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001241 ConvertedType = ToType;
1242 return true;
1243 }
1244
1245 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001246 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001247 if (!FromTypePtr)
1248 return false;
1249
1250 // A pointer to member of B can be converted to a pointer to member of D,
1251 // where D is derived from B (C++ 4.11p2).
1252 QualType FromClass(FromTypePtr->getClass(), 0);
1253 QualType ToClass(ToTypePtr->getClass(), 0);
1254 // FIXME: What happens when these are dependent? Is this function even called?
1255
1256 if (IsDerivedFrom(ToClass, FromClass)) {
1257 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1258 ToClass.getTypePtr());
1259 return true;
1260 }
1261
1262 return false;
1263}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001264
Sebastian Redl72b597d2009-01-25 19:43:20 +00001265/// CheckMemberPointerConversion - Check the member pointer conversion from the
1266/// expression From to the type ToType. This routine checks for ambiguous or
1267/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1268/// for which IsMemberPointerConversion has already returned true. It returns
1269/// true and produces a diagnostic if there was an error, or returns false
1270/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001271bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001272 CastExpr::CastKind &Kind,
1273 bool IgnoreBaseAccess) {
1274 (void)IgnoreBaseAccess;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001275 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001276 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001277 if (!FromPtrType) {
1278 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001279 assert(From->isNullPointerConstant(Context,
1280 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001281 "Expr must be null pointer constant!");
1282 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001283 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001284 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001285
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001286 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001287 assert(ToPtrType && "No member pointer cast has a target type "
1288 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001289
Sebastian Redled8f2002009-01-28 18:33:18 +00001290 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1291 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001292
Sebastian Redled8f2002009-01-28 18:33:18 +00001293 // FIXME: What about dependent types?
1294 assert(FromClass->isRecordType() && "Pointer into non-class.");
1295 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001296
Douglas Gregor36d1b142009-10-06 17:59:45 +00001297 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1298 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001299 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1300 assert(DerivationOkay &&
1301 "Should not have been called if derivation isn't OK.");
1302 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001303
Sebastian Redled8f2002009-01-28 18:33:18 +00001304 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1305 getUnqualifiedType())) {
1306 // Derivation is ambiguous. Redo the check to find the exact paths.
1307 Paths.clear();
1308 Paths.setRecordingPaths(true);
1309 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1310 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1311 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001312
Sebastian Redled8f2002009-01-28 18:33:18 +00001313 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1314 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1315 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1316 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001317 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001318
Douglas Gregor89ee6822009-02-28 01:32:25 +00001319 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001320 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1321 << FromClass << ToClass << QualType(VBase, 0)
1322 << From->getSourceRange();
1323 return true;
1324 }
1325
Anders Carlssond7923c62009-08-22 23:33:40 +00001326 // Must be a base to derived member conversion.
1327 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001328 return false;
1329}
1330
Douglas Gregor9a657932008-10-21 23:43:52 +00001331/// IsQualificationConversion - Determines whether the conversion from
1332/// an rvalue of type FromType to ToType is a qualification conversion
1333/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001334bool
1335Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001336 FromType = Context.getCanonicalType(FromType);
1337 ToType = Context.getCanonicalType(ToType);
1338
1339 // If FromType and ToType are the same type, this is not a
1340 // qualification conversion.
1341 if (FromType == ToType)
1342 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001343
Douglas Gregor9a657932008-10-21 23:43:52 +00001344 // (C++ 4.4p4):
1345 // A conversion can add cv-qualifiers at levels other than the first
1346 // in multi-level pointers, subject to the following rules: [...]
1347 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001348 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001349 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001350 // Within each iteration of the loop, we check the qualifiers to
1351 // determine if this still looks like a qualification
1352 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001353 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001354 // until there are no more pointers or pointers-to-members left to
1355 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001356 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001357
1358 // -- for every j > 0, if const is in cv 1,j then const is in cv
1359 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001360 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001361 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001362
Douglas Gregor9a657932008-10-21 23:43:52 +00001363 // -- if the cv 1,j and cv 2,j are different, then const is in
1364 // every cv for 0 < k < j.
1365 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001366 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001367 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001368
Douglas Gregor9a657932008-10-21 23:43:52 +00001369 // Keep track of whether all prior cv-qualifiers in the "to" type
1370 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001371 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001372 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001373 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001374
1375 // We are left with FromType and ToType being the pointee types
1376 // after unwrapping the original FromType and ToType the same number
1377 // of types. If we unwrapped any pointers, and if FromType and
1378 // ToType have the same unqualified type (since we checked
1379 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001380 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001381}
1382
Douglas Gregor576e98c2009-01-30 23:27:23 +00001383/// Determines whether there is a user-defined conversion sequence
1384/// (C++ [over.ics.user]) that converts expression From to the type
1385/// ToType. If such a conversion exists, User will contain the
1386/// user-defined conversion sequence that performs such a conversion
1387/// and this routine will return true. Otherwise, this routine returns
1388/// false and User is unspecified.
1389///
1390/// \param AllowConversionFunctions true if the conversion should
1391/// consider conversion functions at all. If false, only constructors
1392/// will be considered.
1393///
1394/// \param AllowExplicit true if the conversion should consider C++0x
1395/// "explicit" conversion functions as well as non-explicit conversion
1396/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001397///
1398/// \param ForceRValue true if the expression should be treated as an rvalue
1399/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001400/// \param UserCast true if looking for user defined conversion for a static
1401/// cast.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001402Sema::OverloadingResult Sema::IsUserDefinedConversion(
1403 Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001404 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001405 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001406 bool AllowConversionFunctions,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001407 bool AllowExplicit, bool ForceRValue,
1408 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001409 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001410 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1411 // We're not going to find any constructors.
1412 } else if (CXXRecordDecl *ToRecordDecl
1413 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001414 // C++ [over.match.ctor]p1:
1415 // When objects of class type are direct-initialized (8.5), or
1416 // copy-initialized from an expression of the same or a
1417 // derived class type (8.5), overload resolution selects the
1418 // constructor. [...] For copy-initialization, the candidate
1419 // functions are all the converting constructors (12.3.1) of
1420 // that class. The argument list is the expression-list within
1421 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001422 bool SuppressUserConversions = !UserCast;
1423 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1424 IsDerivedFrom(From->getType(), ToType)) {
1425 SuppressUserConversions = false;
1426 AllowConversionFunctions = false;
1427 }
1428
Mike Stump11289f42009-09-09 15:08:12 +00001429 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001430 = Context.DeclarationNames.getCXXConstructorName(
1431 Context.getCanonicalType(ToType).getUnqualifiedType());
1432 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001433 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001434 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001435 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001436 // Find the constructor (which may be a template).
1437 CXXConstructorDecl *Constructor = 0;
1438 FunctionTemplateDecl *ConstructorTmpl
1439 = dyn_cast<FunctionTemplateDecl>(*Con);
1440 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001441 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001442 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1443 else
1444 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001445
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001446 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001447 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001448 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00001449 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1450 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001451 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001452 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001453 // Allow one user-defined conversion when user specifies a
1454 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001455 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001456 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001457 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001458 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001459 }
1460 }
1461
Douglas Gregor576e98c2009-01-30 23:27:23 +00001462 if (!AllowConversionFunctions) {
1463 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001464 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1465 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001466 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001467 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001468 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001469 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001470 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001471 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1472 // Add all of the conversion functions as candidates.
John McCalld14a8642009-11-21 08:51:07 +00001473 const UnresolvedSet *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001474 = FromRecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00001475 for (UnresolvedSet::iterator I = Conversions->begin(),
1476 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00001477 NamedDecl *D = *I;
1478 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1479 if (isa<UsingShadowDecl>(D))
1480 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1481
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001482 CXXConversionDecl *Conv;
1483 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001484 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001485 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1486 else
John McCalld14a8642009-11-21 08:51:07 +00001487 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001488
1489 if (AllowExplicit || !Conv->isExplicit()) {
1490 if (ConvTemplate)
John McCall6e9f8f62009-12-03 04:06:58 +00001491 AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1492 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001493 else
John McCall6e9f8f62009-12-03 04:06:58 +00001494 AddConversionCandidate(Conv, ActingContext, From, ToType,
1495 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001496 }
1497 }
1498 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001499 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001500
1501 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001502 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001503 case OR_Success:
1504 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001505 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001506 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1507 // C++ [over.ics.user]p1:
1508 // If the user-defined conversion is specified by a
1509 // constructor (12.3.1), the initial standard conversion
1510 // sequence converts the source type to the type required by
1511 // the argument of the constructor.
1512 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001513 QualType ThisType = Constructor->getThisType(Context);
Fariborz Jahanian55824512009-11-06 00:23:08 +00001514 if (Best->Conversions[0].ConversionKind ==
1515 ImplicitConversionSequence::EllipsisConversion)
1516 User.EllipsisConversion = true;
1517 else {
1518 User.Before = Best->Conversions[0].Standard;
1519 User.EllipsisConversion = false;
1520 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001521 User.ConversionFunction = Constructor;
1522 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001523 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001524 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001525 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001526 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001527 } else if (CXXConversionDecl *Conversion
1528 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1529 // C++ [over.ics.user]p1:
1530 //
1531 // [...] If the user-defined conversion is specified by a
1532 // conversion function (12.3.2), the initial standard
1533 // conversion sequence converts the source type to the
1534 // implicit object parameter of the conversion function.
1535 User.Before = Best->Conversions[0].Standard;
1536 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001537 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001538
1539 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001540 // The second standard conversion sequence converts the
1541 // result of the user-defined conversion to the target type
1542 // for the sequence. Since an implicit conversion sequence
1543 // is an initialization, the special rules for
1544 // initialization by user-defined conversion apply when
1545 // selecting the best user-defined conversion for a
1546 // user-defined conversion sequence (see 13.3.3 and
1547 // 13.3.3.1).
1548 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001549 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001550 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001551 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001552 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001553 }
Mike Stump11289f42009-09-09 15:08:12 +00001554
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001555 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001556 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001557 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001558 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001559 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001560
1561 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001562 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001563 }
1564
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001565 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001566}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001567
1568bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001569Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001570 ImplicitConversionSequence ICS;
1571 OverloadCandidateSet CandidateSet;
1572 OverloadingResult OvResult =
1573 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1574 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001575 if (OvResult == OR_Ambiguous)
1576 Diag(From->getSourceRange().getBegin(),
1577 diag::err_typecheck_ambiguous_condition)
1578 << From->getType() << ToType << From->getSourceRange();
1579 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1580 Diag(From->getSourceRange().getBegin(),
1581 diag::err_typecheck_nonviable_condition)
1582 << From->getType() << ToType << From->getSourceRange();
1583 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001584 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00001585 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001586 return true;
1587}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001588
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001589/// CompareImplicitConversionSequences - Compare two implicit
1590/// conversion sequences to determine whether one is better than the
1591/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001592ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001593Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1594 const ImplicitConversionSequence& ICS2)
1595{
1596 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1597 // conversion sequences (as defined in 13.3.3.1)
1598 // -- a standard conversion sequence (13.3.3.1.1) is a better
1599 // conversion sequence than a user-defined conversion sequence or
1600 // an ellipsis conversion sequence, and
1601 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1602 // conversion sequence than an ellipsis conversion sequence
1603 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001604 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001605 if (ICS1.ConversionKind < ICS2.ConversionKind)
1606 return ImplicitConversionSequence::Better;
1607 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1608 return ImplicitConversionSequence::Worse;
1609
1610 // Two implicit conversion sequences of the same form are
1611 // indistinguishable conversion sequences unless one of the
1612 // following rules apply: (C++ 13.3.3.2p3):
1613 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1614 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001615 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001616 ImplicitConversionSequence::UserDefinedConversion) {
1617 // User-defined conversion sequence U1 is a better conversion
1618 // sequence than another user-defined conversion sequence U2 if
1619 // they contain the same user-defined conversion function or
1620 // constructor and if the second standard conversion sequence of
1621 // U1 is better than the second standard conversion sequence of
1622 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001623 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001624 ICS2.UserDefined.ConversionFunction)
1625 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1626 ICS2.UserDefined.After);
1627 }
1628
1629 return ImplicitConversionSequence::Indistinguishable;
1630}
1631
1632/// CompareStandardConversionSequences - Compare two standard
1633/// conversion sequences to determine whether one is better than the
1634/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001635ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001636Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1637 const StandardConversionSequence& SCS2)
1638{
1639 // Standard conversion sequence S1 is a better conversion sequence
1640 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1641
1642 // -- S1 is a proper subsequence of S2 (comparing the conversion
1643 // sequences in the canonical form defined by 13.3.3.1.1,
1644 // excluding any Lvalue Transformation; the identity conversion
1645 // sequence is considered to be a subsequence of any
1646 // non-identity conversion sequence) or, if not that,
1647 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1648 // Neither is a proper subsequence of the other. Do nothing.
1649 ;
1650 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1651 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001652 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001653 SCS1.Third == ICK_Identity))
1654 // SCS1 is a proper subsequence of SCS2.
1655 return ImplicitConversionSequence::Better;
1656 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1657 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001658 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001659 SCS2.Third == ICK_Identity))
1660 // SCS2 is a proper subsequence of SCS1.
1661 return ImplicitConversionSequence::Worse;
1662
1663 // -- the rank of S1 is better than the rank of S2 (by the rules
1664 // defined below), or, if not that,
1665 ImplicitConversionRank Rank1 = SCS1.getRank();
1666 ImplicitConversionRank Rank2 = SCS2.getRank();
1667 if (Rank1 < Rank2)
1668 return ImplicitConversionSequence::Better;
1669 else if (Rank2 < Rank1)
1670 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001671
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001672 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1673 // are indistinguishable unless one of the following rules
1674 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001675
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001676 // A conversion that is not a conversion of a pointer, or
1677 // pointer to member, to bool is better than another conversion
1678 // that is such a conversion.
1679 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1680 return SCS2.isPointerConversionToBool()
1681 ? ImplicitConversionSequence::Better
1682 : ImplicitConversionSequence::Worse;
1683
Douglas Gregor5c407d92008-10-23 00:40:37 +00001684 // C++ [over.ics.rank]p4b2:
1685 //
1686 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001687 // conversion of B* to A* is better than conversion of B* to
1688 // void*, and conversion of A* to void* is better than conversion
1689 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001690 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001691 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001692 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001693 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001694 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1695 // Exactly one of the conversion sequences is a conversion to
1696 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001697 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1698 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001699 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1700 // Neither conversion sequence converts to a void pointer; compare
1701 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001702 if (ImplicitConversionSequence::CompareKind DerivedCK
1703 = CompareDerivedToBaseConversions(SCS1, SCS2))
1704 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001705 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1706 // Both conversion sequences are conversions to void
1707 // pointers. Compare the source types to determine if there's an
1708 // inheritance relationship in their sources.
1709 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1710 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1711
1712 // Adjust the types we're converting from via the array-to-pointer
1713 // conversion, if we need to.
1714 if (SCS1.First == ICK_Array_To_Pointer)
1715 FromType1 = Context.getArrayDecayedType(FromType1);
1716 if (SCS2.First == ICK_Array_To_Pointer)
1717 FromType2 = Context.getArrayDecayedType(FromType2);
1718
Mike Stump11289f42009-09-09 15:08:12 +00001719 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001720 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001721 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001722 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001723
1724 if (IsDerivedFrom(FromPointee2, FromPointee1))
1725 return ImplicitConversionSequence::Better;
1726 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1727 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001728
1729 // Objective-C++: If one interface is more specific than the
1730 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001731 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1732 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001733 if (FromIface1 && FromIface1) {
1734 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1735 return ImplicitConversionSequence::Better;
1736 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1737 return ImplicitConversionSequence::Worse;
1738 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001739 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001740
1741 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1742 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001743 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001744 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001745 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001746
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001747 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001748 // C++0x [over.ics.rank]p3b4:
1749 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1750 // implicit object parameter of a non-static member function declared
1751 // without a ref-qualifier, and S1 binds an rvalue reference to an
1752 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001753 // FIXME: We don't know if we're dealing with the implicit object parameter,
1754 // or if the member function in this case has a ref qualifier.
1755 // (Of course, we don't have ref qualifiers yet.)
1756 if (SCS1.RRefBinding != SCS2.RRefBinding)
1757 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1758 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001759
1760 // C++ [over.ics.rank]p3b4:
1761 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1762 // which the references refer are the same type except for
1763 // top-level cv-qualifiers, and the type to which the reference
1764 // initialized by S2 refers is more cv-qualified than the type
1765 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001766 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1767 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001768 T1 = Context.getCanonicalType(T1);
1769 T2 = Context.getCanonicalType(T2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001770 if (Context.hasSameUnqualifiedType(T1, T2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001771 if (T2.isMoreQualifiedThan(T1))
1772 return ImplicitConversionSequence::Better;
1773 else if (T1.isMoreQualifiedThan(T2))
1774 return ImplicitConversionSequence::Worse;
1775 }
1776 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001777
1778 return ImplicitConversionSequence::Indistinguishable;
1779}
1780
1781/// CompareQualificationConversions - Compares two standard conversion
1782/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001783/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1784ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001785Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001786 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001787 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001788 // -- S1 and S2 differ only in their qualification conversion and
1789 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1790 // cv-qualification signature of type T1 is a proper subset of
1791 // the cv-qualification signature of type T2, and S1 is not the
1792 // deprecated string literal array-to-pointer conversion (4.2).
1793 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1794 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1795 return ImplicitConversionSequence::Indistinguishable;
1796
1797 // FIXME: the example in the standard doesn't use a qualification
1798 // conversion (!)
1799 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1800 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1801 T1 = Context.getCanonicalType(T1);
1802 T2 = Context.getCanonicalType(T2);
1803
1804 // If the types are the same, we won't learn anything by unwrapped
1805 // them.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001806 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001807 return ImplicitConversionSequence::Indistinguishable;
1808
Mike Stump11289f42009-09-09 15:08:12 +00001809 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001810 = ImplicitConversionSequence::Indistinguishable;
1811 while (UnwrapSimilarPointerTypes(T1, T2)) {
1812 // Within each iteration of the loop, we check the qualifiers to
1813 // determine if this still looks like a qualification
1814 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001815 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001816 // until there are no more pointers or pointers-to-members left
1817 // to unwrap. This essentially mimics what
1818 // IsQualificationConversion does, but here we're checking for a
1819 // strict subset of qualifiers.
1820 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1821 // The qualifiers are the same, so this doesn't tell us anything
1822 // about how the sequences rank.
1823 ;
1824 else if (T2.isMoreQualifiedThan(T1)) {
1825 // T1 has fewer qualifiers, so it could be the better sequence.
1826 if (Result == ImplicitConversionSequence::Worse)
1827 // Neither has qualifiers that are a subset of the other's
1828 // qualifiers.
1829 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001830
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001831 Result = ImplicitConversionSequence::Better;
1832 } else if (T1.isMoreQualifiedThan(T2)) {
1833 // T2 has fewer qualifiers, so it could be the better sequence.
1834 if (Result == ImplicitConversionSequence::Better)
1835 // Neither has qualifiers that are a subset of the other's
1836 // qualifiers.
1837 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001838
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001839 Result = ImplicitConversionSequence::Worse;
1840 } else {
1841 // Qualifiers are disjoint.
1842 return ImplicitConversionSequence::Indistinguishable;
1843 }
1844
1845 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001846 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001847 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001848 }
1849
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001850 // Check that the winning standard conversion sequence isn't using
1851 // the deprecated string literal array to pointer conversion.
1852 switch (Result) {
1853 case ImplicitConversionSequence::Better:
1854 if (SCS1.Deprecated)
1855 Result = ImplicitConversionSequence::Indistinguishable;
1856 break;
1857
1858 case ImplicitConversionSequence::Indistinguishable:
1859 break;
1860
1861 case ImplicitConversionSequence::Worse:
1862 if (SCS2.Deprecated)
1863 Result = ImplicitConversionSequence::Indistinguishable;
1864 break;
1865 }
1866
1867 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001868}
1869
Douglas Gregor5c407d92008-10-23 00:40:37 +00001870/// CompareDerivedToBaseConversions - Compares two standard conversion
1871/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001872/// various kinds of derived-to-base conversions (C++
1873/// [over.ics.rank]p4b3). As part of these checks, we also look at
1874/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001875ImplicitConversionSequence::CompareKind
1876Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1877 const StandardConversionSequence& SCS2) {
1878 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1879 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1880 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1881 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1882
1883 // Adjust the types we're converting from via the array-to-pointer
1884 // conversion, if we need to.
1885 if (SCS1.First == ICK_Array_To_Pointer)
1886 FromType1 = Context.getArrayDecayedType(FromType1);
1887 if (SCS2.First == ICK_Array_To_Pointer)
1888 FromType2 = Context.getArrayDecayedType(FromType2);
1889
1890 // Canonicalize all of the types.
1891 FromType1 = Context.getCanonicalType(FromType1);
1892 ToType1 = Context.getCanonicalType(ToType1);
1893 FromType2 = Context.getCanonicalType(FromType2);
1894 ToType2 = Context.getCanonicalType(ToType2);
1895
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001896 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001897 //
1898 // If class B is derived directly or indirectly from class A and
1899 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001900 //
1901 // For Objective-C, we let A, B, and C also be Objective-C
1902 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001903
1904 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001905 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001906 SCS2.Second == ICK_Pointer_Conversion &&
1907 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1908 FromType1->isPointerType() && FromType2->isPointerType() &&
1909 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001910 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001911 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001912 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001913 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001914 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001915 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001916 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001917 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001918
John McCall9dd450b2009-09-21 23:43:11 +00001919 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1920 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1921 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1922 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001923
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001924 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001925 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1926 if (IsDerivedFrom(ToPointee1, ToPointee2))
1927 return ImplicitConversionSequence::Better;
1928 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1929 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001930
1931 if (ToIface1 && ToIface2) {
1932 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1933 return ImplicitConversionSequence::Better;
1934 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1935 return ImplicitConversionSequence::Worse;
1936 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001937 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001938
1939 // -- conversion of B* to A* is better than conversion of C* to A*,
1940 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1941 if (IsDerivedFrom(FromPointee2, FromPointee1))
1942 return ImplicitConversionSequence::Better;
1943 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1944 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001945
Douglas Gregor237f96c2008-11-26 23:31:11 +00001946 if (FromIface1 && FromIface2) {
1947 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1948 return ImplicitConversionSequence::Better;
1949 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1950 return ImplicitConversionSequence::Worse;
1951 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001952 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001953 }
1954
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001955 // Compare based on reference bindings.
1956 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1957 SCS1.Second == ICK_Derived_To_Base) {
1958 // -- binding of an expression of type C to a reference of type
1959 // B& is better than binding an expression of type C to a
1960 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001961 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1962 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001963 if (IsDerivedFrom(ToType1, ToType2))
1964 return ImplicitConversionSequence::Better;
1965 else if (IsDerivedFrom(ToType2, ToType1))
1966 return ImplicitConversionSequence::Worse;
1967 }
1968
Douglas Gregor2fe98832008-11-03 19:09:14 +00001969 // -- binding of an expression of type B to a reference of type
1970 // A& is better than binding an expression of type C to a
1971 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001972 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1973 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001974 if (IsDerivedFrom(FromType2, FromType1))
1975 return ImplicitConversionSequence::Better;
1976 else if (IsDerivedFrom(FromType1, FromType2))
1977 return ImplicitConversionSequence::Worse;
1978 }
1979 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001980
1981 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001982 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1983 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1984 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1985 const MemberPointerType * FromMemPointer1 =
1986 FromType1->getAs<MemberPointerType>();
1987 const MemberPointerType * ToMemPointer1 =
1988 ToType1->getAs<MemberPointerType>();
1989 const MemberPointerType * FromMemPointer2 =
1990 FromType2->getAs<MemberPointerType>();
1991 const MemberPointerType * ToMemPointer2 =
1992 ToType2->getAs<MemberPointerType>();
1993 const Type *FromPointeeType1 = FromMemPointer1->getClass();
1994 const Type *ToPointeeType1 = ToMemPointer1->getClass();
1995 const Type *FromPointeeType2 = FromMemPointer2->getClass();
1996 const Type *ToPointeeType2 = ToMemPointer2->getClass();
1997 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1998 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
1999 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2000 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002001 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002002 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2003 if (IsDerivedFrom(ToPointee1, ToPointee2))
2004 return ImplicitConversionSequence::Worse;
2005 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2006 return ImplicitConversionSequence::Better;
2007 }
2008 // conversion of B::* to C::* is better than conversion of A::* to C::*
2009 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2010 if (IsDerivedFrom(FromPointee1, FromPointee2))
2011 return ImplicitConversionSequence::Better;
2012 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2013 return ImplicitConversionSequence::Worse;
2014 }
2015 }
2016
Douglas Gregor2fe98832008-11-03 19:09:14 +00002017 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2018 SCS1.Second == ICK_Derived_To_Base) {
2019 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002020 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2021 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002022 if (IsDerivedFrom(ToType1, ToType2))
2023 return ImplicitConversionSequence::Better;
2024 else if (IsDerivedFrom(ToType2, ToType1))
2025 return ImplicitConversionSequence::Worse;
2026 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002027
Douglas Gregor2fe98832008-11-03 19:09:14 +00002028 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002029 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2030 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002031 if (IsDerivedFrom(FromType2, FromType1))
2032 return ImplicitConversionSequence::Better;
2033 else if (IsDerivedFrom(FromType1, FromType2))
2034 return ImplicitConversionSequence::Worse;
2035 }
2036 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002037
Douglas Gregor5c407d92008-10-23 00:40:37 +00002038 return ImplicitConversionSequence::Indistinguishable;
2039}
2040
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002041/// TryCopyInitialization - Try to copy-initialize a value of type
2042/// ToType from the expression From. Return the implicit conversion
2043/// sequence required to pass this argument, which may be a bad
2044/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002045/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002046/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2047/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002048ImplicitConversionSequence
2049Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002050 bool SuppressUserConversions, bool ForceRValue,
2051 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002052 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002053 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00002054 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002055 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002056 SuppressUserConversions,
2057 /*AllowExplicit=*/false,
2058 ForceRValue,
2059 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002060 return ICS;
2061 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002062 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002063 SuppressUserConversions,
2064 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002065 ForceRValue,
2066 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002067 }
2068}
2069
Sebastian Redl42e92c42009-04-12 17:16:29 +00002070/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2071/// the expression @p From. Returns true (and emits a diagnostic) if there was
2072/// an error, returns false if the initialization succeeded. Elidable should
2073/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2074/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002075bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002076 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002077 if (!getLangOptions().CPlusPlus) {
2078 // In C, argument passing is the same as performing an assignment.
2079 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002080
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002081 AssignConvertType ConvTy =
2082 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002083 if (ConvTy != Compatible &&
2084 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2085 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002086
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002087 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2088 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002089 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002090
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002091 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002092 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002093 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002094 /*SuppressUserConversions=*/false,
2095 /*AllowExplicit=*/false,
2096 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002097
Sebastian Redl42e92c42009-04-12 17:16:29 +00002098 if (!PerformImplicitConversion(From, ToType, Flavor,
2099 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002100 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002101 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002102 return Diag(From->getSourceRange().getBegin(),
2103 diag::err_typecheck_convert_incompatible)
2104 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002105 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002106}
2107
Douglas Gregor436424c2008-11-18 23:14:02 +00002108/// TryObjectArgumentInitialization - Try to initialize the object
2109/// parameter of the given member function (@c Method) from the
2110/// expression @p From.
2111ImplicitConversionSequence
John McCall6e9f8f62009-12-03 04:06:58 +00002112Sema::TryObjectArgumentInitialization(QualType FromType,
2113 CXXMethodDecl *Method,
2114 CXXRecordDecl *ActingContext) {
2115 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002116 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2117 // const volatile object.
2118 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2119 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2120 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002121
2122 // Set up the conversion sequence as a "bad" conversion, to allow us
2123 // to exit early.
2124 ImplicitConversionSequence ICS;
2125 ICS.Standard.setAsIdentityConversion();
2126 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2127
2128 // We need to have an object of class type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002129 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002130 FromType = PT->getPointeeType();
2131
2132 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002133
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002134 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002135 // where X is the class of which the function is a member
2136 // (C++ [over.match.funcs]p4). However, when finding an implicit
2137 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002138 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002139 // (C++ [over.match.funcs]p5). We perform a simplified version of
2140 // reference binding here, that allows class rvalues to bind to
2141 // non-constant references.
2142
2143 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2144 // with the implicit object parameter (C++ [over.match.funcs]p5).
2145 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002146 if (ImplicitParamType.getCVRQualifiers()
2147 != FromTypeCanon.getLocalCVRQualifiers() &&
Douglas Gregor01df9462009-11-05 00:07:36 +00002148 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor436424c2008-11-18 23:14:02 +00002149 return ICS;
2150
2151 // Check that we have either the same type or a derived type. It
2152 // affects the conversion rank.
2153 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002154 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002155 ICS.Standard.Second = ICK_Identity;
2156 else if (IsDerivedFrom(FromType, ClassType))
2157 ICS.Standard.Second = ICK_Derived_To_Base;
2158 else
2159 return ICS;
2160
2161 // Success. Mark this as a reference binding.
2162 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2163 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2164 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2165 ICS.Standard.ReferenceBinding = true;
2166 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002167 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002168 return ICS;
2169}
2170
2171/// PerformObjectArgumentInitialization - Perform initialization of
2172/// the implicit object parameter for the given Method with the given
2173/// expression.
2174bool
2175Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002176 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002177 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002178 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002179
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002180 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002181 FromRecordType = PT->getPointeeType();
2182 DestType = Method->getThisType(Context);
2183 } else {
2184 FromRecordType = From->getType();
2185 DestType = ImplicitParamRecordType;
2186 }
2187
John McCall6e9f8f62009-12-03 04:06:58 +00002188 // Note that we always use the true parent context when performing
2189 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002190 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002191 = TryObjectArgumentInitialization(From->getType(), Method,
2192 Method->getParent());
Douglas Gregor436424c2008-11-18 23:14:02 +00002193 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2194 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002195 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002196 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002197
Douglas Gregor436424c2008-11-18 23:14:02 +00002198 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002199 CheckDerivedToBaseConversion(FromRecordType,
2200 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002201 From->getSourceRange().getBegin(),
2202 From->getSourceRange()))
2203 return true;
2204
Mike Stump11289f42009-09-09 15:08:12 +00002205 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002206 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002207 return false;
2208}
2209
Douglas Gregor5fb53972009-01-14 15:45:31 +00002210/// TryContextuallyConvertToBool - Attempt to contextually convert the
2211/// expression From to bool (C++0x [conv]p3).
2212ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002213 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002214 // FIXME: Are these flags correct?
2215 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002216 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002217 /*ForceRValue=*/false,
2218 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002219}
2220
2221/// PerformContextuallyConvertToBool - Perform a contextual conversion
2222/// of the expression From to bool (C++0x [conv]p3).
2223bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2224 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2225 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2226 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002227
Fariborz Jahanian76197412009-11-18 18:26:29 +00002228 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002229 return Diag(From->getSourceRange().getBegin(),
2230 diag::err_typecheck_bool_condition)
2231 << From->getType() << From->getSourceRange();
2232 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002233}
2234
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002235/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002236/// candidate functions, using the given function call arguments. If
2237/// @p SuppressUserConversions, then don't allow user-defined
2238/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002239/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2240/// hacky way to implement the overloading rules for elidable copy
2241/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002242///
2243/// \para PartialOverloading true if we are performing "partial" overloading
2244/// based on an incomplete set of function arguments. This feature is used by
2245/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002246void
2247Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002248 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002249 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002250 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002251 bool ForceRValue,
2252 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002253 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002254 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002255 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002256 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002257 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002258 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002259 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002260
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002261 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002262 if (!isa<CXXConstructorDecl>(Method)) {
2263 // If we get here, it's because we're calling a member function
2264 // that is named without a member access expression (e.g.,
2265 // "this->f") that was either written explicitly or created
2266 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002267 // function, e.g., X::f(). We use an empty type for the implied
2268 // object argument (C++ [over.call.func]p3), and the acting context
2269 // is irrelevant.
2270 AddMethodCandidate(Method, Method->getParent(),
2271 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002272 SuppressUserConversions, ForceRValue);
2273 return;
2274 }
2275 // We treat a constructor like a non-member function, since its object
2276 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002277 }
2278
Douglas Gregorff7028a2009-11-13 23:59:09 +00002279 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002280 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002281
Douglas Gregor27381f32009-11-23 12:27:39 +00002282 // Overload resolution is always an unevaluated context.
2283 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2284
Douglas Gregorffe14e32009-11-14 01:20:54 +00002285 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2286 // C++ [class.copy]p3:
2287 // A member function template is never instantiated to perform the copy
2288 // of a class object to an object of its class type.
2289 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2290 if (NumArgs == 1 &&
2291 Constructor->isCopyConstructorLikeSpecialization() &&
2292 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2293 return;
2294 }
2295
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002296 // Add this candidate
2297 CandidateSet.push_back(OverloadCandidate());
2298 OverloadCandidate& Candidate = CandidateSet.back();
2299 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002300 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002301 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002302 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002303
2304 unsigned NumArgsInProto = Proto->getNumArgs();
2305
2306 // (C++ 13.3.2p2): A candidate function having fewer than m
2307 // parameters is viable only if it has an ellipsis in its parameter
2308 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002309 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2310 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002311 Candidate.Viable = false;
2312 return;
2313 }
2314
2315 // (C++ 13.3.2p2): A candidate function having more than m parameters
2316 // is viable only if the (m+1)st parameter has a default argument
2317 // (8.3.6). For the purposes of overload resolution, the
2318 // parameter list is truncated on the right, so that there are
2319 // exactly m parameters.
2320 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002321 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002322 // Not enough arguments.
2323 Candidate.Viable = false;
2324 return;
2325 }
2326
2327 // Determine the implicit conversion sequences for each of the
2328 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002329 Candidate.Conversions.resize(NumArgs);
2330 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2331 if (ArgIdx < NumArgsInProto) {
2332 // (C++ 13.3.2p3): for F to be a viable function, there shall
2333 // exist for each argument an implicit conversion sequence
2334 // (13.3.3.1) that converts that argument to the corresponding
2335 // parameter of F.
2336 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002337 Candidate.Conversions[ArgIdx]
2338 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002339 SuppressUserConversions, ForceRValue,
2340 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002341 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002342 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002343 // 13.3.3.1-p10 If several different sequences of conversions exist that
2344 // each convert the argument to the parameter type, the implicit conversion
2345 // sequence associated with the parameter is defined to be the unique conversion
2346 // sequence designated the ambiguous conversion sequence. For the purpose of
2347 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2348 // conversion sequence is treated as a user-defined sequence that is
2349 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002350 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002351 Candidate.Conversions[ArgIdx].ConversionKind =
2352 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002353 // Set the conversion function to one of them. As due to ambiguity,
2354 // they carry the same weight and is needed for overload resolution
2355 // later.
2356 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2357 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2358 }
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002359 else {
2360 Candidate.Viable = false;
2361 break;
2362 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002363 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002364 } else {
2365 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2366 // argument for which there is no corresponding parameter is
2367 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002368 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002369 = ImplicitConversionSequence::EllipsisConversion;
2370 }
2371 }
2372}
2373
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002374/// \brief Add all of the function declarations in the given function set to
2375/// the overload canddiate set.
2376void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2377 Expr **Args, unsigned NumArgs,
2378 OverloadCandidateSet& CandidateSet,
2379 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002380 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002381 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002382 F != FEnd; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002383 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002384 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2385 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2386 AddMethodCandidate(cast<CXXMethodDecl>(FD),
John McCall6e9f8f62009-12-03 04:06:58 +00002387 cast<CXXMethodDecl>(FD)->getParent(),
2388 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002389 CandidateSet, SuppressUserConversions);
2390 else
2391 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2392 SuppressUserConversions);
2393 } else {
2394 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2395 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2396 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2397 AddMethodTemplateCandidate(FunTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002398 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002399 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002400 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002401 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002402 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002403 else
2404 AddTemplateOverloadCandidate(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002405 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002406 Args, NumArgs, CandidateSet,
2407 SuppressUserConversions);
2408 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002409 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002410}
2411
John McCallf0f1cf02009-11-17 07:50:12 +00002412/// AddMethodCandidate - Adds a named decl (which is some kind of
2413/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002414void Sema::AddMethodCandidate(NamedDecl *Decl,
2415 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002416 Expr **Args, unsigned NumArgs,
2417 OverloadCandidateSet& CandidateSet,
2418 bool SuppressUserConversions, bool ForceRValue) {
2419
2420 // FIXME: use this
John McCall6e9f8f62009-12-03 04:06:58 +00002421 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002422
2423 if (isa<UsingShadowDecl>(Decl))
2424 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2425
2426 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2427 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2428 "Expected a member function template");
John McCall6e9f8f62009-12-03 04:06:58 +00002429 AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2430 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002431 CandidateSet,
2432 SuppressUserConversions,
2433 ForceRValue);
2434 } else {
John McCall6e9f8f62009-12-03 04:06:58 +00002435 AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2436 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002437 CandidateSet, SuppressUserConversions, ForceRValue);
2438 }
2439}
2440
Douglas Gregor436424c2008-11-18 23:14:02 +00002441/// AddMethodCandidate - Adds the given C++ member function to the set
2442/// of candidate functions, using the given function call arguments
2443/// and the object argument (@c Object). For example, in a call
2444/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2445/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2446/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002447/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2448/// a slightly hacky way to implement the overloading rules for elidable copy
2449/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002450void
John McCall6e9f8f62009-12-03 04:06:58 +00002451Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2452 QualType ObjectType, Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002453 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002454 bool SuppressUserConversions, bool ForceRValue) {
2455 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002456 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002457 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002458 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002459 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002460 assert(!isa<CXXConstructorDecl>(Method) &&
2461 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002462
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002463 if (!CandidateSet.isNewCandidate(Method))
2464 return;
2465
Douglas Gregor27381f32009-11-23 12:27:39 +00002466 // Overload resolution is always an unevaluated context.
2467 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2468
Douglas Gregor436424c2008-11-18 23:14:02 +00002469 // Add this candidate
2470 CandidateSet.push_back(OverloadCandidate());
2471 OverloadCandidate& Candidate = CandidateSet.back();
2472 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002473 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002474 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002475
2476 unsigned NumArgsInProto = Proto->getNumArgs();
2477
2478 // (C++ 13.3.2p2): A candidate function having fewer than m
2479 // parameters is viable only if it has an ellipsis in its parameter
2480 // list (8.3.5).
2481 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2482 Candidate.Viable = false;
2483 return;
2484 }
2485
2486 // (C++ 13.3.2p2): A candidate function having more than m parameters
2487 // is viable only if the (m+1)st parameter has a default argument
2488 // (8.3.6). For the purposes of overload resolution, the
2489 // parameter list is truncated on the right, so that there are
2490 // exactly m parameters.
2491 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2492 if (NumArgs < MinRequiredArgs) {
2493 // Not enough arguments.
2494 Candidate.Viable = false;
2495 return;
2496 }
2497
2498 Candidate.Viable = true;
2499 Candidate.Conversions.resize(NumArgs + 1);
2500
John McCall6e9f8f62009-12-03 04:06:58 +00002501 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002502 // The implicit object argument is ignored.
2503 Candidate.IgnoreObjectArgument = true;
2504 else {
2505 // Determine the implicit conversion sequence for the object
2506 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002507 Candidate.Conversions[0]
2508 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
Mike Stump11289f42009-09-09 15:08:12 +00002509 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002510 == ImplicitConversionSequence::BadConversion) {
2511 Candidate.Viable = false;
2512 return;
2513 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002514 }
2515
2516 // Determine the implicit conversion sequences for each of the
2517 // arguments.
2518 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2519 if (ArgIdx < NumArgsInProto) {
2520 // (C++ 13.3.2p3): for F to be a viable function, there shall
2521 // exist for each argument an implicit conversion sequence
2522 // (13.3.3.1) that converts that argument to the corresponding
2523 // parameter of F.
2524 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002525 Candidate.Conversions[ArgIdx + 1]
2526 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002527 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002528 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002529 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002530 == ImplicitConversionSequence::BadConversion) {
2531 Candidate.Viable = false;
2532 break;
2533 }
2534 } else {
2535 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2536 // argument for which there is no corresponding parameter is
2537 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002538 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002539 = ImplicitConversionSequence::EllipsisConversion;
2540 }
2541 }
2542}
2543
Douglas Gregor97628d62009-08-21 00:16:32 +00002544/// \brief Add a C++ member function template as a candidate to the candidate
2545/// set, using template argument deduction to produce an appropriate member
2546/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002547void
Douglas Gregor97628d62009-08-21 00:16:32 +00002548Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002549 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002550 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002551 QualType ObjectType,
2552 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002553 OverloadCandidateSet& CandidateSet,
2554 bool SuppressUserConversions,
2555 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002556 if (!CandidateSet.isNewCandidate(MethodTmpl))
2557 return;
2558
Douglas Gregor97628d62009-08-21 00:16:32 +00002559 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002560 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002561 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002562 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002563 // candidate functions in the usual way.113) A given name can refer to one
2564 // or more function templates and also to a set of overloaded non-template
2565 // functions. In such a case, the candidate functions generated from each
2566 // function template are combined with the set of non-template candidate
2567 // functions.
2568 TemplateDeductionInfo Info(Context);
2569 FunctionDecl *Specialization = 0;
2570 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002571 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002572 Args, NumArgs, Specialization, Info)) {
2573 // FIXME: Record what happened with template argument deduction, so
2574 // that we can give the user a beautiful diagnostic.
2575 (void)Result;
2576 return;
2577 }
Mike Stump11289f42009-09-09 15:08:12 +00002578
Douglas Gregor97628d62009-08-21 00:16:32 +00002579 // Add the function template specialization produced by template argument
2580 // deduction as a candidate.
2581 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002582 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002583 "Specialization is not a member function?");
John McCall6e9f8f62009-12-03 04:06:58 +00002584 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2585 ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002586 CandidateSet, SuppressUserConversions, ForceRValue);
2587}
2588
Douglas Gregor05155d82009-08-21 23:19:43 +00002589/// \brief Add a C++ function template specialization as a candidate
2590/// in the candidate set, using template argument deduction to produce
2591/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002592void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002593Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002594 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002595 Expr **Args, unsigned NumArgs,
2596 OverloadCandidateSet& CandidateSet,
2597 bool SuppressUserConversions,
2598 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002599 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2600 return;
2601
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002602 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002603 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002604 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002605 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002606 // candidate functions in the usual way.113) A given name can refer to one
2607 // or more function templates and also to a set of overloaded non-template
2608 // functions. In such a case, the candidate functions generated from each
2609 // function template are combined with the set of non-template candidate
2610 // functions.
2611 TemplateDeductionInfo Info(Context);
2612 FunctionDecl *Specialization = 0;
2613 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002614 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002615 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002616 // FIXME: Record what happened with template argument deduction, so
2617 // that we can give the user a beautiful diagnostic.
2618 (void)Result;
2619 return;
2620 }
Mike Stump11289f42009-09-09 15:08:12 +00002621
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002622 // Add the function template specialization produced by template argument
2623 // deduction as a candidate.
2624 assert(Specialization && "Missing function template specialization?");
2625 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2626 SuppressUserConversions, ForceRValue);
2627}
Mike Stump11289f42009-09-09 15:08:12 +00002628
Douglas Gregora1f013e2008-11-07 22:36:19 +00002629/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002630/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002631/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002632/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002633/// (which may or may not be the same type as the type that the
2634/// conversion function produces).
2635void
2636Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002637 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002638 Expr *From, QualType ToType,
2639 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002640 assert(!Conversion->getDescribedFunctionTemplate() &&
2641 "Conversion function templates use AddTemplateConversionCandidate");
2642
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002643 if (!CandidateSet.isNewCandidate(Conversion))
2644 return;
2645
Douglas Gregor27381f32009-11-23 12:27:39 +00002646 // Overload resolution is always an unevaluated context.
2647 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2648
Douglas Gregora1f013e2008-11-07 22:36:19 +00002649 // Add this candidate
2650 CandidateSet.push_back(OverloadCandidate());
2651 OverloadCandidate& Candidate = CandidateSet.back();
2652 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002653 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002654 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002655 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002656 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002657 = Conversion->getConversionType().getAsOpaquePtr();
2658 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2659
Douglas Gregor436424c2008-11-18 23:14:02 +00002660 // Determine the implicit conversion sequence for the implicit
2661 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002662 Candidate.Viable = true;
2663 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002664 Candidate.Conversions[0]
2665 = TryObjectArgumentInitialization(From->getType(), Conversion,
2666 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002667 // Conversion functions to a different type in the base class is visible in
2668 // the derived class. So, a derived to base conversion should not participate
2669 // in overload resolution.
2670 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2671 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002672 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002673 == ImplicitConversionSequence::BadConversion) {
2674 Candidate.Viable = false;
2675 return;
2676 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002677
2678 // We won't go through a user-define type conversion function to convert a
2679 // derived to base as such conversions are given Conversion Rank. They only
2680 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2681 QualType FromCanon
2682 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2683 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2684 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2685 Candidate.Viable = false;
2686 return;
2687 }
2688
Douglas Gregora1f013e2008-11-07 22:36:19 +00002689
2690 // To determine what the conversion from the result of calling the
2691 // conversion function to the type we're eventually trying to
2692 // convert to (ToType), we need to synthesize a call to the
2693 // conversion function and attempt copy initialization from it. This
2694 // makes sure that we get the right semantics with respect to
2695 // lvalues/rvalues and the type. Fortunately, we can allocate this
2696 // call on the stack and we don't need its arguments to be
2697 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002698 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002699 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002700 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002701 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002702 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002703
2704 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002705 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2706 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002707 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002708 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002709 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002710 ImplicitConversionSequence ICS =
2711 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002712 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002713 /*ForceRValue=*/false,
2714 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002715
Douglas Gregora1f013e2008-11-07 22:36:19 +00002716 switch (ICS.ConversionKind) {
2717 case ImplicitConversionSequence::StandardConversion:
2718 Candidate.FinalConversion = ICS.Standard;
2719 break;
2720
2721 case ImplicitConversionSequence::BadConversion:
2722 Candidate.Viable = false;
2723 break;
2724
2725 default:
Mike Stump11289f42009-09-09 15:08:12 +00002726 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002727 "Can only end up with a standard conversion sequence or failure");
2728 }
2729}
2730
Douglas Gregor05155d82009-08-21 23:19:43 +00002731/// \brief Adds a conversion function template specialization
2732/// candidate to the overload set, using template argument deduction
2733/// to deduce the template arguments of the conversion function
2734/// template from the type that we are converting to (C++
2735/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002736void
Douglas Gregor05155d82009-08-21 23:19:43 +00002737Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6e9f8f62009-12-03 04:06:58 +00002738 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002739 Expr *From, QualType ToType,
2740 OverloadCandidateSet &CandidateSet) {
2741 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2742 "Only conversion function templates permitted here");
2743
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002744 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2745 return;
2746
Douglas Gregor05155d82009-08-21 23:19:43 +00002747 TemplateDeductionInfo Info(Context);
2748 CXXConversionDecl *Specialization = 0;
2749 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002750 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002751 Specialization, Info)) {
2752 // FIXME: Record what happened with template argument deduction, so
2753 // that we can give the user a beautiful diagnostic.
2754 (void)Result;
2755 return;
2756 }
Mike Stump11289f42009-09-09 15:08:12 +00002757
Douglas Gregor05155d82009-08-21 23:19:43 +00002758 // Add the conversion function template specialization produced by
2759 // template argument deduction as a candidate.
2760 assert(Specialization && "Missing function template specialization?");
John McCall6e9f8f62009-12-03 04:06:58 +00002761 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002762}
2763
Douglas Gregorab7897a2008-11-19 22:57:39 +00002764/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2765/// converts the given @c Object to a function pointer via the
2766/// conversion function @c Conversion, and then attempts to call it
2767/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2768/// the type of function that we'll eventually be calling.
2769void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002770 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002771 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002772 QualType ObjectType,
2773 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002774 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002775 if (!CandidateSet.isNewCandidate(Conversion))
2776 return;
2777
Douglas Gregor27381f32009-11-23 12:27:39 +00002778 // Overload resolution is always an unevaluated context.
2779 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2780
Douglas Gregorab7897a2008-11-19 22:57:39 +00002781 CandidateSet.push_back(OverloadCandidate());
2782 OverloadCandidate& Candidate = CandidateSet.back();
2783 Candidate.Function = 0;
2784 Candidate.Surrogate = Conversion;
2785 Candidate.Viable = true;
2786 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002787 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002788 Candidate.Conversions.resize(NumArgs + 1);
2789
2790 // Determine the implicit conversion sequence for the implicit
2791 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002792 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002793 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
Douglas Gregorab7897a2008-11-19 22:57:39 +00002794 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2795 Candidate.Viable = false;
2796 return;
2797 }
2798
2799 // The first conversion is actually a user-defined conversion whose
2800 // first conversion is ObjectInit's standard conversion (which is
2801 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002802 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002803 = ImplicitConversionSequence::UserDefinedConversion;
2804 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002805 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002806 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002807 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002808 = Candidate.Conversions[0].UserDefined.Before;
2809 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2810
Mike Stump11289f42009-09-09 15:08:12 +00002811 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002812 unsigned NumArgsInProto = Proto->getNumArgs();
2813
2814 // (C++ 13.3.2p2): A candidate function having fewer than m
2815 // parameters is viable only if it has an ellipsis in its parameter
2816 // list (8.3.5).
2817 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2818 Candidate.Viable = false;
2819 return;
2820 }
2821
2822 // Function types don't have any default arguments, so just check if
2823 // we have enough arguments.
2824 if (NumArgs < NumArgsInProto) {
2825 // Not enough arguments.
2826 Candidate.Viable = false;
2827 return;
2828 }
2829
2830 // Determine the implicit conversion sequences for each of the
2831 // arguments.
2832 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2833 if (ArgIdx < NumArgsInProto) {
2834 // (C++ 13.3.2p3): for F to be a viable function, there shall
2835 // exist for each argument an implicit conversion sequence
2836 // (13.3.3.1) that converts that argument to the corresponding
2837 // parameter of F.
2838 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002839 Candidate.Conversions[ArgIdx + 1]
2840 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002841 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002842 /*ForceRValue=*/false,
2843 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002844 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002845 == ImplicitConversionSequence::BadConversion) {
2846 Candidate.Viable = false;
2847 break;
2848 }
2849 } else {
2850 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2851 // argument for which there is no corresponding parameter is
2852 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002853 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002854 = ImplicitConversionSequence::EllipsisConversion;
2855 }
2856 }
2857}
2858
Mike Stump87c57ac2009-05-16 07:39:55 +00002859// FIXME: This will eventually be removed, once we've migrated all of the
2860// operator overloading logic over to the scheme used by binary operators, which
2861// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002862void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002863 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002864 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002865 OverloadCandidateSet& CandidateSet,
2866 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002867 FunctionSet Functions;
2868
2869 QualType T1 = Args[0]->getType();
2870 QualType T2;
2871 if (NumArgs > 1)
2872 T2 = Args[1]->getType();
2873
2874 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002875 if (S)
2876 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002877 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002878 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2879 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002880 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002881}
2882
2883/// \brief Add overload candidates for overloaded operators that are
2884/// member functions.
2885///
2886/// Add the overloaded operator candidates that are member functions
2887/// for the operator Op that was used in an operator expression such
2888/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2889/// CandidateSet will store the added overload candidates. (C++
2890/// [over.match.oper]).
2891void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2892 SourceLocation OpLoc,
2893 Expr **Args, unsigned NumArgs,
2894 OverloadCandidateSet& CandidateSet,
2895 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002896 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2897
2898 // C++ [over.match.oper]p3:
2899 // For a unary operator @ with an operand of a type whose
2900 // cv-unqualified version is T1, and for a binary operator @ with
2901 // a left operand of a type whose cv-unqualified version is T1 and
2902 // a right operand of a type whose cv-unqualified version is T2,
2903 // three sets of candidate functions, designated member
2904 // candidates, non-member candidates and built-in candidates, are
2905 // constructed as follows:
2906 QualType T1 = Args[0]->getType();
2907 QualType T2;
2908 if (NumArgs > 1)
2909 T2 = Args[1]->getType();
2910
2911 // -- If T1 is a class type, the set of member candidates is the
2912 // result of the qualified lookup of T1::operator@
2913 // (13.3.1.1.1); otherwise, the set of member candidates is
2914 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002915 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002916 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002917 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002918 return;
Mike Stump11289f42009-09-09 15:08:12 +00002919
John McCall27b18f82009-11-17 02:14:36 +00002920 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2921 LookupQualifiedName(Operators, T1Rec->getDecl());
2922 Operators.suppressDiagnostics();
2923
Mike Stump11289f42009-09-09 15:08:12 +00002924 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002925 OperEnd = Operators.end();
2926 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00002927 ++Oper)
John McCall6e9f8f62009-12-03 04:06:58 +00002928 AddMethodCandidate(*Oper, Args[0]->getType(),
2929 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00002930 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002931 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002932}
2933
Douglas Gregora11693b2008-11-12 17:17:38 +00002934/// AddBuiltinCandidate - Add a candidate for a built-in
2935/// operator. ResultTy and ParamTys are the result and parameter types
2936/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002937/// arguments being passed to the candidate. IsAssignmentOperator
2938/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002939/// operator. NumContextualBoolArguments is the number of arguments
2940/// (at the beginning of the argument list) that will be contextually
2941/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002942void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002943 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002944 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002945 bool IsAssignmentOperator,
2946 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00002947 // Overload resolution is always an unevaluated context.
2948 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2949
Douglas Gregora11693b2008-11-12 17:17:38 +00002950 // Add this candidate
2951 CandidateSet.push_back(OverloadCandidate());
2952 OverloadCandidate& Candidate = CandidateSet.back();
2953 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002954 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002955 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002956 Candidate.BuiltinTypes.ResultTy = ResultTy;
2957 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2958 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2959
2960 // Determine the implicit conversion sequences for each of the
2961 // arguments.
2962 Candidate.Viable = true;
2963 Candidate.Conversions.resize(NumArgs);
2964 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002965 // C++ [over.match.oper]p4:
2966 // For the built-in assignment operators, conversions of the
2967 // left operand are restricted as follows:
2968 // -- no temporaries are introduced to hold the left operand, and
2969 // -- no user-defined conversions are applied to the left
2970 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002971 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002972 //
2973 // We block these conversions by turning off user-defined
2974 // conversions, since that is the only way that initialization of
2975 // a reference to a non-class type can occur from something that
2976 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002977 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002978 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002979 "Contextual conversion to bool requires bool type");
2980 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2981 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002982 Candidate.Conversions[ArgIdx]
2983 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002984 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002985 /*ForceRValue=*/false,
2986 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002987 }
Mike Stump11289f42009-09-09 15:08:12 +00002988 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002989 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002990 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002991 break;
2992 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002993 }
2994}
2995
2996/// BuiltinCandidateTypeSet - A set of types that will be used for the
2997/// candidate operator functions for built-in operators (C++
2998/// [over.built]). The types are separated into pointer types and
2999/// enumeration types.
3000class BuiltinCandidateTypeSet {
3001 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003002 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003003
3004 /// PointerTypes - The set of pointer types that will be used in the
3005 /// built-in candidates.
3006 TypeSet PointerTypes;
3007
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003008 /// MemberPointerTypes - The set of member pointer types that will be
3009 /// used in the built-in candidates.
3010 TypeSet MemberPointerTypes;
3011
Douglas Gregora11693b2008-11-12 17:17:38 +00003012 /// EnumerationTypes - The set of enumeration types that will be
3013 /// used in the built-in candidates.
3014 TypeSet EnumerationTypes;
3015
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003016 /// Sema - The semantic analysis instance where we are building the
3017 /// candidate type set.
3018 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003019
Douglas Gregora11693b2008-11-12 17:17:38 +00003020 /// Context - The AST context in which we will build the type sets.
3021 ASTContext &Context;
3022
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003023 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3024 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003025 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003026
3027public:
3028 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003029 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003030
Mike Stump11289f42009-09-09 15:08:12 +00003031 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003032 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003033
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003034 void AddTypesConvertedFrom(QualType Ty,
3035 SourceLocation Loc,
3036 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003037 bool AllowExplicitConversions,
3038 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003039
3040 /// pointer_begin - First pointer type found;
3041 iterator pointer_begin() { return PointerTypes.begin(); }
3042
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003043 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003044 iterator pointer_end() { return PointerTypes.end(); }
3045
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003046 /// member_pointer_begin - First member pointer type found;
3047 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3048
3049 /// member_pointer_end - Past the last member pointer type found;
3050 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3051
Douglas Gregora11693b2008-11-12 17:17:38 +00003052 /// enumeration_begin - First enumeration type found;
3053 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3054
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003055 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003056 iterator enumeration_end() { return EnumerationTypes.end(); }
3057};
3058
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003059/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003060/// the set of pointer types along with any more-qualified variants of
3061/// that type. For example, if @p Ty is "int const *", this routine
3062/// will add "int const *", "int const volatile *", "int const
3063/// restrict *", and "int const volatile restrict *" to the set of
3064/// pointer types. Returns true if the add of @p Ty itself succeeded,
3065/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003066///
3067/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003068bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003069BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3070 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003071
Douglas Gregora11693b2008-11-12 17:17:38 +00003072 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003073 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003074 return false;
3075
John McCall8ccfcb52009-09-24 19:53:00 +00003076 const PointerType *PointerTy = Ty->getAs<PointerType>();
3077 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003078
John McCall8ccfcb52009-09-24 19:53:00 +00003079 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003080 // Don't add qualified variants of arrays. For one, they're not allowed
3081 // (the qualifier would sink to the element type), and for another, the
3082 // only overload situation where it matters is subscript or pointer +- int,
3083 // and those shouldn't have qualifier variants anyway.
3084 if (PointeeTy->isArrayType())
3085 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003086 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003087 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003088 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003089 bool hasVolatile = VisibleQuals.hasVolatile();
3090 bool hasRestrict = VisibleQuals.hasRestrict();
3091
John McCall8ccfcb52009-09-24 19:53:00 +00003092 // Iterate through all strict supersets of BaseCVR.
3093 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3094 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003095 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3096 // in the types.
3097 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3098 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003099 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3100 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003101 }
3102
3103 return true;
3104}
3105
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003106/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3107/// to the set of pointer types along with any more-qualified variants of
3108/// that type. For example, if @p Ty is "int const *", this routine
3109/// will add "int const *", "int const volatile *", "int const
3110/// restrict *", and "int const volatile restrict *" to the set of
3111/// pointer types. Returns true if the add of @p Ty itself succeeded,
3112/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003113///
3114/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003115bool
3116BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3117 QualType Ty) {
3118 // Insert this type.
3119 if (!MemberPointerTypes.insert(Ty))
3120 return false;
3121
John McCall8ccfcb52009-09-24 19:53:00 +00003122 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3123 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003124
John McCall8ccfcb52009-09-24 19:53:00 +00003125 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003126 // Don't add qualified variants of arrays. For one, they're not allowed
3127 // (the qualifier would sink to the element type), and for another, the
3128 // only overload situation where it matters is subscript or pointer +- int,
3129 // and those shouldn't have qualifier variants anyway.
3130 if (PointeeTy->isArrayType())
3131 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003132 const Type *ClassTy = PointerTy->getClass();
3133
3134 // Iterate through all strict supersets of the pointee type's CVR
3135 // qualifiers.
3136 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3137 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3138 if ((CVR | BaseCVR) != CVR) continue;
3139
3140 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3141 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003142 }
3143
3144 return true;
3145}
3146
Douglas Gregora11693b2008-11-12 17:17:38 +00003147/// AddTypesConvertedFrom - Add each of the types to which the type @p
3148/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003149/// primarily interested in pointer types and enumeration types. We also
3150/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003151/// AllowUserConversions is true if we should look at the conversion
3152/// functions of a class type, and AllowExplicitConversions if we
3153/// should also include the explicit conversion functions of a class
3154/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003155void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003156BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003157 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003158 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003159 bool AllowExplicitConversions,
3160 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003161 // Only deal with canonical types.
3162 Ty = Context.getCanonicalType(Ty);
3163
3164 // Look through reference types; they aren't part of the type of an
3165 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003166 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003167 Ty = RefTy->getPointeeType();
3168
3169 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003170 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003171
Sebastian Redl65ae2002009-11-05 16:36:20 +00003172 // If we're dealing with an array type, decay to the pointer.
3173 if (Ty->isArrayType())
3174 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3175
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003176 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003177 QualType PointeeTy = PointerTy->getPointeeType();
3178
3179 // Insert our type, and its more-qualified variants, into the set
3180 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003181 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003182 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003183 } else if (Ty->isMemberPointerType()) {
3184 // Member pointers are far easier, since the pointee can't be converted.
3185 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3186 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003187 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003188 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003189 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003190 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003191 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003192 // No conversion functions in incomplete types.
3193 return;
3194 }
Mike Stump11289f42009-09-09 15:08:12 +00003195
Douglas Gregora11693b2008-11-12 17:17:38 +00003196 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003197 const UnresolvedSet *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003198 = ClassDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00003199 for (UnresolvedSet::iterator I = Conversions->begin(),
3200 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003201
Mike Stump11289f42009-09-09 15:08:12 +00003202 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003203 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003204 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003205 continue;
3206
John McCalld14a8642009-11-21 08:51:07 +00003207 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003208 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003209 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003210 VisibleQuals);
3211 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003212 }
3213 }
3214 }
3215}
3216
Douglas Gregor84605ae2009-08-24 13:43:27 +00003217/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3218/// the volatile- and non-volatile-qualified assignment operators for the
3219/// given type to the candidate set.
3220static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3221 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003222 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003223 unsigned NumArgs,
3224 OverloadCandidateSet &CandidateSet) {
3225 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003226
Douglas Gregor84605ae2009-08-24 13:43:27 +00003227 // T& operator=(T&, T)
3228 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3229 ParamTypes[1] = T;
3230 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3231 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003232
Douglas Gregor84605ae2009-08-24 13:43:27 +00003233 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3234 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003235 ParamTypes[0]
3236 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003237 ParamTypes[1] = T;
3238 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003239 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003240 }
3241}
Mike Stump11289f42009-09-09 15:08:12 +00003242
Sebastian Redl1054fae2009-10-25 17:03:50 +00003243/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3244/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003245static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3246 Qualifiers VRQuals;
3247 const RecordType *TyRec;
3248 if (const MemberPointerType *RHSMPType =
3249 ArgExpr->getType()->getAs<MemberPointerType>())
3250 TyRec = cast<RecordType>(RHSMPType->getClass());
3251 else
3252 TyRec = ArgExpr->getType()->getAs<RecordType>();
3253 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003254 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003255 VRQuals.addVolatile();
3256 VRQuals.addRestrict();
3257 return VRQuals;
3258 }
3259
3260 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003261 const UnresolvedSet *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003262 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003263
John McCalld14a8642009-11-21 08:51:07 +00003264 for (UnresolvedSet::iterator I = Conversions->begin(),
3265 E = Conversions->end(); I != E; ++I) {
3266 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003267 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3268 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3269 CanTy = ResTypeRef->getPointeeType();
3270 // Need to go down the pointer/mempointer chain and add qualifiers
3271 // as see them.
3272 bool done = false;
3273 while (!done) {
3274 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3275 CanTy = ResTypePtr->getPointeeType();
3276 else if (const MemberPointerType *ResTypeMPtr =
3277 CanTy->getAs<MemberPointerType>())
3278 CanTy = ResTypeMPtr->getPointeeType();
3279 else
3280 done = true;
3281 if (CanTy.isVolatileQualified())
3282 VRQuals.addVolatile();
3283 if (CanTy.isRestrictQualified())
3284 VRQuals.addRestrict();
3285 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3286 return VRQuals;
3287 }
3288 }
3289 }
3290 return VRQuals;
3291}
3292
Douglas Gregord08452f2008-11-19 15:42:04 +00003293/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3294/// operator overloads to the candidate set (C++ [over.built]), based
3295/// on the operator @p Op and the arguments given. For example, if the
3296/// operator is a binary '+', this routine might add "int
3297/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003298void
Mike Stump11289f42009-09-09 15:08:12 +00003299Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003300 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003301 Expr **Args, unsigned NumArgs,
3302 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003303 // The set of "promoted arithmetic types", which are the arithmetic
3304 // types are that preserved by promotion (C++ [over.built]p2). Note
3305 // that the first few of these types are the promoted integral
3306 // types; these types need to be first.
3307 // FIXME: What about complex?
3308 const unsigned FirstIntegralType = 0;
3309 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003310 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003311 LastPromotedIntegralType = 13;
3312 const unsigned FirstPromotedArithmeticType = 7,
3313 LastPromotedArithmeticType = 16;
3314 const unsigned NumArithmeticTypes = 16;
3315 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003316 Context.BoolTy, Context.CharTy, Context.WCharTy,
3317// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003318 Context.SignedCharTy, Context.ShortTy,
3319 Context.UnsignedCharTy, Context.UnsignedShortTy,
3320 Context.IntTy, Context.LongTy, Context.LongLongTy,
3321 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3322 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3323 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003324 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3325 "Invalid first promoted integral type");
3326 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3327 == Context.UnsignedLongLongTy &&
3328 "Invalid last promoted integral type");
3329 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3330 "Invalid first promoted arithmetic type");
3331 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3332 == Context.LongDoubleTy &&
3333 "Invalid last promoted arithmetic type");
3334
Douglas Gregora11693b2008-11-12 17:17:38 +00003335 // Find all of the types that the arguments can convert to, but only
3336 // if the operator we're looking at has built-in operator candidates
3337 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003338 Qualifiers VisibleTypeConversionsQuals;
3339 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003340 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3341 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3342
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003343 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003344 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3345 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003346 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003347 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003348 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003349 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003350 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003351 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003352 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003353 true,
3354 (Op == OO_Exclaim ||
3355 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003356 Op == OO_PipePipe),
3357 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003358 }
3359
3360 bool isComparison = false;
3361 switch (Op) {
3362 case OO_None:
3363 case NUM_OVERLOADED_OPERATORS:
3364 assert(false && "Expected an overloaded operator");
3365 break;
3366
Douglas Gregord08452f2008-11-19 15:42:04 +00003367 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003368 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003369 goto UnaryStar;
3370 else
3371 goto BinaryStar;
3372 break;
3373
3374 case OO_Plus: // '+' is either unary or binary
3375 if (NumArgs == 1)
3376 goto UnaryPlus;
3377 else
3378 goto BinaryPlus;
3379 break;
3380
3381 case OO_Minus: // '-' is either unary or binary
3382 if (NumArgs == 1)
3383 goto UnaryMinus;
3384 else
3385 goto BinaryMinus;
3386 break;
3387
3388 case OO_Amp: // '&' is either unary or binary
3389 if (NumArgs == 1)
3390 goto UnaryAmp;
3391 else
3392 goto BinaryAmp;
3393
3394 case OO_PlusPlus:
3395 case OO_MinusMinus:
3396 // C++ [over.built]p3:
3397 //
3398 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3399 // is either volatile or empty, there exist candidate operator
3400 // functions of the form
3401 //
3402 // VQ T& operator++(VQ T&);
3403 // T operator++(VQ T&, int);
3404 //
3405 // C++ [over.built]p4:
3406 //
3407 // For every pair (T, VQ), where T is an arithmetic type other
3408 // than bool, and VQ is either volatile or empty, there exist
3409 // candidate operator functions of the form
3410 //
3411 // VQ T& operator--(VQ T&);
3412 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003413 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003414 Arith < NumArithmeticTypes; ++Arith) {
3415 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003416 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003417 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003418
3419 // Non-volatile version.
3420 if (NumArgs == 1)
3421 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3422 else
3423 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003424 // heuristic to reduce number of builtin candidates in the set.
3425 // Add volatile version only if there are conversions to a volatile type.
3426 if (VisibleTypeConversionsQuals.hasVolatile()) {
3427 // Volatile version
3428 ParamTypes[0]
3429 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3430 if (NumArgs == 1)
3431 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3432 else
3433 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3434 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003435 }
3436
3437 // C++ [over.built]p5:
3438 //
3439 // For every pair (T, VQ), where T is a cv-qualified or
3440 // cv-unqualified object type, and VQ is either volatile or
3441 // empty, there exist candidate operator functions of the form
3442 //
3443 // T*VQ& operator++(T*VQ&);
3444 // T*VQ& operator--(T*VQ&);
3445 // T* operator++(T*VQ&, int);
3446 // T* operator--(T*VQ&, int);
3447 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3448 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3449 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003450 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003451 continue;
3452
Mike Stump11289f42009-09-09 15:08:12 +00003453 QualType ParamTypes[2] = {
3454 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003455 };
Mike Stump11289f42009-09-09 15:08:12 +00003456
Douglas Gregord08452f2008-11-19 15:42:04 +00003457 // Without volatile
3458 if (NumArgs == 1)
3459 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3460 else
3461 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3462
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003463 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3464 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003465 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003466 ParamTypes[0]
3467 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003468 if (NumArgs == 1)
3469 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3470 else
3471 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3472 }
3473 }
3474 break;
3475
3476 UnaryStar:
3477 // C++ [over.built]p6:
3478 // For every cv-qualified or cv-unqualified object type T, there
3479 // exist candidate operator functions of the form
3480 //
3481 // T& operator*(T*);
3482 //
3483 // C++ [over.built]p7:
3484 // For every function type T, there exist candidate operator
3485 // functions of the form
3486 // T& operator*(T*);
3487 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3488 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3489 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003490 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003491 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003492 &ParamTy, Args, 1, CandidateSet);
3493 }
3494 break;
3495
3496 UnaryPlus:
3497 // C++ [over.built]p8:
3498 // For every type T, there exist candidate operator functions of
3499 // the form
3500 //
3501 // T* operator+(T*);
3502 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3503 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3504 QualType ParamTy = *Ptr;
3505 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3506 }
Mike Stump11289f42009-09-09 15:08:12 +00003507
Douglas Gregord08452f2008-11-19 15:42:04 +00003508 // Fall through
3509
3510 UnaryMinus:
3511 // C++ [over.built]p9:
3512 // For every promoted arithmetic type T, there exist candidate
3513 // operator functions of the form
3514 //
3515 // T operator+(T);
3516 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003517 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003518 Arith < LastPromotedArithmeticType; ++Arith) {
3519 QualType ArithTy = ArithmeticTypes[Arith];
3520 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3521 }
3522 break;
3523
3524 case OO_Tilde:
3525 // C++ [over.built]p10:
3526 // For every promoted integral type T, there exist candidate
3527 // operator functions of the form
3528 //
3529 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003530 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003531 Int < LastPromotedIntegralType; ++Int) {
3532 QualType IntTy = ArithmeticTypes[Int];
3533 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3534 }
3535 break;
3536
Douglas Gregora11693b2008-11-12 17:17:38 +00003537 case OO_New:
3538 case OO_Delete:
3539 case OO_Array_New:
3540 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003541 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003542 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003543 break;
3544
3545 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003546 UnaryAmp:
3547 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003548 // C++ [over.match.oper]p3:
3549 // -- For the operator ',', the unary operator '&', or the
3550 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003551 break;
3552
Douglas Gregor84605ae2009-08-24 13:43:27 +00003553 case OO_EqualEqual:
3554 case OO_ExclaimEqual:
3555 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003556 // For every pointer to member type T, there exist candidate operator
3557 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003558 //
3559 // bool operator==(T,T);
3560 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003561 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003562 MemPtr = CandidateTypes.member_pointer_begin(),
3563 MemPtrEnd = CandidateTypes.member_pointer_end();
3564 MemPtr != MemPtrEnd;
3565 ++MemPtr) {
3566 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3567 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3568 }
Mike Stump11289f42009-09-09 15:08:12 +00003569
Douglas Gregor84605ae2009-08-24 13:43:27 +00003570 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003571
Douglas Gregora11693b2008-11-12 17:17:38 +00003572 case OO_Less:
3573 case OO_Greater:
3574 case OO_LessEqual:
3575 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003576 // C++ [over.built]p15:
3577 //
3578 // For every pointer or enumeration type T, there exist
3579 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003580 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003581 // bool operator<(T, T);
3582 // bool operator>(T, T);
3583 // bool operator<=(T, T);
3584 // bool operator>=(T, T);
3585 // bool operator==(T, T);
3586 // bool operator!=(T, T);
3587 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3588 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3589 QualType ParamTypes[2] = { *Ptr, *Ptr };
3590 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3591 }
Mike Stump11289f42009-09-09 15:08:12 +00003592 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003593 = CandidateTypes.enumeration_begin();
3594 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3595 QualType ParamTypes[2] = { *Enum, *Enum };
3596 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3597 }
3598
3599 // Fall through.
3600 isComparison = true;
3601
Douglas Gregord08452f2008-11-19 15:42:04 +00003602 BinaryPlus:
3603 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003604 if (!isComparison) {
3605 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3606
3607 // C++ [over.built]p13:
3608 //
3609 // For every cv-qualified or cv-unqualified object type T
3610 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003611 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003612 // T* operator+(T*, ptrdiff_t);
3613 // T& operator[](T*, ptrdiff_t); [BELOW]
3614 // T* operator-(T*, ptrdiff_t);
3615 // T* operator+(ptrdiff_t, T*);
3616 // T& operator[](ptrdiff_t, T*); [BELOW]
3617 //
3618 // C++ [over.built]p14:
3619 //
3620 // For every T, where T is a pointer to object type, there
3621 // exist candidate operator functions of the form
3622 //
3623 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003624 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003625 = CandidateTypes.pointer_begin();
3626 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3627 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3628
3629 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3630 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3631
3632 if (Op == OO_Plus) {
3633 // T* operator+(ptrdiff_t, T*);
3634 ParamTypes[0] = ParamTypes[1];
3635 ParamTypes[1] = *Ptr;
3636 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3637 } else {
3638 // ptrdiff_t operator-(T, T);
3639 ParamTypes[1] = *Ptr;
3640 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3641 Args, 2, CandidateSet);
3642 }
3643 }
3644 }
3645 // Fall through
3646
Douglas Gregora11693b2008-11-12 17:17:38 +00003647 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003648 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003649 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003650 // C++ [over.built]p12:
3651 //
3652 // For every pair of promoted arithmetic types L and R, there
3653 // exist candidate operator functions of the form
3654 //
3655 // LR operator*(L, R);
3656 // LR operator/(L, R);
3657 // LR operator+(L, R);
3658 // LR operator-(L, R);
3659 // bool operator<(L, R);
3660 // bool operator>(L, R);
3661 // bool operator<=(L, R);
3662 // bool operator>=(L, R);
3663 // bool operator==(L, R);
3664 // bool operator!=(L, R);
3665 //
3666 // where LR is the result of the usual arithmetic conversions
3667 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003668 //
3669 // C++ [over.built]p24:
3670 //
3671 // For every pair of promoted arithmetic types L and R, there exist
3672 // candidate operator functions of the form
3673 //
3674 // LR operator?(bool, L, R);
3675 //
3676 // where LR is the result of the usual arithmetic conversions
3677 // between types L and R.
3678 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003679 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003680 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003681 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003682 Right < LastPromotedArithmeticType; ++Right) {
3683 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003684 QualType Result
3685 = isComparison
3686 ? Context.BoolTy
3687 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003688 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3689 }
3690 }
3691 break;
3692
3693 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003694 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003695 case OO_Caret:
3696 case OO_Pipe:
3697 case OO_LessLess:
3698 case OO_GreaterGreater:
3699 // C++ [over.built]p17:
3700 //
3701 // For every pair of promoted integral types L and R, there
3702 // exist candidate operator functions of the form
3703 //
3704 // LR operator%(L, R);
3705 // LR operator&(L, R);
3706 // LR operator^(L, R);
3707 // LR operator|(L, R);
3708 // L operator<<(L, R);
3709 // L operator>>(L, R);
3710 //
3711 // where LR is the result of the usual arithmetic conversions
3712 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003713 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003714 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003715 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003716 Right < LastPromotedIntegralType; ++Right) {
3717 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3718 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3719 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003720 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003721 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3722 }
3723 }
3724 break;
3725
3726 case OO_Equal:
3727 // C++ [over.built]p20:
3728 //
3729 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003730 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003731 // empty, there exist candidate operator functions of the form
3732 //
3733 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003734 for (BuiltinCandidateTypeSet::iterator
3735 Enum = CandidateTypes.enumeration_begin(),
3736 EnumEnd = CandidateTypes.enumeration_end();
3737 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003738 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003739 CandidateSet);
3740 for (BuiltinCandidateTypeSet::iterator
3741 MemPtr = CandidateTypes.member_pointer_begin(),
3742 MemPtrEnd = CandidateTypes.member_pointer_end();
3743 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003744 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003745 CandidateSet);
3746 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003747
3748 case OO_PlusEqual:
3749 case OO_MinusEqual:
3750 // C++ [over.built]p19:
3751 //
3752 // For every pair (T, VQ), where T is any type and VQ is either
3753 // volatile or empty, there exist candidate operator functions
3754 // of the form
3755 //
3756 // T*VQ& operator=(T*VQ&, T*);
3757 //
3758 // C++ [over.built]p21:
3759 //
3760 // For every pair (T, VQ), where T is a cv-qualified or
3761 // cv-unqualified object type and VQ is either volatile or
3762 // empty, there exist candidate operator functions of the form
3763 //
3764 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3765 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3766 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3767 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3768 QualType ParamTypes[2];
3769 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3770
3771 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003772 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003773 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3774 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003775
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003776 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3777 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003778 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003779 ParamTypes[0]
3780 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003781 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3782 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003783 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003784 }
3785 // Fall through.
3786
3787 case OO_StarEqual:
3788 case OO_SlashEqual:
3789 // C++ [over.built]p18:
3790 //
3791 // For every triple (L, VQ, R), where L is an arithmetic type,
3792 // VQ is either volatile or empty, and R is a promoted
3793 // arithmetic type, there exist candidate operator functions of
3794 // the form
3795 //
3796 // VQ L& operator=(VQ L&, R);
3797 // VQ L& operator*=(VQ L&, R);
3798 // VQ L& operator/=(VQ L&, R);
3799 // VQ L& operator+=(VQ L&, R);
3800 // VQ L& operator-=(VQ L&, R);
3801 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003802 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003803 Right < LastPromotedArithmeticType; ++Right) {
3804 QualType ParamTypes[2];
3805 ParamTypes[1] = ArithmeticTypes[Right];
3806
3807 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003808 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003809 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3810 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003811
3812 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003813 if (VisibleTypeConversionsQuals.hasVolatile()) {
3814 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3815 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3816 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3817 /*IsAssigmentOperator=*/Op == OO_Equal);
3818 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003819 }
3820 }
3821 break;
3822
3823 case OO_PercentEqual:
3824 case OO_LessLessEqual:
3825 case OO_GreaterGreaterEqual:
3826 case OO_AmpEqual:
3827 case OO_CaretEqual:
3828 case OO_PipeEqual:
3829 // C++ [over.built]p22:
3830 //
3831 // For every triple (L, VQ, R), where L is an integral type, VQ
3832 // is either volatile or empty, and R is a promoted integral
3833 // type, there exist candidate operator functions of the form
3834 //
3835 // VQ L& operator%=(VQ L&, R);
3836 // VQ L& operator<<=(VQ L&, R);
3837 // VQ L& operator>>=(VQ L&, R);
3838 // VQ L& operator&=(VQ L&, R);
3839 // VQ L& operator^=(VQ L&, R);
3840 // VQ L& operator|=(VQ L&, R);
3841 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003842 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003843 Right < LastPromotedIntegralType; ++Right) {
3844 QualType ParamTypes[2];
3845 ParamTypes[1] = ArithmeticTypes[Right];
3846
3847 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003848 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003849 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003850 if (VisibleTypeConversionsQuals.hasVolatile()) {
3851 // Add this built-in operator as a candidate (VQ is 'volatile').
3852 ParamTypes[0] = ArithmeticTypes[Left];
3853 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3854 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3855 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3856 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003857 }
3858 }
3859 break;
3860
Douglas Gregord08452f2008-11-19 15:42:04 +00003861 case OO_Exclaim: {
3862 // C++ [over.operator]p23:
3863 //
3864 // There also exist candidate operator functions of the form
3865 //
Mike Stump11289f42009-09-09 15:08:12 +00003866 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003867 // bool operator&&(bool, bool); [BELOW]
3868 // bool operator||(bool, bool); [BELOW]
3869 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003870 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3871 /*IsAssignmentOperator=*/false,
3872 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003873 break;
3874 }
3875
Douglas Gregora11693b2008-11-12 17:17:38 +00003876 case OO_AmpAmp:
3877 case OO_PipePipe: {
3878 // C++ [over.operator]p23:
3879 //
3880 // There also exist candidate operator functions of the form
3881 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003882 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003883 // bool operator&&(bool, bool);
3884 // bool operator||(bool, bool);
3885 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003886 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3887 /*IsAssignmentOperator=*/false,
3888 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003889 break;
3890 }
3891
3892 case OO_Subscript:
3893 // C++ [over.built]p13:
3894 //
3895 // For every cv-qualified or cv-unqualified object type T there
3896 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003897 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003898 // T* operator+(T*, ptrdiff_t); [ABOVE]
3899 // T& operator[](T*, ptrdiff_t);
3900 // T* operator-(T*, ptrdiff_t); [ABOVE]
3901 // T* operator+(ptrdiff_t, T*); [ABOVE]
3902 // T& operator[](ptrdiff_t, T*);
3903 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3904 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3905 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003906 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003907 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003908
3909 // T& operator[](T*, ptrdiff_t)
3910 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3911
3912 // T& operator[](ptrdiff_t, T*);
3913 ParamTypes[0] = ParamTypes[1];
3914 ParamTypes[1] = *Ptr;
3915 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3916 }
3917 break;
3918
3919 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003920 // C++ [over.built]p11:
3921 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3922 // C1 is the same type as C2 or is a derived class of C2, T is an object
3923 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3924 // there exist candidate operator functions of the form
3925 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3926 // where CV12 is the union of CV1 and CV2.
3927 {
3928 for (BuiltinCandidateTypeSet::iterator Ptr =
3929 CandidateTypes.pointer_begin();
3930 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3931 QualType C1Ty = (*Ptr);
3932 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003933 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003934 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003935 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003936 if (!isa<RecordType>(C1))
3937 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003938 // heuristic to reduce number of builtin candidates in the set.
3939 // Add volatile/restrict version only if there are conversions to a
3940 // volatile/restrict type.
3941 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3942 continue;
3943 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3944 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003945 }
3946 for (BuiltinCandidateTypeSet::iterator
3947 MemPtr = CandidateTypes.member_pointer_begin(),
3948 MemPtrEnd = CandidateTypes.member_pointer_end();
3949 MemPtr != MemPtrEnd; ++MemPtr) {
3950 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3951 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00003952 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003953 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3954 break;
3955 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3956 // build CV12 T&
3957 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003958 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3959 T.isVolatileQualified())
3960 continue;
3961 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3962 T.isRestrictQualified())
3963 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003964 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003965 QualType ResultTy = Context.getLValueReferenceType(T);
3966 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3967 }
3968 }
3969 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003970 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003971
3972 case OO_Conditional:
3973 // Note that we don't consider the first argument, since it has been
3974 // contextually converted to bool long ago. The candidates below are
3975 // therefore added as binary.
3976 //
3977 // C++ [over.built]p24:
3978 // For every type T, where T is a pointer or pointer-to-member type,
3979 // there exist candidate operator functions of the form
3980 //
3981 // T operator?(bool, T, T);
3982 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003983 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3984 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3985 QualType ParamTypes[2] = { *Ptr, *Ptr };
3986 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3987 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003988 for (BuiltinCandidateTypeSet::iterator Ptr =
3989 CandidateTypes.member_pointer_begin(),
3990 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3991 QualType ParamTypes[2] = { *Ptr, *Ptr };
3992 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3993 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003994 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003995 }
3996}
3997
Douglas Gregore254f902009-02-04 00:32:51 +00003998/// \brief Add function candidates found via argument-dependent lookup
3999/// to the set of overloading candidates.
4000///
4001/// This routine performs argument-dependent name lookup based on the
4002/// given function name (which may also be an operator name) and adds
4003/// all of the overload candidates found by ADL to the overload
4004/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004005void
Douglas Gregore254f902009-02-04 00:32:51 +00004006Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4007 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004008 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004009 OverloadCandidateSet& CandidateSet,
4010 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004011 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00004012
Douglas Gregorcabea402009-09-22 15:41:20 +00004013 // FIXME: Should we be trafficking in canonical function decls throughout?
4014
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004015 // Record all of the function candidates that we've already
4016 // added to the overload set, so that we don't add those same
4017 // candidates a second time.
4018 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4019 CandEnd = CandidateSet.end();
4020 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004021 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004022 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004023 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4024 Functions.insert(FunTmpl);
4025 }
Douglas Gregore254f902009-02-04 00:32:51 +00004026
Douglas Gregorcabea402009-09-22 15:41:20 +00004027 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00004028 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00004029
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004030 // Erase all of the candidates we already knew about.
4031 // FIXME: This is suboptimal. Is there a better way?
4032 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4033 CandEnd = CandidateSet.end();
4034 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004035 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004036 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004037 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4038 Functions.erase(FunTmpl);
4039 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004040
4041 // For each of the ADL candidates we found, add it to the overload
4042 // set.
4043 for (FunctionSet::iterator Func = Functions.begin(),
4044 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00004045 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004046 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCall6b51f282009-11-23 01:53:49 +00004047 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004048 continue;
4049
4050 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4051 false, false, PartialOverloading);
4052 } else
Mike Stump11289f42009-09-09 15:08:12 +00004053 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00004054 ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004055 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004056 }
Douglas Gregore254f902009-02-04 00:32:51 +00004057}
4058
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004059/// isBetterOverloadCandidate - Determines whether the first overload
4060/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004061bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004062Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00004063 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004064 // Define viable functions to be better candidates than non-viable
4065 // functions.
4066 if (!Cand2.Viable)
4067 return Cand1.Viable;
4068 else if (!Cand1.Viable)
4069 return false;
4070
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004071 // C++ [over.match.best]p1:
4072 //
4073 // -- if F is a static member function, ICS1(F) is defined such
4074 // that ICS1(F) is neither better nor worse than ICS1(G) for
4075 // any function G, and, symmetrically, ICS1(G) is neither
4076 // better nor worse than ICS1(F).
4077 unsigned StartArg = 0;
4078 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4079 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004080
Douglas Gregord3cb3562009-07-07 23:38:56 +00004081 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004082 // A viable function F1 is defined to be a better function than another
4083 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004084 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004085 unsigned NumArgs = Cand1.Conversions.size();
4086 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4087 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004088 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004089 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4090 Cand2.Conversions[ArgIdx])) {
4091 case ImplicitConversionSequence::Better:
4092 // Cand1 has a better conversion sequence.
4093 HasBetterConversion = true;
4094 break;
4095
4096 case ImplicitConversionSequence::Worse:
4097 // Cand1 can't be better than Cand2.
4098 return false;
4099
4100 case ImplicitConversionSequence::Indistinguishable:
4101 // Do nothing.
4102 break;
4103 }
4104 }
4105
Mike Stump11289f42009-09-09 15:08:12 +00004106 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004107 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004108 if (HasBetterConversion)
4109 return true;
4110
Mike Stump11289f42009-09-09 15:08:12 +00004111 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004112 // specialization, or, if not that,
4113 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4114 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4115 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004116
4117 // -- F1 and F2 are function template specializations, and the function
4118 // template for F1 is more specialized than the template for F2
4119 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004120 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004121 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4122 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004123 if (FunctionTemplateDecl *BetterTemplate
4124 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4125 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004126 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4127 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004128 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004129
Douglas Gregora1f013e2008-11-07 22:36:19 +00004130 // -- the context is an initialization by user-defined conversion
4131 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4132 // from the return type of F1 to the destination type (i.e.,
4133 // the type of the entity being initialized) is a better
4134 // conversion sequence than the standard conversion sequence
4135 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004136 if (Cand1.Function && Cand2.Function &&
4137 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004138 isa<CXXConversionDecl>(Cand2.Function)) {
4139 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4140 Cand2.FinalConversion)) {
4141 case ImplicitConversionSequence::Better:
4142 // Cand1 has a better conversion sequence.
4143 return true;
4144
4145 case ImplicitConversionSequence::Worse:
4146 // Cand1 can't be better than Cand2.
4147 return false;
4148
4149 case ImplicitConversionSequence::Indistinguishable:
4150 // Do nothing
4151 break;
4152 }
4153 }
4154
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004155 return false;
4156}
4157
Mike Stump11289f42009-09-09 15:08:12 +00004158/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004159/// within an overload candidate set.
4160///
4161/// \param CandidateSet the set of candidate functions.
4162///
4163/// \param Loc the location of the function name (or operator symbol) for
4164/// which overload resolution occurs.
4165///
Mike Stump11289f42009-09-09 15:08:12 +00004166/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004167/// function, Best points to the candidate function found.
4168///
4169/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00004170Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004171Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004172 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004173 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004174 // Find the best viable function.
4175 Best = CandidateSet.end();
4176 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4177 Cand != CandidateSet.end(); ++Cand) {
4178 if (Cand->Viable) {
4179 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4180 Best = Cand;
4181 }
4182 }
4183
4184 // If we didn't find any viable functions, abort.
4185 if (Best == CandidateSet.end())
4186 return OR_No_Viable_Function;
4187
4188 // Make sure that this function is better than every other viable
4189 // function. If not, we have an ambiguity.
4190 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4191 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004192 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004193 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004194 !isBetterOverloadCandidate(*Best, *Cand)) {
4195 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004196 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004197 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004198 }
Mike Stump11289f42009-09-09 15:08:12 +00004199
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004200 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004201 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004202 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004203 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004204 return OR_Deleted;
4205
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004206 // C++ [basic.def.odr]p2:
4207 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004208 // when referred to from a potentially-evaluated expression. [Note: this
4209 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004210 // (clause 13), user-defined conversions (12.3.2), allocation function for
4211 // placement new (5.3.4), as well as non-default initialization (8.5).
4212 if (Best->Function)
4213 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004214 return OR_Success;
4215}
4216
4217/// PrintOverloadCandidates - When overload resolution fails, prints
4218/// diagnostic messages containing the candidates in the candidate
4219/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00004220void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004221Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004222 bool OnlyViable,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004223 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004224 SourceLocation OpLoc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004225 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4226 LastCand = CandidateSet.end();
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004227 bool Reported = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004228 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004229 if (Cand->Viable || !OnlyViable) {
4230 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004231 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004232 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004233 // Deleted or "unavailable" function.
4234 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4235 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00004236 } else if (FunctionTemplateDecl *FunTmpl
4237 = Cand->Function->getPrimaryTemplate()) {
4238 // Function template specialization
4239 // FIXME: Give a better reason!
4240 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4241 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4242 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00004243 } else {
4244 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00004245 bool errReported = false;
4246 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4247 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4248 const ImplicitConversionSequence &Conversion =
4249 Cand->Conversions[i];
4250 if ((Conversion.ConversionKind !=
4251 ImplicitConversionSequence::BadConversion) ||
4252 Conversion.ConversionFunctionSet.size() == 0)
4253 continue;
4254 Diag(Cand->Function->getLocation(),
4255 diag::err_ovl_candidate_not_viable) << (i+1);
4256 errReported = true;
4257 for (int j = Conversion.ConversionFunctionSet.size()-1;
4258 j >= 0; j--) {
4259 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4260 Diag(Func->getLocation(), diag::err_ovl_candidate);
4261 }
4262 }
4263 }
4264 if (!errReported)
4265 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004266 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004267 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004268 // Desugar the type of the surrogate down to a function type,
4269 // retaining as many typedefs as possible while still showing
4270 // the function type (and, therefore, its parameter types).
4271 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004272 bool isLValueReference = false;
4273 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004274 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004275 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004276 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004277 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004278 isLValueReference = true;
4279 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004280 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004281 FnType = FnTypeRef->getPointeeType();
4282 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004283 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004284 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004285 FnType = FnTypePtr->getPointeeType();
4286 isPointer = true;
4287 }
4288 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00004289 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004290 // Reconstruct the pointer/reference as appropriate.
4291 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004292 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4293 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004294
Douglas Gregorab7897a2008-11-19 22:57:39 +00004295 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004296 << FnType;
Douglas Gregor66950a32009-09-30 21:46:01 +00004297 } else if (OnlyViable) {
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004298 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanian0fe5e032009-10-09 17:09:58 +00004299 "builtin-binary-operator-not-binary");
Fariborz Jahanian956127d2009-10-16 23:25:02 +00004300 std::string TypeStr("operator");
4301 TypeStr += Opc;
4302 TypeStr += "(";
4303 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4304 if (Cand->Conversions.size() == 1) {
4305 TypeStr += ")";
4306 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4307 }
4308 else {
4309 TypeStr += ", ";
4310 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4311 TypeStr += ")";
4312 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4313 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004314 }
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004315 else if (!Cand->Viable && !Reported) {
4316 // Non-viability might be due to ambiguous user-defined conversions,
4317 // needed for built-in operators. Report them as well, but only once
4318 // as we have typically many built-in candidates.
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004319 unsigned NoOperands = Cand->Conversions.size();
4320 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004321 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4322 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4323 ICS.ConversionFunctionSet.empty())
4324 continue;
4325 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4326 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4327 QualType FromTy =
4328 QualType(
4329 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4330 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4331 << FromTy << Func->getConversionType();
4332 }
4333 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4334 FunctionDecl *Func =
4335 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4336 Diag(Func->getLocation(),diag::err_ovl_candidate);
4337 }
4338 }
4339 Reported = true;
4340 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004341 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004342 }
4343}
4344
Douglas Gregorcd695e52008-11-10 20:40:00 +00004345/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4346/// an overloaded function (C++ [over.over]), where @p From is an
4347/// expression with overloaded function type and @p ToType is the type
4348/// we're trying to resolve to. For example:
4349///
4350/// @code
4351/// int f(double);
4352/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004353///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004354/// int (*pfd)(double) = f; // selects f(double)
4355/// @endcode
4356///
4357/// This routine returns the resulting FunctionDecl if it could be
4358/// resolved, and NULL otherwise. When @p Complain is true, this
4359/// routine will emit diagnostics if there is an error.
4360FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004361Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004362 bool Complain) {
4363 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004364 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004365 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004366 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004367 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004368 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004369 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004370 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004371 FunctionType = MemTypePtr->getPointeeType();
4372 IsMember = true;
4373 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004374
4375 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004376 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004377 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004378 return 0;
4379
4380 // Find the actual overloaded function declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004381
Douglas Gregorcd695e52008-11-10 20:40:00 +00004382 // C++ [over.over]p1:
4383 // [...] [Note: any redundant set of parentheses surrounding the
4384 // overloaded function name is ignored (5.1). ]
4385 Expr *OvlExpr = From->IgnoreParens();
4386
4387 // C++ [over.over]p1:
4388 // [...] The overloaded function name can be preceded by the &
4389 // operator.
4390 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4391 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4392 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4393 }
4394
Anders Carlssonb68b0282009-10-20 22:53:47 +00004395 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004396 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCalld14a8642009-11-21 08:51:07 +00004397
4398 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004399
John McCall10eae182009-11-30 22:42:35 +00004400 // Look into the overloaded expression.
John McCalle66edc12009-11-24 19:00:30 +00004401 if (UnresolvedLookupExpr *UL
John McCalld14a8642009-11-21 08:51:07 +00004402 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4403 Fns.append(UL->decls_begin(), UL->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00004404 if (UL->hasExplicitTemplateArgs()) {
4405 HasExplicitTemplateArgs = true;
4406 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4407 }
John McCall10eae182009-11-30 22:42:35 +00004408 } else if (UnresolvedMemberExpr *ME
4409 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4410 Fns.append(ME->decls_begin(), ME->decls_end());
4411 if (ME->hasExplicitTemplateArgs()) {
4412 HasExplicitTemplateArgs = true;
John McCall6b51f282009-11-23 01:53:49 +00004413 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004414 }
Douglas Gregor9b146582009-07-08 20:55:45 +00004415 }
Mike Stump11289f42009-09-09 15:08:12 +00004416
John McCalld14a8642009-11-21 08:51:07 +00004417 // If we didn't actually find anything, we're done.
4418 if (Fns.empty())
4419 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004420
Douglas Gregorcd695e52008-11-10 20:40:00 +00004421 // Look through all of the overloaded functions, searching for one
4422 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004423 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004424 bool FoundNonTemplateFunction = false;
John McCalld14a8642009-11-21 08:51:07 +00004425 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4426 E = Fns.end(); I != E; ++I) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004427 // C++ [over.over]p3:
4428 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004429 // targets of type "pointer-to-function" or "reference-to-function."
4430 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004431 // type "pointer-to-member-function."
4432 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004433
Mike Stump11289f42009-09-09 15:08:12 +00004434 if (FunctionTemplateDecl *FunctionTemplate
John McCalld14a8642009-11-21 08:51:07 +00004435 = dyn_cast<FunctionTemplateDecl>(*I)) {
Mike Stump11289f42009-09-09 15:08:12 +00004436 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004437 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004438 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004439 // static when converting to member pointer.
4440 if (Method->isStatic() == IsMember)
4441 continue;
4442 } else if (IsMember)
4443 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004444
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004445 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004446 // If the name is a function template, template argument deduction is
4447 // done (14.8.2.2), and if the argument deduction succeeds, the
4448 // resulting template argument list is used to generate a single
4449 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004450 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004451 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004452 FunctionDecl *Specialization = 0;
4453 TemplateDeductionInfo Info(Context);
4454 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004455 = DeduceTemplateArguments(FunctionTemplate,
4456 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor9b146582009-07-08 20:55:45 +00004457 FunctionType, Specialization, Info)) {
4458 // FIXME: make a note of the failed deduction for diagnostics.
4459 (void)Result;
4460 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004461 // FIXME: If the match isn't exact, shouldn't we just drop this as
4462 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004463 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004464 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004465 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004466 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004467 }
John McCalld14a8642009-11-21 08:51:07 +00004468
4469 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00004470 }
Mike Stump11289f42009-09-09 15:08:12 +00004471
John McCalld14a8642009-11-21 08:51:07 +00004472 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004473 // Skip non-static functions when converting to pointer, and static
4474 // when converting to member pointer.
4475 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004476 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004477
4478 // If we have explicit template arguments, skip non-templates.
4479 if (HasExplicitTemplateArgs)
4480 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004481 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004482 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004483
John McCalld14a8642009-11-21 08:51:07 +00004484 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*I)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00004485 QualType ResultTy;
4486 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4487 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4488 ResultTy)) {
John McCalld14a8642009-11-21 08:51:07 +00004489 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004490 FoundNonTemplateFunction = true;
4491 }
Mike Stump11289f42009-09-09 15:08:12 +00004492 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004493 }
4494
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004495 // If there were 0 or 1 matches, we're done.
4496 if (Matches.empty())
4497 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004498 else if (Matches.size() == 1) {
4499 FunctionDecl *Result = *Matches.begin();
4500 MarkDeclarationReferenced(From->getLocStart(), Result);
4501 return Result;
4502 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004503
4504 // C++ [over.over]p4:
4505 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004506 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004507 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004508 // [...] and any given function template specialization F1 is
4509 // eliminated if the set contains a second function template
4510 // specialization whose function template is more specialized
4511 // than the function template of F1 according to the partial
4512 // ordering rules of 14.5.5.2.
4513
4514 // The algorithm specified above is quadratic. We instead use a
4515 // two-pass algorithm (similar to the one used to identify the
4516 // best viable function in an overload set) that identifies the
4517 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004518 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004519 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004520 FunctionDecl *Result =
4521 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4522 TPOC_Other, From->getLocStart(),
4523 PDiag(),
4524 PDiag(diag::err_addr_ovl_ambiguous)
4525 << TemplateMatches[0]->getDeclName(),
4526 PDiag(diag::err_ovl_template_candidate));
4527 MarkDeclarationReferenced(From->getLocStart(), Result);
4528 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004529 }
Mike Stump11289f42009-09-09 15:08:12 +00004530
Douglas Gregorfae1d712009-09-26 03:56:17 +00004531 // [...] any function template specializations in the set are
4532 // eliminated if the set also contains a non-template function, [...]
4533 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4534 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4535 if ((*M)->getPrimaryTemplate() == 0)
4536 RemainingMatches.push_back(*M);
4537
Mike Stump11289f42009-09-09 15:08:12 +00004538 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004539 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004540 if (RemainingMatches.size() == 1) {
4541 FunctionDecl *Result = RemainingMatches.front();
4542 MarkDeclarationReferenced(From->getLocStart(), Result);
4543 return Result;
4544 }
Mike Stump11289f42009-09-09 15:08:12 +00004545
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004546 // FIXME: We should probably return the same thing that BestViableFunction
4547 // returns (even if we issue the diagnostics here).
4548 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4549 << RemainingMatches[0]->getDeclName();
4550 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4551 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004552 return 0;
4553}
4554
Douglas Gregorcabea402009-09-22 15:41:20 +00004555/// \brief Add a single candidate to the overload set.
4556static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00004557 NamedDecl *Callee,
John McCall6b51f282009-11-23 01:53:49 +00004558 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004559 Expr **Args, unsigned NumArgs,
4560 OverloadCandidateSet &CandidateSet,
4561 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004562 if (isa<UsingShadowDecl>(Callee))
4563 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4564
Douglas Gregorcabea402009-09-22 15:41:20 +00004565 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004566 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorcabea402009-09-22 15:41:20 +00004567 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4568 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004569 return;
John McCalld14a8642009-11-21 08:51:07 +00004570 }
4571
4572 if (FunctionTemplateDecl *FuncTemplate
4573 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004574 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004575 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00004576 return;
4577 }
4578
4579 assert(false && "unhandled case in overloaded call candidate");
4580
4581 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00004582}
4583
4584/// \brief Add the overload candidates named by callee and/or found by argument
4585/// dependent lookup to the given overload set.
John McCalld14a8642009-11-21 08:51:07 +00004586void Sema::AddOverloadedCallCandidates(llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregorcabea402009-09-22 15:41:20 +00004587 DeclarationName &UnqualifiedName,
John McCall4b1f16e2009-11-21 09:38:42 +00004588 bool ArgumentDependentLookup,
John McCall6b51f282009-11-23 01:53:49 +00004589 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004590 Expr **Args, unsigned NumArgs,
4591 OverloadCandidateSet &CandidateSet,
4592 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004593
4594#ifndef NDEBUG
4595 // Verify that ArgumentDependentLookup is consistent with the rules
4596 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00004597 //
Douglas Gregorcabea402009-09-22 15:41:20 +00004598 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4599 // and let Y be the lookup set produced by argument dependent
4600 // lookup (defined as follows). If X contains
4601 //
4602 // -- a declaration of a class member, or
4603 //
4604 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00004605 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00004606 //
4607 // -- a declaration that is neither a function or a function
4608 // template
4609 //
4610 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00004611
4612 if (ArgumentDependentLookup) {
4613 for (unsigned I = 0; I < Fns.size(); ++I) {
4614 assert(!Fns[I]->getDeclContext()->isRecord());
4615 assert(isa<UsingShadowDecl>(Fns[I]) ||
4616 !Fns[I]->getDeclContext()->isFunctionOrMethod());
4617 assert(Fns[I]->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
4618 }
4619 }
4620#endif
4621
4622 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4623 E = Fns.end(); I != E; ++I)
John McCall6b51f282009-11-23 01:53:49 +00004624 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004625 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00004626 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00004627
Douglas Gregorcabea402009-09-22 15:41:20 +00004628 if (ArgumentDependentLookup)
4629 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004630 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004631 CandidateSet,
4632 PartialOverloading);
4633}
4634
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004635/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004636/// (which eventually refers to the declaration Func) and the call
4637/// arguments Args/NumArgs, attempt to resolve the function call down
4638/// to a specific function. If overload resolution succeeds, returns
4639/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004640/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004641/// arguments and Fn, and returns NULL.
John McCalld14a8642009-11-21 08:51:07 +00004642FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn,
4643 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004644 DeclarationName UnqualifiedName,
John McCall6b51f282009-11-23 01:53:49 +00004645 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004646 SourceLocation LParenLoc,
4647 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004648 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004649 SourceLocation RParenLoc,
John McCall4b1f16e2009-11-21 09:38:42 +00004650 bool ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004651 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004652
4653 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004654 // functions.
John McCalld14a8642009-11-21 08:51:07 +00004655 AddOverloadedCallCandidates(Fns, UnqualifiedName, ArgumentDependentLookup,
John McCall6b51f282009-11-23 01:53:49 +00004656 ExplicitTemplateArgs, Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004657 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004658 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004659 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004660 case OR_Success:
4661 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004662
4663 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004664 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004665 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004666 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004667 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4668 break;
4669
4670 case OR_Ambiguous:
4671 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004672 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004673 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4674 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004675
4676 case OR_Deleted:
4677 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4678 << Best->Function->isDeleted()
4679 << UnqualifiedName
4680 << Fn->getSourceRange();
4681 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4682 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004683 }
4684
4685 // Overload resolution failed. Destroy all of the subexpressions and
4686 // return NULL.
4687 Fn->Destroy(Context);
4688 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4689 Args[Arg]->Destroy(Context);
4690 return 0;
4691}
4692
John McCall283b9012009-11-22 00:44:51 +00004693static bool IsOverloaded(const Sema::FunctionSet &Functions) {
4694 return Functions.size() > 1 ||
4695 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
4696}
4697
Douglas Gregor084d8552009-03-13 23:49:33 +00004698/// \brief Create a unary operation that may resolve to an overloaded
4699/// operator.
4700///
4701/// \param OpLoc The location of the operator itself (e.g., '*').
4702///
4703/// \param OpcIn The UnaryOperator::Opcode that describes this
4704/// operator.
4705///
4706/// \param Functions The set of non-member functions that will be
4707/// considered by overload resolution. The caller needs to build this
4708/// set based on the context using, e.g.,
4709/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4710/// set should not contain any member functions; those will be added
4711/// by CreateOverloadedUnaryOp().
4712///
4713/// \param input The input argument.
4714Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4715 unsigned OpcIn,
4716 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004717 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004718 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4719 Expr *Input = (Expr *)input.get();
4720
4721 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4722 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4723 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4724
4725 Expr *Args[2] = { Input, 0 };
4726 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004727
Douglas Gregor084d8552009-03-13 23:49:33 +00004728 // For post-increment and post-decrement, add the implicit '0' as
4729 // the second argument, so that we know this is a post-increment or
4730 // post-decrement.
4731 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4732 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004733 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004734 SourceLocation());
4735 NumArgs = 2;
4736 }
4737
4738 if (Input->isTypeDependent()) {
John McCalld14a8642009-11-21 08:51:07 +00004739 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00004740 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4741 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00004742 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump11289f42009-09-09 15:08:12 +00004743 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004744 FuncEnd = Functions.end();
4745 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00004746 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00004747
Douglas Gregor084d8552009-03-13 23:49:33 +00004748 input.release();
4749 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4750 &Args[0], NumArgs,
4751 Context.DependentTy,
4752 OpLoc));
4753 }
4754
4755 // Build an empty overload set.
4756 OverloadCandidateSet CandidateSet;
4757
4758 // Add the candidates from the given function set.
4759 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4760
4761 // Add operator candidates that are member functions.
4762 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4763
4764 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004765 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00004766
4767 // Perform overload resolution.
4768 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004769 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004770 case OR_Success: {
4771 // We found a built-in operator or an overloaded operator.
4772 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004773
Douglas Gregor084d8552009-03-13 23:49:33 +00004774 if (FnDecl) {
4775 // We matched an overloaded operator. Build a call to that
4776 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004777
Douglas Gregor084d8552009-03-13 23:49:33 +00004778 // Convert the arguments.
4779 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4780 if (PerformObjectArgumentInitialization(Input, Method))
4781 return ExprError();
4782 } else {
4783 // Convert the arguments.
4784 if (PerformCopyInitialization(Input,
4785 FnDecl->getParamDecl(0)->getType(),
4786 "passing"))
4787 return ExprError();
4788 }
4789
4790 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004791 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004792
Douglas Gregor084d8552009-03-13 23:49:33 +00004793 // Build the actual expression node.
4794 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4795 SourceLocation());
4796 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004797
Douglas Gregor084d8552009-03-13 23:49:33 +00004798 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00004799 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004800 ExprOwningPtr<CallExpr> TheCall(this,
4801 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00004802 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004803
4804 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4805 FnDecl))
4806 return ExprError();
4807
4808 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00004809 } else {
4810 // We matched a built-in operator. Convert the arguments, then
4811 // break out so that we will build the appropriate built-in
4812 // operator node.
4813 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4814 Best->Conversions[0], "passing"))
4815 return ExprError();
4816
4817 break;
4818 }
4819 }
4820
4821 case OR_No_Viable_Function:
4822 // No viable function; fall through to handling this as a
4823 // built-in operator, which will produce an error message for us.
4824 break;
4825
4826 case OR_Ambiguous:
4827 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4828 << UnaryOperator::getOpcodeStr(Opc)
4829 << Input->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004830 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4831 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00004832 return ExprError();
4833
4834 case OR_Deleted:
4835 Diag(OpLoc, diag::err_ovl_deleted_oper)
4836 << Best->Function->isDeleted()
4837 << UnaryOperator::getOpcodeStr(Opc)
4838 << Input->getSourceRange();
4839 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4840 return ExprError();
4841 }
4842
4843 // Either we found no viable overloaded operator or we matched a
4844 // built-in operator. In either case, fall through to trying to
4845 // build a built-in operation.
4846 input.release();
4847 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4848}
4849
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004850/// \brief Create a binary operation that may resolve to an overloaded
4851/// operator.
4852///
4853/// \param OpLoc The location of the operator itself (e.g., '+').
4854///
4855/// \param OpcIn The BinaryOperator::Opcode that describes this
4856/// operator.
4857///
4858/// \param Functions The set of non-member functions that will be
4859/// considered by overload resolution. The caller needs to build this
4860/// set based on the context using, e.g.,
4861/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4862/// set should not contain any member functions; those will be added
4863/// by CreateOverloadedBinOp().
4864///
4865/// \param LHS Left-hand argument.
4866/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004867Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004868Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004869 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004870 FunctionSet &Functions,
4871 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004872 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004873 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004874
4875 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4876 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4877 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4878
4879 // If either side is type-dependent, create an appropriate dependent
4880 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004881 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00004882 if (Functions.empty()) {
4883 // If there are no functions to store, just build a dependent
4884 // BinaryOperator or CompoundAssignment.
4885 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4886 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4887 Context.DependentTy, OpLoc));
4888
4889 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4890 Context.DependentTy,
4891 Context.DependentTy,
4892 Context.DependentTy,
4893 OpLoc));
4894 }
4895
John McCalld14a8642009-11-21 08:51:07 +00004896 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00004897 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4898 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00004899 /* ADL */ true, IsOverloaded(Functions));
John McCalld14a8642009-11-21 08:51:07 +00004900
Mike Stump11289f42009-09-09 15:08:12 +00004901 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004902 FuncEnd = Functions.end();
4903 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00004904 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00004905
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004906 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004907 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004908 Context.DependentTy,
4909 OpLoc));
4910 }
4911
4912 // If this is the .* operator, which is not overloadable, just
4913 // create a built-in binary operator.
4914 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004915 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004916
Sebastian Redl6a96bf72009-11-18 23:10:33 +00004917 // If this is the assignment operator, we only perform overload resolution
4918 // if the left-hand side is a class or enumeration type. This is actually
4919 // a hack. The standard requires that we do overload resolution between the
4920 // various built-in candidates, but as DR507 points out, this can lead to
4921 // problems. So we do it this way, which pretty much follows what GCC does.
4922 // Note that we go the traditional code path for compound assignment forms.
4923 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00004924 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004925
Douglas Gregor084d8552009-03-13 23:49:33 +00004926 // Build an empty overload set.
4927 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004928
4929 // Add the candidates from the given function set.
4930 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4931
4932 // Add operator candidates that are member functions.
4933 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4934
4935 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004936 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004937
4938 // Perform overload resolution.
4939 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004940 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004941 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004942 // We found a built-in operator or an overloaded operator.
4943 FunctionDecl *FnDecl = Best->Function;
4944
4945 if (FnDecl) {
4946 // We matched an overloaded operator. Build a call to that
4947 // operator.
4948
4949 // Convert the arguments.
4950 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004951 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4952 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004953 "passing"))
4954 return ExprError();
4955 } else {
4956 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004957 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004958 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004959 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004960 "passing"))
4961 return ExprError();
4962 }
4963
4964 // Determine the result type
4965 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004966 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004967 ResultTy = ResultTy.getNonReferenceType();
4968
4969 // Build the actual expression node.
4970 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004971 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004972 UsualUnaryConversions(FnExpr);
4973
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00004974 ExprOwningPtr<CXXOperatorCallExpr>
4975 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4976 Args, 2, ResultTy,
4977 OpLoc));
4978
4979 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4980 FnDecl))
4981 return ExprError();
4982
4983 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004984 } else {
4985 // We matched a built-in operator. Convert the arguments, then
4986 // break out so that we will build the appropriate built-in
4987 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004988 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004989 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004990 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004991 Best->Conversions[1], "passing"))
4992 return ExprError();
4993
4994 break;
4995 }
4996 }
4997
Douglas Gregor66950a32009-09-30 21:46:01 +00004998 case OR_No_Viable_Function: {
4999 // C++ [over.match.oper]p9:
5000 // If the operator is the operator , [...] and there are no
5001 // viable functions, then the operator is assumed to be the
5002 // built-in operator and interpreted according to clause 5.
5003 if (Opc == BinaryOperator::Comma)
5004 break;
5005
Sebastian Redl027de2a2009-05-21 11:50:50 +00005006 // For class as left operand for assignment or compound assigment operator
5007 // do not fall through to handling in built-in, but report that no overloaded
5008 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005009 OwningExprResult Result = ExprError();
5010 if (Args[0]->getType()->isRecordType() &&
5011 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005012 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5013 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005014 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005015 } else {
5016 // No viable function; try to create a built-in operation, which will
5017 // produce an error. Then, show the non-viable candidates.
5018 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005019 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005020 assert(Result.isInvalid() &&
5021 "C++ binary operator overloading is missing candidates!");
5022 if (Result.isInvalid())
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005023 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5024 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005025 return move(Result);
5026 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005027
5028 case OR_Ambiguous:
5029 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5030 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005031 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005032 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5033 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005034 return ExprError();
5035
5036 case OR_Deleted:
5037 Diag(OpLoc, diag::err_ovl_deleted_oper)
5038 << Best->Function->isDeleted()
5039 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005040 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005041 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5042 return ExprError();
5043 }
5044
Douglas Gregor66950a32009-09-30 21:46:01 +00005045 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005046 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005047}
5048
Sebastian Redladba46e2009-10-29 20:17:01 +00005049Action::OwningExprResult
5050Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5051 SourceLocation RLoc,
5052 ExprArg Base, ExprArg Idx) {
5053 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5054 static_cast<Expr*>(Idx.get()) };
5055 DeclarationName OpName =
5056 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5057
5058 // If either side is type-dependent, create an appropriate dependent
5059 // expression.
5060 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5061
John McCalld14a8642009-11-21 08:51:07 +00005062 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005063 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5064 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005065 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005066 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005067
5068 Base.release();
5069 Idx.release();
5070 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5071 Args, 2,
5072 Context.DependentTy,
5073 RLoc));
5074 }
5075
5076 // Build an empty overload set.
5077 OverloadCandidateSet CandidateSet;
5078
5079 // Subscript can only be overloaded as a member function.
5080
5081 // Add operator candidates that are member functions.
5082 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5083
5084 // Add builtin operator candidates.
5085 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5086
5087 // Perform overload resolution.
5088 OverloadCandidateSet::iterator Best;
5089 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5090 case OR_Success: {
5091 // We found a built-in operator or an overloaded operator.
5092 FunctionDecl *FnDecl = Best->Function;
5093
5094 if (FnDecl) {
5095 // We matched an overloaded operator. Build a call to that
5096 // operator.
5097
5098 // Convert the arguments.
5099 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5100 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5101 PerformCopyInitialization(Args[1],
5102 FnDecl->getParamDecl(0)->getType(),
5103 "passing"))
5104 return ExprError();
5105
5106 // Determine the result type
5107 QualType ResultTy
5108 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5109 ResultTy = ResultTy.getNonReferenceType();
5110
5111 // Build the actual expression node.
5112 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5113 LLoc);
5114 UsualUnaryConversions(FnExpr);
5115
5116 Base.release();
5117 Idx.release();
5118 ExprOwningPtr<CXXOperatorCallExpr>
5119 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5120 FnExpr, Args, 2,
5121 ResultTy, RLoc));
5122
5123 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5124 FnDecl))
5125 return ExprError();
5126
5127 return MaybeBindToTemporary(TheCall.release());
5128 } else {
5129 // We matched a built-in operator. Convert the arguments, then
5130 // break out so that we will build the appropriate built-in
5131 // operator node.
5132 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5133 Best->Conversions[0], "passing") ||
5134 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5135 Best->Conversions[1], "passing"))
5136 return ExprError();
5137
5138 break;
5139 }
5140 }
5141
5142 case OR_No_Viable_Function: {
5143 // No viable function; try to create a built-in operation, which will
5144 // produce an error. Then, show the non-viable candidates.
5145 OwningExprResult Result =
5146 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5147 assert(Result.isInvalid() &&
5148 "C++ subscript operator overloading is missing candidates!");
5149 if (Result.isInvalid())
5150 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5151 "[]", LLoc);
5152 return move(Result);
5153 }
5154
5155 case OR_Ambiguous:
5156 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5157 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5158 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5159 "[]", LLoc);
5160 return ExprError();
5161
5162 case OR_Deleted:
5163 Diag(LLoc, diag::err_ovl_deleted_oper)
5164 << Best->Function->isDeleted() << "[]"
5165 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5166 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5167 return ExprError();
5168 }
5169
5170 // We matched a built-in operator; build it.
5171 Base.release();
5172 Idx.release();
5173 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5174 Owned(Args[1]), RLoc);
5175}
5176
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005177/// BuildCallToMemberFunction - Build a call to a member
5178/// function. MemExpr is the expression that refers to the member
5179/// function (and includes the object parameter), Args/NumArgs are the
5180/// arguments to the function call (not including the object
5181/// parameter). The caller needs to validate that the member
5182/// expression refers to a member function or an overloaded member
5183/// function.
John McCall2d74de92009-12-01 22:10:20 +00005184Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005185Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5186 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005187 unsigned NumArgs, SourceLocation *CommaLocs,
5188 SourceLocation RParenLoc) {
5189 // Dig out the member expression. This holds both the object
5190 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00005191 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5192
John McCall10eae182009-11-30 22:42:35 +00005193 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005194 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00005195 if (isa<MemberExpr>(NakedMemExpr)) {
5196 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00005197 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5198 } else {
5199 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCall2d74de92009-12-01 22:10:20 +00005200
John McCall6e9f8f62009-12-03 04:06:58 +00005201 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00005202
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005203 // Add overload candidates
5204 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00005205
John McCall2d74de92009-12-01 22:10:20 +00005206 // FIXME: avoid copy.
5207 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5208 if (UnresExpr->hasExplicitTemplateArgs()) {
5209 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5210 TemplateArgs = &TemplateArgsBuffer;
5211 }
5212
John McCall10eae182009-11-30 22:42:35 +00005213 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5214 E = UnresExpr->decls_end(); I != E; ++I) {
5215
John McCall6e9f8f62009-12-03 04:06:58 +00005216 NamedDecl *Func = *I;
5217 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5218 if (isa<UsingShadowDecl>(Func))
5219 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5220
John McCall10eae182009-11-30 22:42:35 +00005221 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00005222 // If explicit template arguments were provided, we can't call a
5223 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00005224 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00005225 continue;
5226
John McCall6e9f8f62009-12-03 04:06:58 +00005227 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5228 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005229 } else {
John McCall10eae182009-11-30 22:42:35 +00005230 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall6e9f8f62009-12-03 04:06:58 +00005231 ActingDC, TemplateArgs,
5232 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005233 CandidateSet,
5234 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005235 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005236 }
Mike Stump11289f42009-09-09 15:08:12 +00005237
John McCall10eae182009-11-30 22:42:35 +00005238 DeclarationName DeclName = UnresExpr->getMemberName();
5239
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005240 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00005241 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005242 case OR_Success:
5243 Method = cast<CXXMethodDecl>(Best->Function);
5244 break;
5245
5246 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00005247 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005248 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005249 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005250 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5251 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005252 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005253
5254 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00005255 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005256 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005257 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5258 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005259 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005260
5261 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00005262 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00005263 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005264 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005265 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5266 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005267 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005268 }
5269
Douglas Gregor51c538b2009-11-20 19:42:02 +00005270 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00005271
John McCall2d74de92009-12-01 22:10:20 +00005272 // If overload resolution picked a static member, build a
5273 // non-member call based on that function.
5274 if (Method->isStatic()) {
5275 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5276 Args, NumArgs, RParenLoc);
5277 }
5278
John McCall10eae182009-11-30 22:42:35 +00005279 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005280 }
5281
5282 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005283 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00005284 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005285 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005286 Method->getResultType().getNonReferenceType(),
5287 RParenLoc));
5288
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005289 // Check for a valid return type.
5290 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5291 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00005292 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005293
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005294 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00005295 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00005296 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005297 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCall2d74de92009-12-01 22:10:20 +00005298 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005299 MemExpr->setBase(ObjectArg);
5300
5301 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005302 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005303 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005304 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00005305 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005306
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005307 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00005308 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00005309
John McCall2d74de92009-12-01 22:10:20 +00005310 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005311}
5312
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005313/// BuildCallToObjectOfClassType - Build a call to an object of class
5314/// type (C++ [over.call.object]), which can end up invoking an
5315/// overloaded function call operator (@c operator()) or performing a
5316/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005317Sema::ExprResult
5318Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005319 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005320 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005321 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005322 SourceLocation RParenLoc) {
5323 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005324 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005325
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005326 // C++ [over.call.object]p1:
5327 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005328 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005329 // candidate functions includes at least the function call
5330 // operators of T. The function call operators of T are obtained by
5331 // ordinary lookup of the name operator() in the context of
5332 // (E).operator().
5333 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005334 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005335
5336 if (RequireCompleteType(LParenLoc, Object->getType(),
5337 PartialDiagnostic(diag::err_incomplete_object_call)
5338 << Object->getSourceRange()))
5339 return true;
5340
John McCall27b18f82009-11-17 02:14:36 +00005341 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5342 LookupQualifiedName(R, Record->getDecl());
5343 R.suppressDiagnostics();
5344
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005345 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00005346 Oper != OperEnd; ++Oper) {
John McCall6e9f8f62009-12-03 04:06:58 +00005347 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005348 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005349 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005350
Douglas Gregorab7897a2008-11-19 22:57:39 +00005351 // C++ [over.call.object]p2:
5352 // In addition, for each conversion function declared in T of the
5353 // form
5354 //
5355 // operator conversion-type-id () cv-qualifier;
5356 //
5357 // where cv-qualifier is the same cv-qualification as, or a
5358 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005359 // denotes the type "pointer to function of (P1,...,Pn) returning
5360 // R", or the type "reference to pointer to function of
5361 // (P1,...,Pn) returning R", or the type "reference to function
5362 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005363 // is also considered as a candidate function. Similarly,
5364 // surrogate call functions are added to the set of candidate
5365 // functions for each conversion function declared in an
5366 // accessible base class provided the function is not hidden
5367 // within T by another intervening declaration.
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005368 // FIXME: Look in base classes for more conversion operators!
John McCalld14a8642009-11-21 08:51:07 +00005369 const UnresolvedSet *Conversions
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005370 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00005371 for (UnresolvedSet::iterator I = Conversions->begin(),
5372 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00005373 NamedDecl *D = *I;
5374 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5375 if (isa<UsingShadowDecl>(D))
5376 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5377
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005378 // Skip over templated conversion functions; they aren't
5379 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00005380 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005381 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005382
John McCall6e9f8f62009-12-03 04:06:58 +00005383 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00005384
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005385 // Strip the reference type (if any) and then the pointer type (if
5386 // any) to get down to what might be a function type.
5387 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5388 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5389 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005390
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005391 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall6e9f8f62009-12-03 04:06:58 +00005392 AddSurrogateCandidate(Conv, ActingContext, Proto,
5393 Object->getType(), Args, NumArgs,
5394 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005395 }
Mike Stump11289f42009-09-09 15:08:12 +00005396
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005397 // Perform overload resolution.
5398 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005399 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005400 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005401 // Overload resolution succeeded; we'll build the appropriate call
5402 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005403 break;
5404
5405 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005406 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00005407 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00005408 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00005409 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005410 break;
5411
5412 case OR_Ambiguous:
5413 Diag(Object->getSourceRange().getBegin(),
5414 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005415 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005416 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5417 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005418
5419 case OR_Deleted:
5420 Diag(Object->getSourceRange().getBegin(),
5421 diag::err_ovl_deleted_object_call)
5422 << Best->Function->isDeleted()
5423 << Object->getType() << Object->getSourceRange();
5424 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5425 break;
Mike Stump11289f42009-09-09 15:08:12 +00005426 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005427
Douglas Gregorab7897a2008-11-19 22:57:39 +00005428 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005429 // We had an error; delete all of the subexpressions and return
5430 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005431 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005432 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005433 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005434 return true;
5435 }
5436
Douglas Gregorab7897a2008-11-19 22:57:39 +00005437 if (Best->Function == 0) {
5438 // Since there is no function declaration, this is one of the
5439 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00005440 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00005441 = cast<CXXConversionDecl>(
5442 Best->Conversions[0].UserDefined.ConversionFunction);
5443
5444 // We selected one of the surrogate functions that converts the
5445 // object parameter to a function pointer. Perform the conversion
5446 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005447
5448 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005449 // and then call it.
Eli Friedmana958a012009-12-09 04:52:43 +00005450 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005451
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005452 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005453 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5454 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005455 }
5456
5457 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5458 // that calls this method, using Object for the implicit object
5459 // parameter and passing along the remaining arguments.
5460 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00005461 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005462
5463 unsigned NumArgsInProto = Proto->getNumArgs();
5464 unsigned NumArgsToCheck = NumArgs;
5465
5466 // Build the full argument list for the method call (the
5467 // implicit object parameter is placed at the beginning of the
5468 // list).
5469 Expr **MethodArgs;
5470 if (NumArgs < NumArgsInProto) {
5471 NumArgsToCheck = NumArgsInProto;
5472 MethodArgs = new Expr*[NumArgsInProto + 1];
5473 } else {
5474 MethodArgs = new Expr*[NumArgs + 1];
5475 }
5476 MethodArgs[0] = Object;
5477 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5478 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00005479
5480 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00005481 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005482 UsualUnaryConversions(NewFn);
5483
5484 // Once we've built TheCall, all of the expressions are properly
5485 // owned.
5486 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005487 ExprOwningPtr<CXXOperatorCallExpr>
5488 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005489 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005490 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005491 delete [] MethodArgs;
5492
Anders Carlsson3d5829c2009-10-13 21:49:31 +00005493 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5494 Method))
5495 return true;
5496
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005497 // We may have default arguments. If so, we need to allocate more
5498 // slots in the call for them.
5499 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005500 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005501 else if (NumArgs > NumArgsInProto)
5502 NumArgsToCheck = NumArgsInProto;
5503
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005504 bool IsError = false;
5505
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005506 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005507 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005508 TheCall->setArg(0, Object);
5509
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005510
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005511 // Check the argument types.
5512 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005513 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005514 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005515 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00005516
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005517 // Pass the argument.
5518 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005519 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005520 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00005521 OwningExprResult DefArg
5522 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5523 if (DefArg.isInvalid()) {
5524 IsError = true;
5525 break;
5526 }
5527
5528 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005529 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005530
5531 TheCall->setArg(i + 1, Arg);
5532 }
5533
5534 // If this is a variadic call, handle args passed through "...".
5535 if (Proto->isVariadic()) {
5536 // Promote the arguments (C99 6.5.2.2p7).
5537 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5538 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005539 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005540 TheCall->setArg(i + 1, Arg);
5541 }
5542 }
5543
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005544 if (IsError) return true;
5545
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005546 if (CheckFunctionCall(Method, TheCall.get()))
5547 return true;
5548
Anders Carlsson1c83deb2009-08-16 03:53:54 +00005549 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005550}
5551
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005552/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00005553/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005554/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00005555Sema::OwningExprResult
5556Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5557 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005558 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00005559
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005560 // C++ [over.ref]p1:
5561 //
5562 // [...] An expression x->m is interpreted as (x.operator->())->m
5563 // for a class object x of type T if T::operator->() exists and if
5564 // the operator is selected as the best match function by the
5565 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005566 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5567 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005568 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00005569
Eli Friedman132e70b2009-11-18 01:28:03 +00005570 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5571 PDiag(diag::err_typecheck_incomplete_tag)
5572 << Base->getSourceRange()))
5573 return ExprError();
5574
John McCall27b18f82009-11-17 02:14:36 +00005575 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5576 LookupQualifiedName(R, BaseRecord->getDecl());
5577 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00005578
5579 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00005580 Oper != OperEnd; ++Oper) {
5581 NamedDecl *D = *Oper;
5582 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5583 if (isa<UsingShadowDecl>(D))
5584 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5585
5586 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
5587 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005588 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00005589 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005590
5591 // Perform overload resolution.
5592 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005593 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005594 case OR_Success:
5595 // Overload resolution succeeded; we'll build the call below.
5596 break;
5597
5598 case OR_No_Viable_Function:
5599 if (CandidateSet.empty())
5600 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00005601 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005602 else
5603 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00005604 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005605 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00005606 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005607
5608 case OR_Ambiguous:
5609 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005610 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005611 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005612 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005613
5614 case OR_Deleted:
5615 Diag(OpLoc, diag::err_ovl_deleted_oper)
5616 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005617 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005618 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005619 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005620 }
5621
5622 // Convert the object parameter.
5623 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005624 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005625 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005626
5627 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005628 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005629
5630 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005631 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5632 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005633 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005634
5635 QualType ResultTy = Method->getResultType().getNonReferenceType();
5636 ExprOwningPtr<CXXOperatorCallExpr>
5637 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5638 &Base, 1, ResultTy, OpLoc));
5639
5640 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5641 Method))
5642 return ExprError();
5643 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005644}
5645
Douglas Gregorcd695e52008-11-10 20:40:00 +00005646/// FixOverloadedFunctionReference - E is an expression that refers to
5647/// a C++ overloaded function (possibly with some parentheses and
5648/// perhaps a '&' around it). We have resolved the overloaded function
5649/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005650/// refer (possibly indirectly) to Fn. Returns the new expr.
5651Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005652 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00005653 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5654 if (SubExpr == PE->getSubExpr())
5655 return PE->Retain();
5656
5657 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
5658 }
5659
5660 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5661 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00005662 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00005663 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00005664 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00005665 if (SubExpr == ICE->getSubExpr())
5666 return ICE->Retain();
5667
5668 return new (Context) ImplicitCastExpr(ICE->getType(),
5669 ICE->getCastKind(),
5670 SubExpr,
5671 ICE->isLvalueCast());
5672 }
5673
5674 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005675 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005676 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005677 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5678 if (Method->isStatic()) {
5679 // Do nothing: static member functions aren't any different
5680 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00005681 } else {
John McCalle66edc12009-11-24 19:00:30 +00005682 // Fix the sub expression, which really has to be an
5683 // UnresolvedLookupExpr holding an overloaded member function
5684 // or template.
John McCalld14a8642009-11-21 08:51:07 +00005685 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5686 if (SubExpr == UnOp->getSubExpr())
5687 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00005688
John McCalld14a8642009-11-21 08:51:07 +00005689 assert(isa<DeclRefExpr>(SubExpr)
5690 && "fixed to something other than a decl ref");
5691 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
5692 && "fixed to a member ref with no nested name qualifier");
5693
5694 // We have taken the address of a pointer to member
5695 // function. Perform the computation here so that we get the
5696 // appropriate pointer to member type.
5697 QualType ClassType
5698 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5699 QualType MemPtrType
5700 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
5701
5702 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5703 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005704 }
5705 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00005706 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5707 if (SubExpr == UnOp->getSubExpr())
5708 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005709
Douglas Gregor51c538b2009-11-20 19:42:02 +00005710 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5711 Context.getPointerType(SubExpr->getType()),
5712 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00005713 }
John McCalld14a8642009-11-21 08:51:07 +00005714
5715 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00005716 // FIXME: avoid copy.
5717 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00005718 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00005719 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
5720 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00005721 }
5722
John McCalld14a8642009-11-21 08:51:07 +00005723 return DeclRefExpr::Create(Context,
5724 ULE->getQualifier(),
5725 ULE->getQualifierRange(),
5726 Fn,
5727 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00005728 Fn->getType(),
5729 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00005730 }
5731
John McCall10eae182009-11-30 22:42:35 +00005732 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00005733 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00005734 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5735 if (MemExpr->hasExplicitTemplateArgs()) {
5736 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5737 TemplateArgs = &TemplateArgsBuffer;
5738 }
John McCall6b51f282009-11-23 01:53:49 +00005739
John McCall2d74de92009-12-01 22:10:20 +00005740 Expr *Base;
5741
5742 // If we're filling in
5743 if (MemExpr->isImplicitAccess()) {
5744 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
5745 return DeclRefExpr::Create(Context,
5746 MemExpr->getQualifier(),
5747 MemExpr->getQualifierRange(),
5748 Fn,
5749 MemExpr->getMemberLoc(),
5750 Fn->getType(),
5751 TemplateArgs);
5752 } else
5753 Base = new (Context) CXXThisExpr(SourceLocation(),
5754 MemExpr->getBaseType());
5755 } else
5756 Base = MemExpr->getBase()->Retain();
5757
5758 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00005759 MemExpr->isArrow(),
5760 MemExpr->getQualifier(),
5761 MemExpr->getQualifierRange(),
5762 Fn,
John McCall6b51f282009-11-23 01:53:49 +00005763 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00005764 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00005765 Fn->getType());
5766 }
5767
Douglas Gregor51c538b2009-11-20 19:42:02 +00005768 assert(false && "Invalid reference to overloaded function");
5769 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00005770}
5771
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005772} // end namespace clang