blob: 47393f7b23441bbaef67fb50b5190459c79c9a66 [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
265// it does return false and Old is an overload set, MatchedDecl will
266// be set to point to the FunctionDecl that New cannot be overloaded
267// with.
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.
289bool
John McCall3d988d92009-12-02 08:47:38 +0000290Sema::IsOverload(FunctionDecl *New, LookupResult &Old, NamedDecl *&Match) {
291 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 McCall3d988d92009-12-02 08:47:38 +0000296 Match = OldT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000297 return false;
298 }
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 McCall3d988d92009-12-02 08:47:38 +0000301 Match = OldF;
John McCall1f82f242009-11-18 22:49:29 +0000302 return false;
303 }
304 } else {
305 // (C++ 13p1):
306 // Only function declarations can be overloaded; object and type
307 // declarations cannot be overloaded.
John McCall3d988d92009-12-02 08:47:38 +0000308 Match = OldD;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000309 return false;
John McCall1f82f242009-11-18 22:49:29 +0000310 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000311 }
John McCall1f82f242009-11-18 22:49:29 +0000312
313 return true;
314}
315
316bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
317 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
318 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
319
320 // C++ [temp.fct]p2:
321 // A function template can be overloaded with other function templates
322 // and with normal (non-template) functions.
323 if ((OldTemplate == 0) != (NewTemplate == 0))
324 return true;
325
326 // Is the function New an overload of the function Old?
327 QualType OldQType = Context.getCanonicalType(Old->getType());
328 QualType NewQType = Context.getCanonicalType(New->getType());
329
330 // Compare the signatures (C++ 1.3.10) of the two functions to
331 // determine whether they are overloads. If we find any mismatch
332 // in the signature, they are overloads.
333
334 // If either of these functions is a K&R-style function (no
335 // prototype), then we consider them to have matching signatures.
336 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
337 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
338 return false;
339
340 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
341 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
342
343 // The signature of a function includes the types of its
344 // parameters (C++ 1.3.10), which includes the presence or absence
345 // of the ellipsis; see C++ DR 357).
346 if (OldQType != NewQType &&
347 (OldType->getNumArgs() != NewType->getNumArgs() ||
348 OldType->isVariadic() != NewType->isVariadic() ||
349 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
350 NewType->arg_type_begin())))
351 return true;
352
353 // C++ [temp.over.link]p4:
354 // The signature of a function template consists of its function
355 // signature, its return type and its template parameter list. The names
356 // of the template parameters are significant only for establishing the
357 // relationship between the template parameters and the rest of the
358 // signature.
359 //
360 // We check the return type and template parameter lists for function
361 // templates first; the remaining checks follow.
362 if (NewTemplate &&
363 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
364 OldTemplate->getTemplateParameters(),
365 false, TPL_TemplateMatch) ||
366 OldType->getResultType() != NewType->getResultType()))
367 return true;
368
369 // If the function is a class member, its signature includes the
370 // cv-qualifiers (if any) on the function itself.
371 //
372 // As part of this, also check whether one of the member functions
373 // is static, in which case they are not overloads (C++
374 // 13.1p2). While not part of the definition of the signature,
375 // this check is important to determine whether these functions
376 // can be overloaded.
377 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
378 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
379 if (OldMethod && NewMethod &&
380 !OldMethod->isStatic() && !NewMethod->isStatic() &&
381 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
382 return true;
383
384 // The signatures match; this is not an overload.
385 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000386}
387
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000388/// TryImplicitConversion - Attempt to perform an implicit conversion
389/// from the given expression (Expr) to the given type (ToType). This
390/// function returns an implicit conversion sequence that can be used
391/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000392///
393/// void f(float f);
394/// void g(int i) { f(i); }
395///
396/// this routine would produce an implicit conversion sequence to
397/// describe the initialization of f from i, which will be a standard
398/// conversion sequence containing an lvalue-to-rvalue conversion (C++
399/// 4.1) followed by a floating-integral conversion (C++ 4.9).
400//
401/// Note that this routine only determines how the conversion can be
402/// performed; it does not actually perform the conversion. As such,
403/// it will not produce any diagnostics if no conversion is available,
404/// but will instead return an implicit conversion sequence of kind
405/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000406///
407/// If @p SuppressUserConversions, then user-defined conversions are
408/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000409/// If @p AllowExplicit, then explicit user-defined conversions are
410/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000411/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
412/// no matter its actual lvalueness.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000413/// If @p UserCast, the implicit conversion is being done for a user-specified
414/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000415ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000416Sema::TryImplicitConversion(Expr* From, QualType ToType,
417 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000418 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000419 bool InOverloadResolution,
420 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000421 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000422 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000423 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000424 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000425 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000426 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000427 (UserDefResult = IsUserDefinedConversion(From, ToType,
428 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000429 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000430 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000431 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000432 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000433 // C++ [over.ics.user]p4:
434 // A conversion of an expression of class type to the same class
435 // type is given Exact Match rank, and a conversion of an
436 // expression of class type to a base class of that type is
437 // given Conversion rank, in spite of the fact that a copy
438 // constructor (i.e., a user-defined conversion function) is
439 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000440 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000441 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000442 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000443 = Context.getCanonicalType(From->getType().getUnqualifiedType());
444 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
445 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000446 // Turn this into a "standard" conversion sequence, so that it
447 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000448 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
449 ICS.Standard.setAsIdentityConversion();
450 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
451 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000452 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000453 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000454 ICS.Standard.Second = ICK_Derived_To_Base;
455 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000456 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000457
458 // C++ [over.best.ics]p4:
459 // However, when considering the argument of a user-defined
460 // conversion function that is a candidate by 13.3.1.3 when
461 // invoked for the copying of the temporary in the second step
462 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
463 // 13.3.1.6 in all cases, only standard conversion sequences and
464 // ellipsis conversion sequences are allowed.
465 if (SuppressUserConversions &&
466 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
467 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000468 } else {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000469 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000470 if (UserDefResult == OR_Ambiguous) {
471 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
472 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian574de2c2009-10-12 17:51:19 +0000473 if (Cand->Viable)
474 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000475 }
476 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000477
478 return ICS;
479}
480
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000481/// \brief Determine whether the conversion from FromType to ToType is a valid
482/// conversion that strips "noreturn" off the nested function type.
483static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
484 QualType ToType, QualType &ResultTy) {
485 if (Context.hasSameUnqualifiedType(FromType, ToType))
486 return false;
487
488 // Strip the noreturn off the type we're converting from; noreturn can
489 // safely be removed.
490 FromType = Context.getNoReturnType(FromType, false);
491 if (!Context.hasSameUnqualifiedType(FromType, ToType))
492 return false;
493
494 ResultTy = FromType;
495 return true;
496}
497
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000498/// IsStandardConversion - Determines whether there is a standard
499/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
500/// expression From to the type ToType. Standard conversion sequences
501/// only consider non-class types; for conversions that involve class
502/// types, use TryImplicitConversion. If a conversion exists, SCS will
503/// contain the standard conversion sequence required to perform this
504/// conversion and this routine will return true. Otherwise, this
505/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000506bool
507Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000508 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000509 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000510 QualType FromType = From->getType();
511
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000512 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000513 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000514 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000515 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000516 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000517 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000518
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000519 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000520 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000521 if (FromType->isRecordType() || ToType->isRecordType()) {
522 if (getLangOptions().CPlusPlus)
523 return false;
524
Mike Stump11289f42009-09-09 15:08:12 +0000525 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000526 }
527
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528 // The first conversion can be an lvalue-to-rvalue conversion,
529 // array-to-pointer conversion, or function-to-pointer conversion
530 // (C++ 4p1).
531
Mike Stump11289f42009-09-09 15:08:12 +0000532 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000533 // An lvalue (3.10) of a non-function, non-array type T can be
534 // converted to an rvalue.
535 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000536 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000537 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000538 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000539 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000540
541 // If T is a non-class type, the type of the rvalue is the
542 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000543 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
544 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000545 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000546 } else if (FromType->isArrayType()) {
547 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000548 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000549
550 // An lvalue or rvalue of type "array of N T" or "array of unknown
551 // bound of T" can be converted to an rvalue of type "pointer to
552 // T" (C++ 4.2p1).
553 FromType = Context.getArrayDecayedType(FromType);
554
555 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
556 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000557 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000558
559 // For the purpose of ranking in overload resolution
560 // (13.3.3.1.1), this conversion is considered an
561 // array-to-pointer conversion followed by a qualification
562 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000563 SCS.Second = ICK_Identity;
564 SCS.Third = ICK_Qualification;
565 SCS.ToTypePtr = ToType.getAsOpaquePtr();
566 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000567 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000568 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
569 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000570 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000571
572 // An lvalue of function type T can be converted to an rvalue of
573 // type "pointer to T." The result is a pointer to the
574 // function. (C++ 4.3p1).
575 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000576 } else if (FunctionDecl *Fn
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000577 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000578 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000579 SCS.First = ICK_Function_To_Pointer;
580
581 // We were able to resolve the address of the overloaded function,
582 // so we can convert to the type of that function.
583 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000584 if (ToType->isLValueReferenceType())
585 FromType = Context.getLValueReferenceType(FromType);
586 else if (ToType->isRValueReferenceType())
587 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000588 else if (ToType->isMemberPointerType()) {
589 // Resolve address only succeeds if both sides are member pointers,
590 // but it doesn't have to be the same class. See DR 247.
591 // Note that this means that the type of &Derived::fn can be
592 // Ret (Base::*)(Args) if the fn overload actually found is from the
593 // base class, even if it was brought into the derived class via a
594 // using declaration. The standard isn't clear on this issue at all.
595 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
596 FromType = Context.getMemberPointerType(FromType,
597 Context.getTypeDeclType(M->getParent()).getTypePtr());
598 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000599 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000600 } else {
601 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000602 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000603 }
604
605 // The second conversion can be an integral promotion, floating
606 // point promotion, integral conversion, floating point conversion,
607 // floating-integral conversion, pointer conversion,
608 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000609 // For overloading in C, this can also be a "compatible-type"
610 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000611 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000612 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000613 // The unqualified versions of the types are the same: there's no
614 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000615 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000616 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000617 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000618 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000619 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000620 } else if (IsFloatingPointPromotion(FromType, ToType)) {
621 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000622 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000623 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000624 } else if (IsComplexPromotion(FromType, ToType)) {
625 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000626 SCS.Second = ICK_Complex_Promotion;
627 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000628 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000629 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000630 // Integral conversions (C++ 4.7).
631 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000632 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000633 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000634 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
635 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000636 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000637 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000638 } else if (FromType->isComplexType() && ToType->isComplexType()) {
639 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000640 SCS.Second = ICK_Complex_Conversion;
641 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000642 } else if ((FromType->isFloatingType() &&
643 ToType->isIntegralType() && (!ToType->isBooleanType() &&
644 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000645 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000646 ToType->isFloatingType())) {
647 // Floating-integral conversions (C++ 4.9).
648 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000649 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000650 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000651 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
652 (ToType->isComplexType() && FromType->isArithmeticType())) {
653 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000654 SCS.Second = ICK_Complex_Real;
655 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000656 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
657 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000658 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000659 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000660 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000661 } else if (IsMemberPointerConversion(From, FromType, ToType,
662 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000663 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000664 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000665 } else if (ToType->isBooleanType() &&
666 (FromType->isArithmeticType() ||
667 FromType->isEnumeralType() ||
668 FromType->isPointerType() ||
669 FromType->isBlockPointerType() ||
670 FromType->isMemberPointerType() ||
671 FromType->isNullPtrType())) {
672 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000673 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000674 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000675 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000676 Context.typesAreCompatible(ToType, FromType)) {
677 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000678 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000679 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
680 // Treat a conversion that strips "noreturn" as an identity conversion.
681 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000682 } else {
683 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000684 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000685 }
686
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000687 QualType CanonFrom;
688 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000689 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000690 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000691 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000692 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000693 CanonFrom = Context.getCanonicalType(FromType);
694 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000695 } else {
696 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000697 SCS.Third = ICK_Identity;
698
Mike Stump11289f42009-09-09 15:08:12 +0000699 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000700 // [...] Any difference in top-level cv-qualification is
701 // subsumed by the initialization itself and does not constitute
702 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000703 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000704 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000705 if (CanonFrom.getLocalUnqualifiedType()
706 == CanonTo.getLocalUnqualifiedType() &&
707 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000708 FromType = ToType;
709 CanonFrom = CanonTo;
710 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000711 }
712
713 // If we have not converted the argument type to the parameter type,
714 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000715 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000716 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000717
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000718 SCS.ToTypePtr = FromType.getAsOpaquePtr();
719 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000720}
721
722/// IsIntegralPromotion - Determines whether the conversion from the
723/// expression From (whose potentially-adjusted type is FromType) to
724/// ToType is an integral promotion (C++ 4.5). If so, returns true and
725/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000726bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000727 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000728 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000729 if (!To) {
730 return false;
731 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000732
733 // An rvalue of type char, signed char, unsigned char, short int, or
734 // unsigned short int can be converted to an rvalue of type int if
735 // int can represent all the values of the source type; otherwise,
736 // the source rvalue can be converted to an rvalue of type unsigned
737 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000738 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000739 if (// We can promote any signed, promotable integer type to an int
740 (FromType->isSignedIntegerType() ||
741 // We can promote any unsigned integer type whose size is
742 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000743 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000744 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000745 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000746 }
747
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000748 return To->getKind() == BuiltinType::UInt;
749 }
750
751 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
752 // can be converted to an rvalue of the first of the following types
753 // that can represent all the values of its underlying type: int,
754 // unsigned int, long, or unsigned long (C++ 4.5p2).
755 if ((FromType->isEnumeralType() || FromType->isWideCharType())
756 && ToType->isIntegerType()) {
757 // Determine whether the type we're converting from is signed or
758 // unsigned.
759 bool FromIsSigned;
760 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall9dd450b2009-09-21 23:43:11 +0000761 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000762 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
763 FromIsSigned = UnderlyingType->isSignedIntegerType();
764 } else {
765 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
766 FromIsSigned = true;
767 }
768
769 // The types we'll try to promote to, in the appropriate
770 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000771 QualType PromoteTypes[6] = {
772 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000773 Context.LongTy, Context.UnsignedLongTy ,
774 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000775 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000776 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000777 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
778 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000779 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000780 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
781 // We found the type that we can promote to. If this is the
782 // type we wanted, we have a promotion. Otherwise, no
783 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000784 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000785 }
786 }
787 }
788
789 // An rvalue for an integral bit-field (9.6) can be converted to an
790 // rvalue of type int if int can represent all the values of the
791 // bit-field; otherwise, it can be converted to unsigned int if
792 // unsigned int can represent all the values of the bit-field. If
793 // the bit-field is larger yet, no integral promotion applies to
794 // it. If the bit-field has an enumerated type, it is treated as any
795 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000796 // FIXME: We should delay checking of bit-fields until we actually perform the
797 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000798 using llvm::APSInt;
799 if (From)
800 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000801 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000802 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
803 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
804 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
805 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000806
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000807 // Are we promoting to an int from a bitfield that fits in an int?
808 if (BitWidth < ToSize ||
809 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
810 return To->getKind() == BuiltinType::Int;
811 }
Mike Stump11289f42009-09-09 15:08:12 +0000812
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000813 // Are we promoting to an unsigned int from an unsigned bitfield
814 // that fits into an unsigned int?
815 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
816 return To->getKind() == BuiltinType::UInt;
817 }
Mike Stump11289f42009-09-09 15:08:12 +0000818
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000819 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000820 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000821 }
Mike Stump11289f42009-09-09 15:08:12 +0000822
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000823 // An rvalue of type bool can be converted to an rvalue of type int,
824 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000825 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000826 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000827 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000828
829 return false;
830}
831
832/// IsFloatingPointPromotion - Determines whether the conversion from
833/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
834/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000835bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000836 /// An rvalue of type float can be converted to an rvalue of type
837 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000838 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
839 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000840 if (FromBuiltin->getKind() == BuiltinType::Float &&
841 ToBuiltin->getKind() == BuiltinType::Double)
842 return true;
843
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000844 // C99 6.3.1.5p1:
845 // When a float is promoted to double or long double, or a
846 // double is promoted to long double [...].
847 if (!getLangOptions().CPlusPlus &&
848 (FromBuiltin->getKind() == BuiltinType::Float ||
849 FromBuiltin->getKind() == BuiltinType::Double) &&
850 (ToBuiltin->getKind() == BuiltinType::LongDouble))
851 return true;
852 }
853
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000854 return false;
855}
856
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000857/// \brief Determine if a conversion is a complex promotion.
858///
859/// A complex promotion is defined as a complex -> complex conversion
860/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000861/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000862bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000863 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000864 if (!FromComplex)
865 return false;
866
John McCall9dd450b2009-09-21 23:43:11 +0000867 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000868 if (!ToComplex)
869 return false;
870
871 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000872 ToComplex->getElementType()) ||
873 IsIntegralPromotion(0, FromComplex->getElementType(),
874 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000875}
876
Douglas Gregor237f96c2008-11-26 23:31:11 +0000877/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
878/// the pointer type FromPtr to a pointer to type ToPointee, with the
879/// same type qualifiers as FromPtr has on its pointee type. ToType,
880/// if non-empty, will be a pointer to ToType that may or may not have
881/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000882static QualType
883BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000884 QualType ToPointee, QualType ToType,
885 ASTContext &Context) {
886 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
887 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000888 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000889
890 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000891 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000892 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000893 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000894 return ToType;
895
896 // Build a pointer to ToPointee. It has the right qualifiers
897 // already.
898 return Context.getPointerType(ToPointee);
899 }
900
901 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000902 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000903 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
904 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000905}
906
Mike Stump11289f42009-09-09 15:08:12 +0000907static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000908 bool InOverloadResolution,
909 ASTContext &Context) {
910 // Handle value-dependent integral null pointer constants correctly.
911 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
912 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
913 Expr->getType()->isIntegralType())
914 return !InOverloadResolution;
915
Douglas Gregor56751b52009-09-25 04:25:58 +0000916 return Expr->isNullPointerConstant(Context,
917 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
918 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000919}
Mike Stump11289f42009-09-09 15:08:12 +0000920
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000921/// IsPointerConversion - Determines whether the conversion of the
922/// expression From, which has the (possibly adjusted) type FromType,
923/// can be converted to the type ToType via a pointer conversion (C++
924/// 4.10). If so, returns true and places the converted type (that
925/// might differ from ToType in its cv-qualifiers at some level) into
926/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000927///
Douglas Gregora29dc052008-11-27 01:19:21 +0000928/// This routine also supports conversions to and from block pointers
929/// and conversions with Objective-C's 'id', 'id<protocols...>', and
930/// pointers to interfaces. FIXME: Once we've determined the
931/// appropriate overloading rules for Objective-C, we may want to
932/// split the Objective-C checks into a different routine; however,
933/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000934/// conversions, so for now they live here. IncompatibleObjC will be
935/// set if the conversion is an allowed Objective-C conversion that
936/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000937bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000938 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000939 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000940 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000941 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000942 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
943 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000944
Mike Stump11289f42009-09-09 15:08:12 +0000945 // Conversion from a null pointer constant to any Objective-C pointer type.
946 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000947 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000948 ConvertedType = ToType;
949 return true;
950 }
951
Douglas Gregor231d1c62008-11-27 00:15:41 +0000952 // Blocks: Block pointers can be converted to void*.
953 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000954 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000955 ConvertedType = ToType;
956 return true;
957 }
958 // Blocks: A null pointer constant can be converted to a block
959 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000960 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000961 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000962 ConvertedType = ToType;
963 return true;
964 }
965
Sebastian Redl576fd422009-05-10 18:38:11 +0000966 // If the left-hand-side is nullptr_t, the right side can be a null
967 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000968 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000969 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000970 ConvertedType = ToType;
971 return true;
972 }
973
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000974 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000975 if (!ToTypePtr)
976 return false;
977
978 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000979 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000980 ConvertedType = ToType;
981 return true;
982 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000983
Douglas Gregor237f96c2008-11-26 23:31:11 +0000984 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000985 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000986 if (!FromTypePtr)
987 return false;
988
989 QualType FromPointeeType = FromTypePtr->getPointeeType();
990 QualType ToPointeeType = ToTypePtr->getPointeeType();
991
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000992 // An rvalue of type "pointer to cv T," where T is an object type,
993 // can be converted to an rvalue of type "pointer to cv void" (C++
994 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000995 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000996 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000997 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000998 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000999 return true;
1000 }
1001
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001002 // When we're overloading in C, we allow a special kind of pointer
1003 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001004 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001005 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001006 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001007 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001008 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001009 return true;
1010 }
1011
Douglas Gregor5c407d92008-10-23 00:40:37 +00001012 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001013 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001014 // An rvalue of type "pointer to cv D," where D is a class type,
1015 // can be converted to an rvalue of type "pointer to cv B," where
1016 // B is a base class (clause 10) of D. If B is an inaccessible
1017 // (clause 11) or ambiguous (10.2) base class of D, a program that
1018 // necessitates this conversion is ill-formed. The result of the
1019 // conversion is a pointer to the base class sub-object of the
1020 // derived class object. The null pointer value is converted to
1021 // the null pointer value of the destination type.
1022 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001023 // Note that we do not check for ambiguity or inaccessibility
1024 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001025 if (getLangOptions().CPlusPlus &&
1026 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001027 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001028 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001029 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001030 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001031 ToType, Context);
1032 return true;
1033 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001034
Douglas Gregora119f102008-12-19 19:13:09 +00001035 return false;
1036}
1037
1038/// isObjCPointerConversion - Determines whether this is an
1039/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1040/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001041bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001042 QualType& ConvertedType,
1043 bool &IncompatibleObjC) {
1044 if (!getLangOptions().ObjC1)
1045 return false;
1046
Steve Naroff7cae42b2009-07-10 23:34:53 +00001047 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001048 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001049 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001050 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001051
Steve Naroff7cae42b2009-07-10 23:34:53 +00001052 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001053 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001054 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001055 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001056 ConvertedType = ToType;
1057 return true;
1058 }
1059 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001060 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001061 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001062 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001063 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001064 ConvertedType = ToType;
1065 return true;
1066 }
1067 // Objective C++: We're able to convert from a pointer to an
1068 // interface to a pointer to a different interface.
1069 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1070 ConvertedType = ToType;
1071 return true;
1072 }
1073
1074 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1075 // Okay: this is some kind of implicit downcast of Objective-C
1076 // interfaces, which is permitted. However, we're going to
1077 // complain about it.
1078 IncompatibleObjC = true;
1079 ConvertedType = FromType;
1080 return true;
1081 }
Mike Stump11289f42009-09-09 15:08:12 +00001082 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001083 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001084 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001085 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001086 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001087 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001088 ToPointeeType = ToBlockPtr->getPointeeType();
1089 else
Douglas Gregora119f102008-12-19 19:13:09 +00001090 return false;
1091
Douglas Gregor033f56d2008-12-23 00:53:59 +00001092 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001093 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001094 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001095 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001096 FromPointeeType = FromBlockPtr->getPointeeType();
1097 else
Douglas Gregora119f102008-12-19 19:13:09 +00001098 return false;
1099
Douglas Gregora119f102008-12-19 19:13:09 +00001100 // If we have pointers to pointers, recursively check whether this
1101 // is an Objective-C conversion.
1102 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1103 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1104 IncompatibleObjC)) {
1105 // We always complain about this conversion.
1106 IncompatibleObjC = true;
1107 ConvertedType = ToType;
1108 return true;
1109 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001110 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001111 // differences in the argument and result types are in Objective-C
1112 // pointer conversions. If so, we permit the conversion (but
1113 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001114 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001115 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001116 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001117 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001118 if (FromFunctionType && ToFunctionType) {
1119 // If the function types are exactly the same, this isn't an
1120 // Objective-C pointer conversion.
1121 if (Context.getCanonicalType(FromPointeeType)
1122 == Context.getCanonicalType(ToPointeeType))
1123 return false;
1124
1125 // Perform the quick checks that will tell us whether these
1126 // function types are obviously different.
1127 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1128 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1129 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1130 return false;
1131
1132 bool HasObjCConversion = false;
1133 if (Context.getCanonicalType(FromFunctionType->getResultType())
1134 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1135 // Okay, the types match exactly. Nothing to do.
1136 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1137 ToFunctionType->getResultType(),
1138 ConvertedType, IncompatibleObjC)) {
1139 // Okay, we have an Objective-C pointer conversion.
1140 HasObjCConversion = true;
1141 } else {
1142 // Function types are too different. Abort.
1143 return false;
1144 }
Mike Stump11289f42009-09-09 15:08:12 +00001145
Douglas Gregora119f102008-12-19 19:13:09 +00001146 // Check argument types.
1147 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1148 ArgIdx != NumArgs; ++ArgIdx) {
1149 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1150 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1151 if (Context.getCanonicalType(FromArgType)
1152 == Context.getCanonicalType(ToArgType)) {
1153 // Okay, the types match exactly. Nothing to do.
1154 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1155 ConvertedType, IncompatibleObjC)) {
1156 // Okay, we have an Objective-C pointer conversion.
1157 HasObjCConversion = true;
1158 } else {
1159 // Argument types are too different. Abort.
1160 return false;
1161 }
1162 }
1163
1164 if (HasObjCConversion) {
1165 // We had an Objective-C conversion. Allow this pointer
1166 // conversion, but complain about it.
1167 ConvertedType = ToType;
1168 IncompatibleObjC = true;
1169 return true;
1170 }
1171 }
1172
Sebastian Redl72b597d2009-01-25 19:43:20 +00001173 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001174}
1175
Douglas Gregor39c16d42008-10-24 04:54:22 +00001176/// CheckPointerConversion - Check the pointer conversion from the
1177/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001178/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001179/// conversions for which IsPointerConversion has already returned
1180/// true. It returns true and produces a diagnostic if there was an
1181/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001182bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001183 CastExpr::CastKind &Kind,
1184 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001185 QualType FromType = From->getType();
1186
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001187 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1188 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001189 QualType FromPointeeType = FromPtrType->getPointeeType(),
1190 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001191
Douglas Gregor39c16d42008-10-24 04:54:22 +00001192 if (FromPointeeType->isRecordType() &&
1193 ToPointeeType->isRecordType()) {
1194 // We must have a derived-to-base conversion. Check an
1195 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001196 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1197 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001198 From->getSourceRange(),
1199 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001200 return true;
1201
1202 // The conversion was successful.
1203 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001204 }
1205 }
Mike Stump11289f42009-09-09 15:08:12 +00001206 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001207 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001208 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001209 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001210 // Objective-C++ conversions are always okay.
1211 // FIXME: We should have a different class of conversions for the
1212 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001213 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001214 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001215
Steve Naroff7cae42b2009-07-10 23:34:53 +00001216 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001217 return false;
1218}
1219
Sebastian Redl72b597d2009-01-25 19:43:20 +00001220/// IsMemberPointerConversion - Determines whether the conversion of the
1221/// expression From, which has the (possibly adjusted) type FromType, can be
1222/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1223/// If so, returns true and places the converted type (that might differ from
1224/// ToType in its cv-qualifiers at some level) into ConvertedType.
1225bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001226 QualType ToType,
1227 bool InOverloadResolution,
1228 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001229 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001230 if (!ToTypePtr)
1231 return false;
1232
1233 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001234 if (From->isNullPointerConstant(Context,
1235 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1236 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001237 ConvertedType = ToType;
1238 return true;
1239 }
1240
1241 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001242 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001243 if (!FromTypePtr)
1244 return false;
1245
1246 // A pointer to member of B can be converted to a pointer to member of D,
1247 // where D is derived from B (C++ 4.11p2).
1248 QualType FromClass(FromTypePtr->getClass(), 0);
1249 QualType ToClass(ToTypePtr->getClass(), 0);
1250 // FIXME: What happens when these are dependent? Is this function even called?
1251
1252 if (IsDerivedFrom(ToClass, FromClass)) {
1253 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1254 ToClass.getTypePtr());
1255 return true;
1256 }
1257
1258 return false;
1259}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001260
Sebastian Redl72b597d2009-01-25 19:43:20 +00001261/// CheckMemberPointerConversion - Check the member pointer conversion from the
1262/// expression From to the type ToType. This routine checks for ambiguous or
1263/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1264/// for which IsMemberPointerConversion has already returned true. It returns
1265/// true and produces a diagnostic if there was an error, or returns false
1266/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001267bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001268 CastExpr::CastKind &Kind,
1269 bool IgnoreBaseAccess) {
1270 (void)IgnoreBaseAccess;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001271 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001272 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001273 if (!FromPtrType) {
1274 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001275 assert(From->isNullPointerConstant(Context,
1276 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001277 "Expr must be null pointer constant!");
1278 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001279 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001280 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001281
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001282 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001283 assert(ToPtrType && "No member pointer cast has a target type "
1284 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001285
Sebastian Redled8f2002009-01-28 18:33:18 +00001286 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1287 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001288
Sebastian Redled8f2002009-01-28 18:33:18 +00001289 // FIXME: What about dependent types?
1290 assert(FromClass->isRecordType() && "Pointer into non-class.");
1291 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001292
Douglas Gregor36d1b142009-10-06 17:59:45 +00001293 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1294 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001295 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1296 assert(DerivationOkay &&
1297 "Should not have been called if derivation isn't OK.");
1298 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001299
Sebastian Redled8f2002009-01-28 18:33:18 +00001300 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1301 getUnqualifiedType())) {
1302 // Derivation is ambiguous. Redo the check to find the exact paths.
1303 Paths.clear();
1304 Paths.setRecordingPaths(true);
1305 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1306 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1307 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001308
Sebastian Redled8f2002009-01-28 18:33:18 +00001309 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1310 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1311 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1312 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001313 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001314
Douglas Gregor89ee6822009-02-28 01:32:25 +00001315 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001316 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1317 << FromClass << ToClass << QualType(VBase, 0)
1318 << From->getSourceRange();
1319 return true;
1320 }
1321
Anders Carlssond7923c62009-08-22 23:33:40 +00001322 // Must be a base to derived member conversion.
1323 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001324 return false;
1325}
1326
Douglas Gregor9a657932008-10-21 23:43:52 +00001327/// IsQualificationConversion - Determines whether the conversion from
1328/// an rvalue of type FromType to ToType is a qualification conversion
1329/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001330bool
1331Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001332 FromType = Context.getCanonicalType(FromType);
1333 ToType = Context.getCanonicalType(ToType);
1334
1335 // If FromType and ToType are the same type, this is not a
1336 // qualification conversion.
1337 if (FromType == ToType)
1338 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001339
Douglas Gregor9a657932008-10-21 23:43:52 +00001340 // (C++ 4.4p4):
1341 // A conversion can add cv-qualifiers at levels other than the first
1342 // in multi-level pointers, subject to the following rules: [...]
1343 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001344 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001345 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001346 // Within each iteration of the loop, we check the qualifiers to
1347 // determine if this still looks like a qualification
1348 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001349 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001350 // until there are no more pointers or pointers-to-members left to
1351 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001352 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001353
1354 // -- for every j > 0, if const is in cv 1,j then const is in cv
1355 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001356 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001357 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001358
Douglas Gregor9a657932008-10-21 23:43:52 +00001359 // -- if the cv 1,j and cv 2,j are different, then const is in
1360 // every cv for 0 < k < j.
1361 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001362 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001363 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001364
Douglas Gregor9a657932008-10-21 23:43:52 +00001365 // Keep track of whether all prior cv-qualifiers in the "to" type
1366 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001367 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001368 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001369 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001370
1371 // We are left with FromType and ToType being the pointee types
1372 // after unwrapping the original FromType and ToType the same number
1373 // of types. If we unwrapped any pointers, and if FromType and
1374 // ToType have the same unqualified type (since we checked
1375 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001376 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001377}
1378
Douglas Gregor576e98c2009-01-30 23:27:23 +00001379/// Determines whether there is a user-defined conversion sequence
1380/// (C++ [over.ics.user]) that converts expression From to the type
1381/// ToType. If such a conversion exists, User will contain the
1382/// user-defined conversion sequence that performs such a conversion
1383/// and this routine will return true. Otherwise, this routine returns
1384/// false and User is unspecified.
1385///
1386/// \param AllowConversionFunctions true if the conversion should
1387/// consider conversion functions at all. If false, only constructors
1388/// will be considered.
1389///
1390/// \param AllowExplicit true if the conversion should consider C++0x
1391/// "explicit" conversion functions as well as non-explicit conversion
1392/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001393///
1394/// \param ForceRValue true if the expression should be treated as an rvalue
1395/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001396/// \param UserCast true if looking for user defined conversion for a static
1397/// cast.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001398Sema::OverloadingResult Sema::IsUserDefinedConversion(
1399 Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001400 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001401 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001402 bool AllowConversionFunctions,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001403 bool AllowExplicit, bool ForceRValue,
1404 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001405 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001406 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1407 // We're not going to find any constructors.
1408 } else if (CXXRecordDecl *ToRecordDecl
1409 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001410 // C++ [over.match.ctor]p1:
1411 // When objects of class type are direct-initialized (8.5), or
1412 // copy-initialized from an expression of the same or a
1413 // derived class type (8.5), overload resolution selects the
1414 // constructor. [...] For copy-initialization, the candidate
1415 // functions are all the converting constructors (12.3.1) of
1416 // that class. The argument list is the expression-list within
1417 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001418 bool SuppressUserConversions = !UserCast;
1419 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1420 IsDerivedFrom(From->getType(), ToType)) {
1421 SuppressUserConversions = false;
1422 AllowConversionFunctions = false;
1423 }
1424
Mike Stump11289f42009-09-09 15:08:12 +00001425 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001426 = Context.DeclarationNames.getCXXConstructorName(
1427 Context.getCanonicalType(ToType).getUnqualifiedType());
1428 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001429 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001430 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001431 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001432 // Find the constructor (which may be a template).
1433 CXXConstructorDecl *Constructor = 0;
1434 FunctionTemplateDecl *ConstructorTmpl
1435 = dyn_cast<FunctionTemplateDecl>(*Con);
1436 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001437 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001438 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1439 else
1440 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001441
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001442 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001443 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001444 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00001445 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1446 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001447 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001448 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001449 // Allow one user-defined conversion when user specifies a
1450 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001451 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001452 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001453 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001454 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001455 }
1456 }
1457
Douglas Gregor576e98c2009-01-30 23:27:23 +00001458 if (!AllowConversionFunctions) {
1459 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001460 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1461 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001462 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001463 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001464 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001465 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001466 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001467 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1468 // Add all of the conversion functions as candidates.
John McCalld14a8642009-11-21 08:51:07 +00001469 const UnresolvedSet *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001470 = FromRecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00001471 for (UnresolvedSet::iterator I = Conversions->begin(),
1472 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00001473 NamedDecl *D = *I;
1474 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1475 if (isa<UsingShadowDecl>(D))
1476 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1477
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001478 CXXConversionDecl *Conv;
1479 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001480 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001481 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1482 else
John McCalld14a8642009-11-21 08:51:07 +00001483 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001484
1485 if (AllowExplicit || !Conv->isExplicit()) {
1486 if (ConvTemplate)
John McCall6e9f8f62009-12-03 04:06:58 +00001487 AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1488 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001489 else
John McCall6e9f8f62009-12-03 04:06:58 +00001490 AddConversionCandidate(Conv, ActingContext, From, ToType,
1491 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001492 }
1493 }
1494 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001495 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001496
1497 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001498 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001499 case OR_Success:
1500 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001501 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001502 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1503 // C++ [over.ics.user]p1:
1504 // If the user-defined conversion is specified by a
1505 // constructor (12.3.1), the initial standard conversion
1506 // sequence converts the source type to the type required by
1507 // the argument of the constructor.
1508 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001509 QualType ThisType = Constructor->getThisType(Context);
Fariborz Jahanian55824512009-11-06 00:23:08 +00001510 if (Best->Conversions[0].ConversionKind ==
1511 ImplicitConversionSequence::EllipsisConversion)
1512 User.EllipsisConversion = true;
1513 else {
1514 User.Before = Best->Conversions[0].Standard;
1515 User.EllipsisConversion = false;
1516 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001517 User.ConversionFunction = Constructor;
1518 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001519 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001520 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001521 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001522 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001523 } else if (CXXConversionDecl *Conversion
1524 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1525 // C++ [over.ics.user]p1:
1526 //
1527 // [...] If the user-defined conversion is specified by a
1528 // conversion function (12.3.2), the initial standard
1529 // conversion sequence converts the source type to the
1530 // implicit object parameter of the conversion function.
1531 User.Before = Best->Conversions[0].Standard;
1532 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001533 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001534
1535 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001536 // The second standard conversion sequence converts the
1537 // result of the user-defined conversion to the target type
1538 // for the sequence. Since an implicit conversion sequence
1539 // is an initialization, the special rules for
1540 // initialization by user-defined conversion apply when
1541 // selecting the best user-defined conversion for a
1542 // user-defined conversion sequence (see 13.3.3 and
1543 // 13.3.3.1).
1544 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001545 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001546 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001547 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001548 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001549 }
Mike Stump11289f42009-09-09 15:08:12 +00001550
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001551 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001552 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001553 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001554 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001555 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001556
1557 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001558 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001559 }
1560
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001561 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001562}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001563
1564bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001565Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001566 ImplicitConversionSequence ICS;
1567 OverloadCandidateSet CandidateSet;
1568 OverloadingResult OvResult =
1569 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1570 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001571 if (OvResult == OR_Ambiguous)
1572 Diag(From->getSourceRange().getBegin(),
1573 diag::err_typecheck_ambiguous_condition)
1574 << From->getType() << ToType << From->getSourceRange();
1575 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1576 Diag(From->getSourceRange().getBegin(),
1577 diag::err_typecheck_nonviable_condition)
1578 << From->getType() << ToType << From->getSourceRange();
1579 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001580 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00001581 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001582 return true;
1583}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001584
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001585/// CompareImplicitConversionSequences - Compare two implicit
1586/// conversion sequences to determine whether one is better than the
1587/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001588ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001589Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1590 const ImplicitConversionSequence& ICS2)
1591{
1592 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1593 // conversion sequences (as defined in 13.3.3.1)
1594 // -- a standard conversion sequence (13.3.3.1.1) is a better
1595 // conversion sequence than a user-defined conversion sequence or
1596 // an ellipsis conversion sequence, and
1597 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1598 // conversion sequence than an ellipsis conversion sequence
1599 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001600 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001601 if (ICS1.ConversionKind < ICS2.ConversionKind)
1602 return ImplicitConversionSequence::Better;
1603 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1604 return ImplicitConversionSequence::Worse;
1605
1606 // Two implicit conversion sequences of the same form are
1607 // indistinguishable conversion sequences unless one of the
1608 // following rules apply: (C++ 13.3.3.2p3):
1609 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1610 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001611 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001612 ImplicitConversionSequence::UserDefinedConversion) {
1613 // User-defined conversion sequence U1 is a better conversion
1614 // sequence than another user-defined conversion sequence U2 if
1615 // they contain the same user-defined conversion function or
1616 // constructor and if the second standard conversion sequence of
1617 // U1 is better than the second standard conversion sequence of
1618 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001619 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001620 ICS2.UserDefined.ConversionFunction)
1621 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1622 ICS2.UserDefined.After);
1623 }
1624
1625 return ImplicitConversionSequence::Indistinguishable;
1626}
1627
1628/// CompareStandardConversionSequences - Compare two standard
1629/// conversion sequences to determine whether one is better than the
1630/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001631ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001632Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1633 const StandardConversionSequence& SCS2)
1634{
1635 // Standard conversion sequence S1 is a better conversion sequence
1636 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1637
1638 // -- S1 is a proper subsequence of S2 (comparing the conversion
1639 // sequences in the canonical form defined by 13.3.3.1.1,
1640 // excluding any Lvalue Transformation; the identity conversion
1641 // sequence is considered to be a subsequence of any
1642 // non-identity conversion sequence) or, if not that,
1643 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1644 // Neither is a proper subsequence of the other. Do nothing.
1645 ;
1646 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1647 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001648 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001649 SCS1.Third == ICK_Identity))
1650 // SCS1 is a proper subsequence of SCS2.
1651 return ImplicitConversionSequence::Better;
1652 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1653 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001654 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001655 SCS2.Third == ICK_Identity))
1656 // SCS2 is a proper subsequence of SCS1.
1657 return ImplicitConversionSequence::Worse;
1658
1659 // -- the rank of S1 is better than the rank of S2 (by the rules
1660 // defined below), or, if not that,
1661 ImplicitConversionRank Rank1 = SCS1.getRank();
1662 ImplicitConversionRank Rank2 = SCS2.getRank();
1663 if (Rank1 < Rank2)
1664 return ImplicitConversionSequence::Better;
1665 else if (Rank2 < Rank1)
1666 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001667
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001668 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1669 // are indistinguishable unless one of the following rules
1670 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001671
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001672 // A conversion that is not a conversion of a pointer, or
1673 // pointer to member, to bool is better than another conversion
1674 // that is such a conversion.
1675 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1676 return SCS2.isPointerConversionToBool()
1677 ? ImplicitConversionSequence::Better
1678 : ImplicitConversionSequence::Worse;
1679
Douglas Gregor5c407d92008-10-23 00:40:37 +00001680 // C++ [over.ics.rank]p4b2:
1681 //
1682 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001683 // conversion of B* to A* is better than conversion of B* to
1684 // void*, and conversion of A* to void* is better than conversion
1685 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001686 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001687 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001688 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001689 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001690 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1691 // Exactly one of the conversion sequences is a conversion to
1692 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001693 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1694 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001695 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1696 // Neither conversion sequence converts to a void pointer; compare
1697 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001698 if (ImplicitConversionSequence::CompareKind DerivedCK
1699 = CompareDerivedToBaseConversions(SCS1, SCS2))
1700 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001701 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1702 // Both conversion sequences are conversions to void
1703 // pointers. Compare the source types to determine if there's an
1704 // inheritance relationship in their sources.
1705 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1706 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1707
1708 // Adjust the types we're converting from via the array-to-pointer
1709 // conversion, if we need to.
1710 if (SCS1.First == ICK_Array_To_Pointer)
1711 FromType1 = Context.getArrayDecayedType(FromType1);
1712 if (SCS2.First == ICK_Array_To_Pointer)
1713 FromType2 = Context.getArrayDecayedType(FromType2);
1714
Mike Stump11289f42009-09-09 15:08:12 +00001715 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001716 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001717 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001718 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001719
1720 if (IsDerivedFrom(FromPointee2, FromPointee1))
1721 return ImplicitConversionSequence::Better;
1722 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1723 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001724
1725 // Objective-C++: If one interface is more specific than the
1726 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001727 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1728 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001729 if (FromIface1 && FromIface1) {
1730 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1731 return ImplicitConversionSequence::Better;
1732 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1733 return ImplicitConversionSequence::Worse;
1734 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001735 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001736
1737 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1738 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001739 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001740 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001741 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001742
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001743 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001744 // C++0x [over.ics.rank]p3b4:
1745 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1746 // implicit object parameter of a non-static member function declared
1747 // without a ref-qualifier, and S1 binds an rvalue reference to an
1748 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001749 // FIXME: We don't know if we're dealing with the implicit object parameter,
1750 // or if the member function in this case has a ref qualifier.
1751 // (Of course, we don't have ref qualifiers yet.)
1752 if (SCS1.RRefBinding != SCS2.RRefBinding)
1753 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1754 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001755
1756 // C++ [over.ics.rank]p3b4:
1757 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1758 // which the references refer are the same type except for
1759 // top-level cv-qualifiers, and the type to which the reference
1760 // initialized by S2 refers is more cv-qualified than the type
1761 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001762 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1763 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001764 T1 = Context.getCanonicalType(T1);
1765 T2 = Context.getCanonicalType(T2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001766 if (Context.hasSameUnqualifiedType(T1, T2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001767 if (T2.isMoreQualifiedThan(T1))
1768 return ImplicitConversionSequence::Better;
1769 else if (T1.isMoreQualifiedThan(T2))
1770 return ImplicitConversionSequence::Worse;
1771 }
1772 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001773
1774 return ImplicitConversionSequence::Indistinguishable;
1775}
1776
1777/// CompareQualificationConversions - Compares two standard conversion
1778/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001779/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1780ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001781Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001782 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001783 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001784 // -- S1 and S2 differ only in their qualification conversion and
1785 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1786 // cv-qualification signature of type T1 is a proper subset of
1787 // the cv-qualification signature of type T2, and S1 is not the
1788 // deprecated string literal array-to-pointer conversion (4.2).
1789 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1790 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1791 return ImplicitConversionSequence::Indistinguishable;
1792
1793 // FIXME: the example in the standard doesn't use a qualification
1794 // conversion (!)
1795 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1796 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1797 T1 = Context.getCanonicalType(T1);
1798 T2 = Context.getCanonicalType(T2);
1799
1800 // If the types are the same, we won't learn anything by unwrapped
1801 // them.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001802 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001803 return ImplicitConversionSequence::Indistinguishable;
1804
Mike Stump11289f42009-09-09 15:08:12 +00001805 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001806 = ImplicitConversionSequence::Indistinguishable;
1807 while (UnwrapSimilarPointerTypes(T1, T2)) {
1808 // Within each iteration of the loop, we check the qualifiers to
1809 // determine if this still looks like a qualification
1810 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001811 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001812 // until there are no more pointers or pointers-to-members left
1813 // to unwrap. This essentially mimics what
1814 // IsQualificationConversion does, but here we're checking for a
1815 // strict subset of qualifiers.
1816 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1817 // The qualifiers are the same, so this doesn't tell us anything
1818 // about how the sequences rank.
1819 ;
1820 else if (T2.isMoreQualifiedThan(T1)) {
1821 // T1 has fewer qualifiers, so it could be the better sequence.
1822 if (Result == ImplicitConversionSequence::Worse)
1823 // Neither has qualifiers that are a subset of the other's
1824 // qualifiers.
1825 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001826
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001827 Result = ImplicitConversionSequence::Better;
1828 } else if (T1.isMoreQualifiedThan(T2)) {
1829 // T2 has fewer qualifiers, so it could be the better sequence.
1830 if (Result == ImplicitConversionSequence::Better)
1831 // Neither has qualifiers that are a subset of the other's
1832 // qualifiers.
1833 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001834
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001835 Result = ImplicitConversionSequence::Worse;
1836 } else {
1837 // Qualifiers are disjoint.
1838 return ImplicitConversionSequence::Indistinguishable;
1839 }
1840
1841 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001842 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001843 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001844 }
1845
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001846 // Check that the winning standard conversion sequence isn't using
1847 // the deprecated string literal array to pointer conversion.
1848 switch (Result) {
1849 case ImplicitConversionSequence::Better:
1850 if (SCS1.Deprecated)
1851 Result = ImplicitConversionSequence::Indistinguishable;
1852 break;
1853
1854 case ImplicitConversionSequence::Indistinguishable:
1855 break;
1856
1857 case ImplicitConversionSequence::Worse:
1858 if (SCS2.Deprecated)
1859 Result = ImplicitConversionSequence::Indistinguishable;
1860 break;
1861 }
1862
1863 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001864}
1865
Douglas Gregor5c407d92008-10-23 00:40:37 +00001866/// CompareDerivedToBaseConversions - Compares two standard conversion
1867/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001868/// various kinds of derived-to-base conversions (C++
1869/// [over.ics.rank]p4b3). As part of these checks, we also look at
1870/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001871ImplicitConversionSequence::CompareKind
1872Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1873 const StandardConversionSequence& SCS2) {
1874 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1875 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1876 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1877 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1878
1879 // Adjust the types we're converting from via the array-to-pointer
1880 // conversion, if we need to.
1881 if (SCS1.First == ICK_Array_To_Pointer)
1882 FromType1 = Context.getArrayDecayedType(FromType1);
1883 if (SCS2.First == ICK_Array_To_Pointer)
1884 FromType2 = Context.getArrayDecayedType(FromType2);
1885
1886 // Canonicalize all of the types.
1887 FromType1 = Context.getCanonicalType(FromType1);
1888 ToType1 = Context.getCanonicalType(ToType1);
1889 FromType2 = Context.getCanonicalType(FromType2);
1890 ToType2 = Context.getCanonicalType(ToType2);
1891
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001892 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001893 //
1894 // If class B is derived directly or indirectly from class A and
1895 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001896 //
1897 // For Objective-C, we let A, B, and C also be Objective-C
1898 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001899
1900 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001901 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001902 SCS2.Second == ICK_Pointer_Conversion &&
1903 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1904 FromType1->isPointerType() && FromType2->isPointerType() &&
1905 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001906 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001907 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001908 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001909 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001910 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001911 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001912 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001913 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001914
John McCall9dd450b2009-09-21 23:43:11 +00001915 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1916 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1917 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1918 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001919
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001920 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001921 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1922 if (IsDerivedFrom(ToPointee1, ToPointee2))
1923 return ImplicitConversionSequence::Better;
1924 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1925 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001926
1927 if (ToIface1 && ToIface2) {
1928 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1929 return ImplicitConversionSequence::Better;
1930 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1931 return ImplicitConversionSequence::Worse;
1932 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001933 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001934
1935 // -- conversion of B* to A* is better than conversion of C* to A*,
1936 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1937 if (IsDerivedFrom(FromPointee2, FromPointee1))
1938 return ImplicitConversionSequence::Better;
1939 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1940 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001941
Douglas Gregor237f96c2008-11-26 23:31:11 +00001942 if (FromIface1 && FromIface2) {
1943 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1944 return ImplicitConversionSequence::Better;
1945 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1946 return ImplicitConversionSequence::Worse;
1947 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001948 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001949 }
1950
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001951 // Compare based on reference bindings.
1952 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1953 SCS1.Second == ICK_Derived_To_Base) {
1954 // -- binding of an expression of type C to a reference of type
1955 // B& is better than binding an expression of type C to a
1956 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001957 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1958 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001959 if (IsDerivedFrom(ToType1, ToType2))
1960 return ImplicitConversionSequence::Better;
1961 else if (IsDerivedFrom(ToType2, ToType1))
1962 return ImplicitConversionSequence::Worse;
1963 }
1964
Douglas Gregor2fe98832008-11-03 19:09:14 +00001965 // -- binding of an expression of type B to a reference of type
1966 // A& is better than binding an expression of type C to a
1967 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001968 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1969 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001970 if (IsDerivedFrom(FromType2, FromType1))
1971 return ImplicitConversionSequence::Better;
1972 else if (IsDerivedFrom(FromType1, FromType2))
1973 return ImplicitConversionSequence::Worse;
1974 }
1975 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001976
1977 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001978 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1979 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1980 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1981 const MemberPointerType * FromMemPointer1 =
1982 FromType1->getAs<MemberPointerType>();
1983 const MemberPointerType * ToMemPointer1 =
1984 ToType1->getAs<MemberPointerType>();
1985 const MemberPointerType * FromMemPointer2 =
1986 FromType2->getAs<MemberPointerType>();
1987 const MemberPointerType * ToMemPointer2 =
1988 ToType2->getAs<MemberPointerType>();
1989 const Type *FromPointeeType1 = FromMemPointer1->getClass();
1990 const Type *ToPointeeType1 = ToMemPointer1->getClass();
1991 const Type *FromPointeeType2 = FromMemPointer2->getClass();
1992 const Type *ToPointeeType2 = ToMemPointer2->getClass();
1993 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1994 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
1995 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
1996 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001997 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001998 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1999 if (IsDerivedFrom(ToPointee1, ToPointee2))
2000 return ImplicitConversionSequence::Worse;
2001 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2002 return ImplicitConversionSequence::Better;
2003 }
2004 // conversion of B::* to C::* is better than conversion of A::* to C::*
2005 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2006 if (IsDerivedFrom(FromPointee1, FromPointee2))
2007 return ImplicitConversionSequence::Better;
2008 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2009 return ImplicitConversionSequence::Worse;
2010 }
2011 }
2012
Douglas Gregor2fe98832008-11-03 19:09:14 +00002013 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2014 SCS1.Second == ICK_Derived_To_Base) {
2015 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002016 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2017 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002018 if (IsDerivedFrom(ToType1, ToType2))
2019 return ImplicitConversionSequence::Better;
2020 else if (IsDerivedFrom(ToType2, ToType1))
2021 return ImplicitConversionSequence::Worse;
2022 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002023
Douglas Gregor2fe98832008-11-03 19:09:14 +00002024 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002025 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2026 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002027 if (IsDerivedFrom(FromType2, FromType1))
2028 return ImplicitConversionSequence::Better;
2029 else if (IsDerivedFrom(FromType1, FromType2))
2030 return ImplicitConversionSequence::Worse;
2031 }
2032 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002033
Douglas Gregor5c407d92008-10-23 00:40:37 +00002034 return ImplicitConversionSequence::Indistinguishable;
2035}
2036
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002037/// TryCopyInitialization - Try to copy-initialize a value of type
2038/// ToType from the expression From. Return the implicit conversion
2039/// sequence required to pass this argument, which may be a bad
2040/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002041/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002042/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2043/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002044ImplicitConversionSequence
2045Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002046 bool SuppressUserConversions, bool ForceRValue,
2047 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002048 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002049 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00002050 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002051 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002052 SuppressUserConversions,
2053 /*AllowExplicit=*/false,
2054 ForceRValue,
2055 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002056 return ICS;
2057 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002058 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002059 SuppressUserConversions,
2060 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002061 ForceRValue,
2062 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002063 }
2064}
2065
Sebastian Redl42e92c42009-04-12 17:16:29 +00002066/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2067/// the expression @p From. Returns true (and emits a diagnostic) if there was
2068/// an error, returns false if the initialization succeeded. Elidable should
2069/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2070/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002071bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002072 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002073 if (!getLangOptions().CPlusPlus) {
2074 // In C, argument passing is the same as performing an assignment.
2075 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002076
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002077 AssignConvertType ConvTy =
2078 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002079 if (ConvTy != Compatible &&
2080 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2081 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002082
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002083 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2084 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002085 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002086
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002087 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002088 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002089 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002090 /*SuppressUserConversions=*/false,
2091 /*AllowExplicit=*/false,
2092 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002093
Sebastian Redl42e92c42009-04-12 17:16:29 +00002094 if (!PerformImplicitConversion(From, ToType, Flavor,
2095 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002096 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002097 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002098 return Diag(From->getSourceRange().getBegin(),
2099 diag::err_typecheck_convert_incompatible)
2100 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002101 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002102}
2103
Douglas Gregor436424c2008-11-18 23:14:02 +00002104/// TryObjectArgumentInitialization - Try to initialize the object
2105/// parameter of the given member function (@c Method) from the
2106/// expression @p From.
2107ImplicitConversionSequence
John McCall6e9f8f62009-12-03 04:06:58 +00002108Sema::TryObjectArgumentInitialization(QualType FromType,
2109 CXXMethodDecl *Method,
2110 CXXRecordDecl *ActingContext) {
2111 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002112 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2113 // const volatile object.
2114 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2115 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2116 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002117
2118 // Set up the conversion sequence as a "bad" conversion, to allow us
2119 // to exit early.
2120 ImplicitConversionSequence ICS;
2121 ICS.Standard.setAsIdentityConversion();
2122 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2123
2124 // We need to have an object of class type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002125 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002126 FromType = PT->getPointeeType();
2127
2128 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002129
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002130 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002131 // where X is the class of which the function is a member
2132 // (C++ [over.match.funcs]p4). However, when finding an implicit
2133 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002134 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002135 // (C++ [over.match.funcs]p5). We perform a simplified version of
2136 // reference binding here, that allows class rvalues to bind to
2137 // non-constant references.
2138
2139 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2140 // with the implicit object parameter (C++ [over.match.funcs]p5).
2141 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002142 if (ImplicitParamType.getCVRQualifiers()
2143 != FromTypeCanon.getLocalCVRQualifiers() &&
Douglas Gregor01df9462009-11-05 00:07:36 +00002144 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor436424c2008-11-18 23:14:02 +00002145 return ICS;
2146
2147 // Check that we have either the same type or a derived type. It
2148 // affects the conversion rank.
2149 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002150 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002151 ICS.Standard.Second = ICK_Identity;
2152 else if (IsDerivedFrom(FromType, ClassType))
2153 ICS.Standard.Second = ICK_Derived_To_Base;
2154 else
2155 return ICS;
2156
2157 // Success. Mark this as a reference binding.
2158 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2159 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2160 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2161 ICS.Standard.ReferenceBinding = true;
2162 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002163 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002164 return ICS;
2165}
2166
2167/// PerformObjectArgumentInitialization - Perform initialization of
2168/// the implicit object parameter for the given Method with the given
2169/// expression.
2170bool
2171Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002172 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002173 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002174 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002175
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002176 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002177 FromRecordType = PT->getPointeeType();
2178 DestType = Method->getThisType(Context);
2179 } else {
2180 FromRecordType = From->getType();
2181 DestType = ImplicitParamRecordType;
2182 }
2183
John McCall6e9f8f62009-12-03 04:06:58 +00002184 // Note that we always use the true parent context when performing
2185 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002186 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002187 = TryObjectArgumentInitialization(From->getType(), Method,
2188 Method->getParent());
Douglas Gregor436424c2008-11-18 23:14:02 +00002189 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2190 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002191 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002192 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002193
Douglas Gregor436424c2008-11-18 23:14:02 +00002194 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002195 CheckDerivedToBaseConversion(FromRecordType,
2196 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002197 From->getSourceRange().getBegin(),
2198 From->getSourceRange()))
2199 return true;
2200
Mike Stump11289f42009-09-09 15:08:12 +00002201 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002202 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002203 return false;
2204}
2205
Douglas Gregor5fb53972009-01-14 15:45:31 +00002206/// TryContextuallyConvertToBool - Attempt to contextually convert the
2207/// expression From to bool (C++0x [conv]p3).
2208ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002209 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002210 // FIXME: Are these flags correct?
2211 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002212 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002213 /*ForceRValue=*/false,
2214 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002215}
2216
2217/// PerformContextuallyConvertToBool - Perform a contextual conversion
2218/// of the expression From to bool (C++0x [conv]p3).
2219bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2220 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2221 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2222 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002223
Fariborz Jahanian76197412009-11-18 18:26:29 +00002224 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002225 return Diag(From->getSourceRange().getBegin(),
2226 diag::err_typecheck_bool_condition)
2227 << From->getType() << From->getSourceRange();
2228 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002229}
2230
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002231/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002232/// candidate functions, using the given function call arguments. If
2233/// @p SuppressUserConversions, then don't allow user-defined
2234/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002235/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2236/// hacky way to implement the overloading rules for elidable copy
2237/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002238///
2239/// \para PartialOverloading true if we are performing "partial" overloading
2240/// based on an incomplete set of function arguments. This feature is used by
2241/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002242void
2243Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002244 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002245 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002246 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002247 bool ForceRValue,
2248 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002249 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002250 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002251 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002252 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002253 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002254 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002255 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002256
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002257 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002258 if (!isa<CXXConstructorDecl>(Method)) {
2259 // If we get here, it's because we're calling a member function
2260 // that is named without a member access expression (e.g.,
2261 // "this->f") that was either written explicitly or created
2262 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002263 // function, e.g., X::f(). We use an empty type for the implied
2264 // object argument (C++ [over.call.func]p3), and the acting context
2265 // is irrelevant.
2266 AddMethodCandidate(Method, Method->getParent(),
2267 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002268 SuppressUserConversions, ForceRValue);
2269 return;
2270 }
2271 // We treat a constructor like a non-member function, since its object
2272 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002273 }
2274
Douglas Gregorff7028a2009-11-13 23:59:09 +00002275 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002276 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002277
Douglas Gregor27381f32009-11-23 12:27:39 +00002278 // Overload resolution is always an unevaluated context.
2279 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2280
Douglas Gregorffe14e32009-11-14 01:20:54 +00002281 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2282 // C++ [class.copy]p3:
2283 // A member function template is never instantiated to perform the copy
2284 // of a class object to an object of its class type.
2285 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2286 if (NumArgs == 1 &&
2287 Constructor->isCopyConstructorLikeSpecialization() &&
2288 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2289 return;
2290 }
2291
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002292 // Add this candidate
2293 CandidateSet.push_back(OverloadCandidate());
2294 OverloadCandidate& Candidate = CandidateSet.back();
2295 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002296 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002297 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002298 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002299
2300 unsigned NumArgsInProto = Proto->getNumArgs();
2301
2302 // (C++ 13.3.2p2): A candidate function having fewer than m
2303 // parameters is viable only if it has an ellipsis in its parameter
2304 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002305 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2306 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002307 Candidate.Viable = false;
2308 return;
2309 }
2310
2311 // (C++ 13.3.2p2): A candidate function having more than m parameters
2312 // is viable only if the (m+1)st parameter has a default argument
2313 // (8.3.6). For the purposes of overload resolution, the
2314 // parameter list is truncated on the right, so that there are
2315 // exactly m parameters.
2316 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002317 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002318 // Not enough arguments.
2319 Candidate.Viable = false;
2320 return;
2321 }
2322
2323 // Determine the implicit conversion sequences for each of the
2324 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002325 Candidate.Conversions.resize(NumArgs);
2326 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2327 if (ArgIdx < NumArgsInProto) {
2328 // (C++ 13.3.2p3): for F to be a viable function, there shall
2329 // exist for each argument an implicit conversion sequence
2330 // (13.3.3.1) that converts that argument to the corresponding
2331 // parameter of F.
2332 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002333 Candidate.Conversions[ArgIdx]
2334 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002335 SuppressUserConversions, ForceRValue,
2336 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002337 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002338 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002339 // 13.3.3.1-p10 If several different sequences of conversions exist that
2340 // each convert the argument to the parameter type, the implicit conversion
2341 // sequence associated with the parameter is defined to be the unique conversion
2342 // sequence designated the ambiguous conversion sequence. For the purpose of
2343 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2344 // conversion sequence is treated as a user-defined sequence that is
2345 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002346 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002347 Candidate.Conversions[ArgIdx].ConversionKind =
2348 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002349 // Set the conversion function to one of them. As due to ambiguity,
2350 // they carry the same weight and is needed for overload resolution
2351 // later.
2352 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2353 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2354 }
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002355 else {
2356 Candidate.Viable = false;
2357 break;
2358 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002359 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002360 } else {
2361 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2362 // argument for which there is no corresponding parameter is
2363 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002364 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002365 = ImplicitConversionSequence::EllipsisConversion;
2366 }
2367 }
2368}
2369
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002370/// \brief Add all of the function declarations in the given function set to
2371/// the overload canddiate set.
2372void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2373 Expr **Args, unsigned NumArgs,
2374 OverloadCandidateSet& CandidateSet,
2375 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002376 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002377 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002378 F != FEnd; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002379 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002380 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2381 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2382 AddMethodCandidate(cast<CXXMethodDecl>(FD),
John McCall6e9f8f62009-12-03 04:06:58 +00002383 cast<CXXMethodDecl>(FD)->getParent(),
2384 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002385 CandidateSet, SuppressUserConversions);
2386 else
2387 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2388 SuppressUserConversions);
2389 } else {
2390 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2391 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2392 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2393 AddMethodTemplateCandidate(FunTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002394 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002395 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002396 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002397 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002398 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002399 else
2400 AddTemplateOverloadCandidate(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002401 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002402 Args, NumArgs, CandidateSet,
2403 SuppressUserConversions);
2404 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002405 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002406}
2407
John McCallf0f1cf02009-11-17 07:50:12 +00002408/// AddMethodCandidate - Adds a named decl (which is some kind of
2409/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002410void Sema::AddMethodCandidate(NamedDecl *Decl,
2411 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002412 Expr **Args, unsigned NumArgs,
2413 OverloadCandidateSet& CandidateSet,
2414 bool SuppressUserConversions, bool ForceRValue) {
2415
2416 // FIXME: use this
John McCall6e9f8f62009-12-03 04:06:58 +00002417 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002418
2419 if (isa<UsingShadowDecl>(Decl))
2420 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2421
2422 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2423 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2424 "Expected a member function template");
John McCall6e9f8f62009-12-03 04:06:58 +00002425 AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2426 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002427 CandidateSet,
2428 SuppressUserConversions,
2429 ForceRValue);
2430 } else {
John McCall6e9f8f62009-12-03 04:06:58 +00002431 AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2432 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002433 CandidateSet, SuppressUserConversions, ForceRValue);
2434 }
2435}
2436
Douglas Gregor436424c2008-11-18 23:14:02 +00002437/// AddMethodCandidate - Adds the given C++ member function to the set
2438/// of candidate functions, using the given function call arguments
2439/// and the object argument (@c Object). For example, in a call
2440/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2441/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2442/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002443/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2444/// a slightly hacky way to implement the overloading rules for elidable copy
2445/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002446void
John McCall6e9f8f62009-12-03 04:06:58 +00002447Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2448 QualType ObjectType, Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002449 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002450 bool SuppressUserConversions, bool ForceRValue) {
2451 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002452 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002453 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002454 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002455 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002456 assert(!isa<CXXConstructorDecl>(Method) &&
2457 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002458
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002459 if (!CandidateSet.isNewCandidate(Method))
2460 return;
2461
Douglas Gregor27381f32009-11-23 12:27:39 +00002462 // Overload resolution is always an unevaluated context.
2463 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2464
Douglas Gregor436424c2008-11-18 23:14:02 +00002465 // Add this candidate
2466 CandidateSet.push_back(OverloadCandidate());
2467 OverloadCandidate& Candidate = CandidateSet.back();
2468 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002469 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002470 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002471
2472 unsigned NumArgsInProto = Proto->getNumArgs();
2473
2474 // (C++ 13.3.2p2): A candidate function having fewer than m
2475 // parameters is viable only if it has an ellipsis in its parameter
2476 // list (8.3.5).
2477 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2478 Candidate.Viable = false;
2479 return;
2480 }
2481
2482 // (C++ 13.3.2p2): A candidate function having more than m parameters
2483 // is viable only if the (m+1)st parameter has a default argument
2484 // (8.3.6). For the purposes of overload resolution, the
2485 // parameter list is truncated on the right, so that there are
2486 // exactly m parameters.
2487 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2488 if (NumArgs < MinRequiredArgs) {
2489 // Not enough arguments.
2490 Candidate.Viable = false;
2491 return;
2492 }
2493
2494 Candidate.Viable = true;
2495 Candidate.Conversions.resize(NumArgs + 1);
2496
John McCall6e9f8f62009-12-03 04:06:58 +00002497 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002498 // The implicit object argument is ignored.
2499 Candidate.IgnoreObjectArgument = true;
2500 else {
2501 // Determine the implicit conversion sequence for the object
2502 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002503 Candidate.Conversions[0]
2504 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
Mike Stump11289f42009-09-09 15:08:12 +00002505 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002506 == ImplicitConversionSequence::BadConversion) {
2507 Candidate.Viable = false;
2508 return;
2509 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002510 }
2511
2512 // Determine the implicit conversion sequences for each of the
2513 // arguments.
2514 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2515 if (ArgIdx < NumArgsInProto) {
2516 // (C++ 13.3.2p3): for F to be a viable function, there shall
2517 // exist for each argument an implicit conversion sequence
2518 // (13.3.3.1) that converts that argument to the corresponding
2519 // parameter of F.
2520 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002521 Candidate.Conversions[ArgIdx + 1]
2522 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002523 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002524 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002525 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002526 == ImplicitConversionSequence::BadConversion) {
2527 Candidate.Viable = false;
2528 break;
2529 }
2530 } else {
2531 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2532 // argument for which there is no corresponding parameter is
2533 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002534 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002535 = ImplicitConversionSequence::EllipsisConversion;
2536 }
2537 }
2538}
2539
Douglas Gregor97628d62009-08-21 00:16:32 +00002540/// \brief Add a C++ member function template as a candidate to the candidate
2541/// set, using template argument deduction to produce an appropriate member
2542/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002543void
Douglas Gregor97628d62009-08-21 00:16:32 +00002544Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002545 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002546 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002547 QualType ObjectType,
2548 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002549 OverloadCandidateSet& CandidateSet,
2550 bool SuppressUserConversions,
2551 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002552 if (!CandidateSet.isNewCandidate(MethodTmpl))
2553 return;
2554
Douglas Gregor97628d62009-08-21 00:16:32 +00002555 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002556 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002557 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002558 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002559 // candidate functions in the usual way.113) A given name can refer to one
2560 // or more function templates and also to a set of overloaded non-template
2561 // functions. In such a case, the candidate functions generated from each
2562 // function template are combined with the set of non-template candidate
2563 // functions.
2564 TemplateDeductionInfo Info(Context);
2565 FunctionDecl *Specialization = 0;
2566 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002567 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002568 Args, NumArgs, Specialization, Info)) {
2569 // FIXME: Record what happened with template argument deduction, so
2570 // that we can give the user a beautiful diagnostic.
2571 (void)Result;
2572 return;
2573 }
Mike Stump11289f42009-09-09 15:08:12 +00002574
Douglas Gregor97628d62009-08-21 00:16:32 +00002575 // Add the function template specialization produced by template argument
2576 // deduction as a candidate.
2577 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002578 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002579 "Specialization is not a member function?");
John McCall6e9f8f62009-12-03 04:06:58 +00002580 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2581 ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002582 CandidateSet, SuppressUserConversions, ForceRValue);
2583}
2584
Douglas Gregor05155d82009-08-21 23:19:43 +00002585/// \brief Add a C++ function template specialization as a candidate
2586/// in the candidate set, using template argument deduction to produce
2587/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002588void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002589Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002590 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002591 Expr **Args, unsigned NumArgs,
2592 OverloadCandidateSet& CandidateSet,
2593 bool SuppressUserConversions,
2594 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002595 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2596 return;
2597
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002598 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002599 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002600 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002601 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002602 // candidate functions in the usual way.113) A given name can refer to one
2603 // or more function templates and also to a set of overloaded non-template
2604 // functions. In such a case, the candidate functions generated from each
2605 // function template are combined with the set of non-template candidate
2606 // functions.
2607 TemplateDeductionInfo Info(Context);
2608 FunctionDecl *Specialization = 0;
2609 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002610 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002611 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002612 // FIXME: Record what happened with template argument deduction, so
2613 // that we can give the user a beautiful diagnostic.
2614 (void)Result;
2615 return;
2616 }
Mike Stump11289f42009-09-09 15:08:12 +00002617
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002618 // Add the function template specialization produced by template argument
2619 // deduction as a candidate.
2620 assert(Specialization && "Missing function template specialization?");
2621 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2622 SuppressUserConversions, ForceRValue);
2623}
Mike Stump11289f42009-09-09 15:08:12 +00002624
Douglas Gregora1f013e2008-11-07 22:36:19 +00002625/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002626/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002627/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002628/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002629/// (which may or may not be the same type as the type that the
2630/// conversion function produces).
2631void
2632Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002633 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002634 Expr *From, QualType ToType,
2635 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002636 assert(!Conversion->getDescribedFunctionTemplate() &&
2637 "Conversion function templates use AddTemplateConversionCandidate");
2638
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002639 if (!CandidateSet.isNewCandidate(Conversion))
2640 return;
2641
Douglas Gregor27381f32009-11-23 12:27:39 +00002642 // Overload resolution is always an unevaluated context.
2643 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2644
Douglas Gregora1f013e2008-11-07 22:36:19 +00002645 // Add this candidate
2646 CandidateSet.push_back(OverloadCandidate());
2647 OverloadCandidate& Candidate = CandidateSet.back();
2648 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002649 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002650 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002651 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002652 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002653 = Conversion->getConversionType().getAsOpaquePtr();
2654 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2655
Douglas Gregor436424c2008-11-18 23:14:02 +00002656 // Determine the implicit conversion sequence for the implicit
2657 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002658 Candidate.Viable = true;
2659 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002660 Candidate.Conversions[0]
2661 = TryObjectArgumentInitialization(From->getType(), Conversion,
2662 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002663 // Conversion functions to a different type in the base class is visible in
2664 // the derived class. So, a derived to base conversion should not participate
2665 // in overload resolution.
2666 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2667 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002668 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002669 == ImplicitConversionSequence::BadConversion) {
2670 Candidate.Viable = false;
2671 return;
2672 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002673
2674 // We won't go through a user-define type conversion function to convert a
2675 // derived to base as such conversions are given Conversion Rank. They only
2676 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2677 QualType FromCanon
2678 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2679 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2680 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2681 Candidate.Viable = false;
2682 return;
2683 }
2684
Douglas Gregora1f013e2008-11-07 22:36:19 +00002685
2686 // To determine what the conversion from the result of calling the
2687 // conversion function to the type we're eventually trying to
2688 // convert to (ToType), we need to synthesize a call to the
2689 // conversion function and attempt copy initialization from it. This
2690 // makes sure that we get the right semantics with respect to
2691 // lvalues/rvalues and the type. Fortunately, we can allocate this
2692 // call on the stack and we don't need its arguments to be
2693 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002694 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002695 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002696 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002697 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002698 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002699
2700 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002701 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2702 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002703 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002704 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002705 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002706 ImplicitConversionSequence ICS =
2707 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002708 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002709 /*ForceRValue=*/false,
2710 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002711
Douglas Gregora1f013e2008-11-07 22:36:19 +00002712 switch (ICS.ConversionKind) {
2713 case ImplicitConversionSequence::StandardConversion:
2714 Candidate.FinalConversion = ICS.Standard;
2715 break;
2716
2717 case ImplicitConversionSequence::BadConversion:
2718 Candidate.Viable = false;
2719 break;
2720
2721 default:
Mike Stump11289f42009-09-09 15:08:12 +00002722 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002723 "Can only end up with a standard conversion sequence or failure");
2724 }
2725}
2726
Douglas Gregor05155d82009-08-21 23:19:43 +00002727/// \brief Adds a conversion function template specialization
2728/// candidate to the overload set, using template argument deduction
2729/// to deduce the template arguments of the conversion function
2730/// template from the type that we are converting to (C++
2731/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002732void
Douglas Gregor05155d82009-08-21 23:19:43 +00002733Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6e9f8f62009-12-03 04:06:58 +00002734 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002735 Expr *From, QualType ToType,
2736 OverloadCandidateSet &CandidateSet) {
2737 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2738 "Only conversion function templates permitted here");
2739
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002740 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2741 return;
2742
Douglas Gregor05155d82009-08-21 23:19:43 +00002743 TemplateDeductionInfo Info(Context);
2744 CXXConversionDecl *Specialization = 0;
2745 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002746 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002747 Specialization, Info)) {
2748 // FIXME: Record what happened with template argument deduction, so
2749 // that we can give the user a beautiful diagnostic.
2750 (void)Result;
2751 return;
2752 }
Mike Stump11289f42009-09-09 15:08:12 +00002753
Douglas Gregor05155d82009-08-21 23:19:43 +00002754 // Add the conversion function template specialization produced by
2755 // template argument deduction as a candidate.
2756 assert(Specialization && "Missing function template specialization?");
John McCall6e9f8f62009-12-03 04:06:58 +00002757 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002758}
2759
Douglas Gregorab7897a2008-11-19 22:57:39 +00002760/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2761/// converts the given @c Object to a function pointer via the
2762/// conversion function @c Conversion, and then attempts to call it
2763/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2764/// the type of function that we'll eventually be calling.
2765void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002766 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002767 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002768 QualType ObjectType,
2769 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002770 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002771 if (!CandidateSet.isNewCandidate(Conversion))
2772 return;
2773
Douglas Gregor27381f32009-11-23 12:27:39 +00002774 // Overload resolution is always an unevaluated context.
2775 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2776
Douglas Gregorab7897a2008-11-19 22:57:39 +00002777 CandidateSet.push_back(OverloadCandidate());
2778 OverloadCandidate& Candidate = CandidateSet.back();
2779 Candidate.Function = 0;
2780 Candidate.Surrogate = Conversion;
2781 Candidate.Viable = true;
2782 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002783 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002784 Candidate.Conversions.resize(NumArgs + 1);
2785
2786 // Determine the implicit conversion sequence for the implicit
2787 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002788 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002789 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
Douglas Gregorab7897a2008-11-19 22:57:39 +00002790 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2791 Candidate.Viable = false;
2792 return;
2793 }
2794
2795 // The first conversion is actually a user-defined conversion whose
2796 // first conversion is ObjectInit's standard conversion (which is
2797 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002798 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002799 = ImplicitConversionSequence::UserDefinedConversion;
2800 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002801 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002802 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002803 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002804 = Candidate.Conversions[0].UserDefined.Before;
2805 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2806
Mike Stump11289f42009-09-09 15:08:12 +00002807 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002808 unsigned NumArgsInProto = Proto->getNumArgs();
2809
2810 // (C++ 13.3.2p2): A candidate function having fewer than m
2811 // parameters is viable only if it has an ellipsis in its parameter
2812 // list (8.3.5).
2813 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2814 Candidate.Viable = false;
2815 return;
2816 }
2817
2818 // Function types don't have any default arguments, so just check if
2819 // we have enough arguments.
2820 if (NumArgs < NumArgsInProto) {
2821 // Not enough arguments.
2822 Candidate.Viable = false;
2823 return;
2824 }
2825
2826 // Determine the implicit conversion sequences for each of the
2827 // arguments.
2828 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2829 if (ArgIdx < NumArgsInProto) {
2830 // (C++ 13.3.2p3): for F to be a viable function, there shall
2831 // exist for each argument an implicit conversion sequence
2832 // (13.3.3.1) that converts that argument to the corresponding
2833 // parameter of F.
2834 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002835 Candidate.Conversions[ArgIdx + 1]
2836 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002837 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002838 /*ForceRValue=*/false,
2839 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002840 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002841 == ImplicitConversionSequence::BadConversion) {
2842 Candidate.Viable = false;
2843 break;
2844 }
2845 } else {
2846 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2847 // argument for which there is no corresponding parameter is
2848 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002849 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002850 = ImplicitConversionSequence::EllipsisConversion;
2851 }
2852 }
2853}
2854
Mike Stump87c57ac2009-05-16 07:39:55 +00002855// FIXME: This will eventually be removed, once we've migrated all of the
2856// operator overloading logic over to the scheme used by binary operators, which
2857// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002858void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002859 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002860 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002861 OverloadCandidateSet& CandidateSet,
2862 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002863 FunctionSet Functions;
2864
2865 QualType T1 = Args[0]->getType();
2866 QualType T2;
2867 if (NumArgs > 1)
2868 T2 = Args[1]->getType();
2869
2870 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002871 if (S)
2872 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002873 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002874 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2875 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002876 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002877}
2878
2879/// \brief Add overload candidates for overloaded operators that are
2880/// member functions.
2881///
2882/// Add the overloaded operator candidates that are member functions
2883/// for the operator Op that was used in an operator expression such
2884/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2885/// CandidateSet will store the added overload candidates. (C++
2886/// [over.match.oper]).
2887void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2888 SourceLocation OpLoc,
2889 Expr **Args, unsigned NumArgs,
2890 OverloadCandidateSet& CandidateSet,
2891 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002892 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2893
2894 // C++ [over.match.oper]p3:
2895 // For a unary operator @ with an operand of a type whose
2896 // cv-unqualified version is T1, and for a binary operator @ with
2897 // a left operand of a type whose cv-unqualified version is T1 and
2898 // a right operand of a type whose cv-unqualified version is T2,
2899 // three sets of candidate functions, designated member
2900 // candidates, non-member candidates and built-in candidates, are
2901 // constructed as follows:
2902 QualType T1 = Args[0]->getType();
2903 QualType T2;
2904 if (NumArgs > 1)
2905 T2 = Args[1]->getType();
2906
2907 // -- If T1 is a class type, the set of member candidates is the
2908 // result of the qualified lookup of T1::operator@
2909 // (13.3.1.1.1); otherwise, the set of member candidates is
2910 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002911 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002912 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002913 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002914 return;
Mike Stump11289f42009-09-09 15:08:12 +00002915
John McCall27b18f82009-11-17 02:14:36 +00002916 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2917 LookupQualifiedName(Operators, T1Rec->getDecl());
2918 Operators.suppressDiagnostics();
2919
Mike Stump11289f42009-09-09 15:08:12 +00002920 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002921 OperEnd = Operators.end();
2922 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00002923 ++Oper)
John McCall6e9f8f62009-12-03 04:06:58 +00002924 AddMethodCandidate(*Oper, Args[0]->getType(),
2925 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00002926 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002927 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002928}
2929
Douglas Gregora11693b2008-11-12 17:17:38 +00002930/// AddBuiltinCandidate - Add a candidate for a built-in
2931/// operator. ResultTy and ParamTys are the result and parameter types
2932/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002933/// arguments being passed to the candidate. IsAssignmentOperator
2934/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002935/// operator. NumContextualBoolArguments is the number of arguments
2936/// (at the beginning of the argument list) that will be contextually
2937/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002938void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002939 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002940 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002941 bool IsAssignmentOperator,
2942 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00002943 // Overload resolution is always an unevaluated context.
2944 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2945
Douglas Gregora11693b2008-11-12 17:17:38 +00002946 // Add this candidate
2947 CandidateSet.push_back(OverloadCandidate());
2948 OverloadCandidate& Candidate = CandidateSet.back();
2949 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002950 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002951 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002952 Candidate.BuiltinTypes.ResultTy = ResultTy;
2953 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2954 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2955
2956 // Determine the implicit conversion sequences for each of the
2957 // arguments.
2958 Candidate.Viable = true;
2959 Candidate.Conversions.resize(NumArgs);
2960 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002961 // C++ [over.match.oper]p4:
2962 // For the built-in assignment operators, conversions of the
2963 // left operand are restricted as follows:
2964 // -- no temporaries are introduced to hold the left operand, and
2965 // -- no user-defined conversions are applied to the left
2966 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002967 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002968 //
2969 // We block these conversions by turning off user-defined
2970 // conversions, since that is the only way that initialization of
2971 // a reference to a non-class type can occur from something that
2972 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002973 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002974 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002975 "Contextual conversion to bool requires bool type");
2976 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2977 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002978 Candidate.Conversions[ArgIdx]
2979 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002980 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002981 /*ForceRValue=*/false,
2982 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002983 }
Mike Stump11289f42009-09-09 15:08:12 +00002984 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002985 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002986 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002987 break;
2988 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002989 }
2990}
2991
2992/// BuiltinCandidateTypeSet - A set of types that will be used for the
2993/// candidate operator functions for built-in operators (C++
2994/// [over.built]). The types are separated into pointer types and
2995/// enumeration types.
2996class BuiltinCandidateTypeSet {
2997 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002998 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002999
3000 /// PointerTypes - The set of pointer types that will be used in the
3001 /// built-in candidates.
3002 TypeSet PointerTypes;
3003
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003004 /// MemberPointerTypes - The set of member pointer types that will be
3005 /// used in the built-in candidates.
3006 TypeSet MemberPointerTypes;
3007
Douglas Gregora11693b2008-11-12 17:17:38 +00003008 /// EnumerationTypes - The set of enumeration types that will be
3009 /// used in the built-in candidates.
3010 TypeSet EnumerationTypes;
3011
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003012 /// Sema - The semantic analysis instance where we are building the
3013 /// candidate type set.
3014 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003015
Douglas Gregora11693b2008-11-12 17:17:38 +00003016 /// Context - The AST context in which we will build the type sets.
3017 ASTContext &Context;
3018
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003019 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3020 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003021 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003022
3023public:
3024 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003025 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003026
Mike Stump11289f42009-09-09 15:08:12 +00003027 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003028 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003029
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003030 void AddTypesConvertedFrom(QualType Ty,
3031 SourceLocation Loc,
3032 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003033 bool AllowExplicitConversions,
3034 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003035
3036 /// pointer_begin - First pointer type found;
3037 iterator pointer_begin() { return PointerTypes.begin(); }
3038
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003039 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003040 iterator pointer_end() { return PointerTypes.end(); }
3041
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003042 /// member_pointer_begin - First member pointer type found;
3043 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3044
3045 /// member_pointer_end - Past the last member pointer type found;
3046 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3047
Douglas Gregora11693b2008-11-12 17:17:38 +00003048 /// enumeration_begin - First enumeration type found;
3049 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3050
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003051 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003052 iterator enumeration_end() { return EnumerationTypes.end(); }
3053};
3054
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003055/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003056/// the set of pointer types along with any more-qualified variants of
3057/// that type. For example, if @p Ty is "int const *", this routine
3058/// will add "int const *", "int const volatile *", "int const
3059/// restrict *", and "int const volatile restrict *" to the set of
3060/// pointer types. Returns true if the add of @p Ty itself succeeded,
3061/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003062///
3063/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003064bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003065BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3066 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003067
Douglas Gregora11693b2008-11-12 17:17:38 +00003068 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003069 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003070 return false;
3071
John McCall8ccfcb52009-09-24 19:53:00 +00003072 const PointerType *PointerTy = Ty->getAs<PointerType>();
3073 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003074
John McCall8ccfcb52009-09-24 19:53:00 +00003075 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003076 // Don't add qualified variants of arrays. For one, they're not allowed
3077 // (the qualifier would sink to the element type), and for another, the
3078 // only overload situation where it matters is subscript or pointer +- int,
3079 // and those shouldn't have qualifier variants anyway.
3080 if (PointeeTy->isArrayType())
3081 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003082 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003083 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003084 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003085 bool hasVolatile = VisibleQuals.hasVolatile();
3086 bool hasRestrict = VisibleQuals.hasRestrict();
3087
John McCall8ccfcb52009-09-24 19:53:00 +00003088 // Iterate through all strict supersets of BaseCVR.
3089 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3090 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003091 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3092 // in the types.
3093 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3094 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003095 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3096 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003097 }
3098
3099 return true;
3100}
3101
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003102/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3103/// to the set of pointer types along with any more-qualified variants of
3104/// that type. For example, if @p Ty is "int const *", this routine
3105/// will add "int const *", "int const volatile *", "int const
3106/// restrict *", and "int const volatile restrict *" to the set of
3107/// pointer types. Returns true if the add of @p Ty itself succeeded,
3108/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003109///
3110/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003111bool
3112BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3113 QualType Ty) {
3114 // Insert this type.
3115 if (!MemberPointerTypes.insert(Ty))
3116 return false;
3117
John McCall8ccfcb52009-09-24 19:53:00 +00003118 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3119 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003120
John McCall8ccfcb52009-09-24 19:53:00 +00003121 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003122 // Don't add qualified variants of arrays. For one, they're not allowed
3123 // (the qualifier would sink to the element type), and for another, the
3124 // only overload situation where it matters is subscript or pointer +- int,
3125 // and those shouldn't have qualifier variants anyway.
3126 if (PointeeTy->isArrayType())
3127 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003128 const Type *ClassTy = PointerTy->getClass();
3129
3130 // Iterate through all strict supersets of the pointee type's CVR
3131 // qualifiers.
3132 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3133 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3134 if ((CVR | BaseCVR) != CVR) continue;
3135
3136 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3137 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003138 }
3139
3140 return true;
3141}
3142
Douglas Gregora11693b2008-11-12 17:17:38 +00003143/// AddTypesConvertedFrom - Add each of the types to which the type @p
3144/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003145/// primarily interested in pointer types and enumeration types. We also
3146/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003147/// AllowUserConversions is true if we should look at the conversion
3148/// functions of a class type, and AllowExplicitConversions if we
3149/// should also include the explicit conversion functions of a class
3150/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003151void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003152BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003153 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003154 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003155 bool AllowExplicitConversions,
3156 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003157 // Only deal with canonical types.
3158 Ty = Context.getCanonicalType(Ty);
3159
3160 // Look through reference types; they aren't part of the type of an
3161 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003162 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003163 Ty = RefTy->getPointeeType();
3164
3165 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003166 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003167
Sebastian Redl65ae2002009-11-05 16:36:20 +00003168 // If we're dealing with an array type, decay to the pointer.
3169 if (Ty->isArrayType())
3170 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3171
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003172 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003173 QualType PointeeTy = PointerTy->getPointeeType();
3174
3175 // Insert our type, and its more-qualified variants, into the set
3176 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003177 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003178 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003179 } else if (Ty->isMemberPointerType()) {
3180 // Member pointers are far easier, since the pointee can't be converted.
3181 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3182 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003183 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003184 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003185 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003186 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003187 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003188 // No conversion functions in incomplete types.
3189 return;
3190 }
Mike Stump11289f42009-09-09 15:08:12 +00003191
Douglas Gregora11693b2008-11-12 17:17:38 +00003192 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003193 const UnresolvedSet *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003194 = ClassDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00003195 for (UnresolvedSet::iterator I = Conversions->begin(),
3196 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003197
Mike Stump11289f42009-09-09 15:08:12 +00003198 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003199 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003200 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003201 continue;
3202
John McCalld14a8642009-11-21 08:51:07 +00003203 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003204 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003205 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003206 VisibleQuals);
3207 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003208 }
3209 }
3210 }
3211}
3212
Douglas Gregor84605ae2009-08-24 13:43:27 +00003213/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3214/// the volatile- and non-volatile-qualified assignment operators for the
3215/// given type to the candidate set.
3216static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3217 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003218 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003219 unsigned NumArgs,
3220 OverloadCandidateSet &CandidateSet) {
3221 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003222
Douglas Gregor84605ae2009-08-24 13:43:27 +00003223 // T& operator=(T&, T)
3224 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3225 ParamTypes[1] = T;
3226 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3227 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003228
Douglas Gregor84605ae2009-08-24 13:43:27 +00003229 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3230 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003231 ParamTypes[0]
3232 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003233 ParamTypes[1] = T;
3234 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003235 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003236 }
3237}
Mike Stump11289f42009-09-09 15:08:12 +00003238
Sebastian Redl1054fae2009-10-25 17:03:50 +00003239/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3240/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003241static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3242 Qualifiers VRQuals;
3243 const RecordType *TyRec;
3244 if (const MemberPointerType *RHSMPType =
3245 ArgExpr->getType()->getAs<MemberPointerType>())
3246 TyRec = cast<RecordType>(RHSMPType->getClass());
3247 else
3248 TyRec = ArgExpr->getType()->getAs<RecordType>();
3249 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003250 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003251 VRQuals.addVolatile();
3252 VRQuals.addRestrict();
3253 return VRQuals;
3254 }
3255
3256 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003257 const UnresolvedSet *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003258 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003259
John McCalld14a8642009-11-21 08:51:07 +00003260 for (UnresolvedSet::iterator I = Conversions->begin(),
3261 E = Conversions->end(); I != E; ++I) {
3262 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003263 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3264 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3265 CanTy = ResTypeRef->getPointeeType();
3266 // Need to go down the pointer/mempointer chain and add qualifiers
3267 // as see them.
3268 bool done = false;
3269 while (!done) {
3270 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3271 CanTy = ResTypePtr->getPointeeType();
3272 else if (const MemberPointerType *ResTypeMPtr =
3273 CanTy->getAs<MemberPointerType>())
3274 CanTy = ResTypeMPtr->getPointeeType();
3275 else
3276 done = true;
3277 if (CanTy.isVolatileQualified())
3278 VRQuals.addVolatile();
3279 if (CanTy.isRestrictQualified())
3280 VRQuals.addRestrict();
3281 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3282 return VRQuals;
3283 }
3284 }
3285 }
3286 return VRQuals;
3287}
3288
Douglas Gregord08452f2008-11-19 15:42:04 +00003289/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3290/// operator overloads to the candidate set (C++ [over.built]), based
3291/// on the operator @p Op and the arguments given. For example, if the
3292/// operator is a binary '+', this routine might add "int
3293/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003294void
Mike Stump11289f42009-09-09 15:08:12 +00003295Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003296 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003297 Expr **Args, unsigned NumArgs,
3298 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003299 // The set of "promoted arithmetic types", which are the arithmetic
3300 // types are that preserved by promotion (C++ [over.built]p2). Note
3301 // that the first few of these types are the promoted integral
3302 // types; these types need to be first.
3303 // FIXME: What about complex?
3304 const unsigned FirstIntegralType = 0;
3305 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003306 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003307 LastPromotedIntegralType = 13;
3308 const unsigned FirstPromotedArithmeticType = 7,
3309 LastPromotedArithmeticType = 16;
3310 const unsigned NumArithmeticTypes = 16;
3311 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003312 Context.BoolTy, Context.CharTy, Context.WCharTy,
3313// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003314 Context.SignedCharTy, Context.ShortTy,
3315 Context.UnsignedCharTy, Context.UnsignedShortTy,
3316 Context.IntTy, Context.LongTy, Context.LongLongTy,
3317 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3318 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3319 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003320 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3321 "Invalid first promoted integral type");
3322 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3323 == Context.UnsignedLongLongTy &&
3324 "Invalid last promoted integral type");
3325 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3326 "Invalid first promoted arithmetic type");
3327 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3328 == Context.LongDoubleTy &&
3329 "Invalid last promoted arithmetic type");
3330
Douglas Gregora11693b2008-11-12 17:17:38 +00003331 // Find all of the types that the arguments can convert to, but only
3332 // if the operator we're looking at has built-in operator candidates
3333 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003334 Qualifiers VisibleTypeConversionsQuals;
3335 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003336 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3337 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3338
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003339 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003340 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3341 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003342 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003343 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003344 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003345 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003346 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003347 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003348 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003349 true,
3350 (Op == OO_Exclaim ||
3351 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003352 Op == OO_PipePipe),
3353 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003354 }
3355
3356 bool isComparison = false;
3357 switch (Op) {
3358 case OO_None:
3359 case NUM_OVERLOADED_OPERATORS:
3360 assert(false && "Expected an overloaded operator");
3361 break;
3362
Douglas Gregord08452f2008-11-19 15:42:04 +00003363 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003364 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003365 goto UnaryStar;
3366 else
3367 goto BinaryStar;
3368 break;
3369
3370 case OO_Plus: // '+' is either unary or binary
3371 if (NumArgs == 1)
3372 goto UnaryPlus;
3373 else
3374 goto BinaryPlus;
3375 break;
3376
3377 case OO_Minus: // '-' is either unary or binary
3378 if (NumArgs == 1)
3379 goto UnaryMinus;
3380 else
3381 goto BinaryMinus;
3382 break;
3383
3384 case OO_Amp: // '&' is either unary or binary
3385 if (NumArgs == 1)
3386 goto UnaryAmp;
3387 else
3388 goto BinaryAmp;
3389
3390 case OO_PlusPlus:
3391 case OO_MinusMinus:
3392 // C++ [over.built]p3:
3393 //
3394 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3395 // is either volatile or empty, there exist candidate operator
3396 // functions of the form
3397 //
3398 // VQ T& operator++(VQ T&);
3399 // T operator++(VQ T&, int);
3400 //
3401 // C++ [over.built]p4:
3402 //
3403 // For every pair (T, VQ), where T is an arithmetic type other
3404 // than bool, and VQ is either volatile or empty, there exist
3405 // candidate operator functions of the form
3406 //
3407 // VQ T& operator--(VQ T&);
3408 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003409 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003410 Arith < NumArithmeticTypes; ++Arith) {
3411 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003412 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003413 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003414
3415 // Non-volatile version.
3416 if (NumArgs == 1)
3417 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3418 else
3419 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003420 // heuristic to reduce number of builtin candidates in the set.
3421 // Add volatile version only if there are conversions to a volatile type.
3422 if (VisibleTypeConversionsQuals.hasVolatile()) {
3423 // Volatile version
3424 ParamTypes[0]
3425 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3426 if (NumArgs == 1)
3427 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3428 else
3429 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3430 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003431 }
3432
3433 // C++ [over.built]p5:
3434 //
3435 // For every pair (T, VQ), where T is a cv-qualified or
3436 // cv-unqualified object type, and VQ is either volatile or
3437 // empty, there exist candidate operator functions of the form
3438 //
3439 // T*VQ& operator++(T*VQ&);
3440 // T*VQ& operator--(T*VQ&);
3441 // T* operator++(T*VQ&, int);
3442 // T* operator--(T*VQ&, int);
3443 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3444 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3445 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003446 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003447 continue;
3448
Mike Stump11289f42009-09-09 15:08:12 +00003449 QualType ParamTypes[2] = {
3450 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003451 };
Mike Stump11289f42009-09-09 15:08:12 +00003452
Douglas Gregord08452f2008-11-19 15:42:04 +00003453 // Without volatile
3454 if (NumArgs == 1)
3455 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3456 else
3457 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3458
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003459 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3460 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003461 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003462 ParamTypes[0]
3463 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003464 if (NumArgs == 1)
3465 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3466 else
3467 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3468 }
3469 }
3470 break;
3471
3472 UnaryStar:
3473 // C++ [over.built]p6:
3474 // For every cv-qualified or cv-unqualified object type T, there
3475 // exist candidate operator functions of the form
3476 //
3477 // T& operator*(T*);
3478 //
3479 // C++ [over.built]p7:
3480 // For every function type T, there exist candidate operator
3481 // functions of the form
3482 // T& operator*(T*);
3483 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3484 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3485 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003486 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003487 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003488 &ParamTy, Args, 1, CandidateSet);
3489 }
3490 break;
3491
3492 UnaryPlus:
3493 // C++ [over.built]p8:
3494 // For every type T, there exist candidate operator functions of
3495 // the form
3496 //
3497 // T* operator+(T*);
3498 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3499 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3500 QualType ParamTy = *Ptr;
3501 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3502 }
Mike Stump11289f42009-09-09 15:08:12 +00003503
Douglas Gregord08452f2008-11-19 15:42:04 +00003504 // Fall through
3505
3506 UnaryMinus:
3507 // C++ [over.built]p9:
3508 // For every promoted arithmetic type T, there exist candidate
3509 // operator functions of the form
3510 //
3511 // T operator+(T);
3512 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003513 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003514 Arith < LastPromotedArithmeticType; ++Arith) {
3515 QualType ArithTy = ArithmeticTypes[Arith];
3516 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3517 }
3518 break;
3519
3520 case OO_Tilde:
3521 // C++ [over.built]p10:
3522 // For every promoted integral type T, there exist candidate
3523 // operator functions of the form
3524 //
3525 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003526 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003527 Int < LastPromotedIntegralType; ++Int) {
3528 QualType IntTy = ArithmeticTypes[Int];
3529 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3530 }
3531 break;
3532
Douglas Gregora11693b2008-11-12 17:17:38 +00003533 case OO_New:
3534 case OO_Delete:
3535 case OO_Array_New:
3536 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003537 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003538 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003539 break;
3540
3541 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003542 UnaryAmp:
3543 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003544 // C++ [over.match.oper]p3:
3545 // -- For the operator ',', the unary operator '&', or the
3546 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003547 break;
3548
Douglas Gregor84605ae2009-08-24 13:43:27 +00003549 case OO_EqualEqual:
3550 case OO_ExclaimEqual:
3551 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003552 // For every pointer to member type T, there exist candidate operator
3553 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003554 //
3555 // bool operator==(T,T);
3556 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003557 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003558 MemPtr = CandidateTypes.member_pointer_begin(),
3559 MemPtrEnd = CandidateTypes.member_pointer_end();
3560 MemPtr != MemPtrEnd;
3561 ++MemPtr) {
3562 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3563 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3564 }
Mike Stump11289f42009-09-09 15:08:12 +00003565
Douglas Gregor84605ae2009-08-24 13:43:27 +00003566 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003567
Douglas Gregora11693b2008-11-12 17:17:38 +00003568 case OO_Less:
3569 case OO_Greater:
3570 case OO_LessEqual:
3571 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003572 // C++ [over.built]p15:
3573 //
3574 // For every pointer or enumeration type T, there exist
3575 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003576 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003577 // bool operator<(T, T);
3578 // bool operator>(T, T);
3579 // bool operator<=(T, T);
3580 // bool operator>=(T, T);
3581 // bool operator==(T, T);
3582 // bool operator!=(T, T);
3583 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3584 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3585 QualType ParamTypes[2] = { *Ptr, *Ptr };
3586 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3587 }
Mike Stump11289f42009-09-09 15:08:12 +00003588 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003589 = CandidateTypes.enumeration_begin();
3590 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3591 QualType ParamTypes[2] = { *Enum, *Enum };
3592 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3593 }
3594
3595 // Fall through.
3596 isComparison = true;
3597
Douglas Gregord08452f2008-11-19 15:42:04 +00003598 BinaryPlus:
3599 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003600 if (!isComparison) {
3601 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3602
3603 // C++ [over.built]p13:
3604 //
3605 // For every cv-qualified or cv-unqualified object type T
3606 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003607 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003608 // T* operator+(T*, ptrdiff_t);
3609 // T& operator[](T*, ptrdiff_t); [BELOW]
3610 // T* operator-(T*, ptrdiff_t);
3611 // T* operator+(ptrdiff_t, T*);
3612 // T& operator[](ptrdiff_t, T*); [BELOW]
3613 //
3614 // C++ [over.built]p14:
3615 //
3616 // For every T, where T is a pointer to object type, there
3617 // exist candidate operator functions of the form
3618 //
3619 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003620 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003621 = CandidateTypes.pointer_begin();
3622 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3623 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3624
3625 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3626 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3627
3628 if (Op == OO_Plus) {
3629 // T* operator+(ptrdiff_t, T*);
3630 ParamTypes[0] = ParamTypes[1];
3631 ParamTypes[1] = *Ptr;
3632 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3633 } else {
3634 // ptrdiff_t operator-(T, T);
3635 ParamTypes[1] = *Ptr;
3636 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3637 Args, 2, CandidateSet);
3638 }
3639 }
3640 }
3641 // Fall through
3642
Douglas Gregora11693b2008-11-12 17:17:38 +00003643 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003644 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003645 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003646 // C++ [over.built]p12:
3647 //
3648 // For every pair of promoted arithmetic types L and R, there
3649 // exist candidate operator functions of the form
3650 //
3651 // LR operator*(L, R);
3652 // LR operator/(L, R);
3653 // LR operator+(L, R);
3654 // LR operator-(L, R);
3655 // bool operator<(L, R);
3656 // bool operator>(L, R);
3657 // bool operator<=(L, R);
3658 // bool operator>=(L, R);
3659 // bool operator==(L, R);
3660 // bool operator!=(L, R);
3661 //
3662 // where LR is the result of the usual arithmetic conversions
3663 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003664 //
3665 // C++ [over.built]p24:
3666 //
3667 // For every pair of promoted arithmetic types L and R, there exist
3668 // candidate operator functions of the form
3669 //
3670 // LR operator?(bool, L, R);
3671 //
3672 // where LR is the result of the usual arithmetic conversions
3673 // between types L and R.
3674 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003675 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003676 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003677 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003678 Right < LastPromotedArithmeticType; ++Right) {
3679 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003680 QualType Result
3681 = isComparison
3682 ? Context.BoolTy
3683 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003684 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3685 }
3686 }
3687 break;
3688
3689 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003690 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003691 case OO_Caret:
3692 case OO_Pipe:
3693 case OO_LessLess:
3694 case OO_GreaterGreater:
3695 // C++ [over.built]p17:
3696 //
3697 // For every pair of promoted integral types L and R, there
3698 // exist candidate operator functions of the form
3699 //
3700 // LR operator%(L, R);
3701 // LR operator&(L, R);
3702 // LR operator^(L, R);
3703 // LR operator|(L, R);
3704 // L operator<<(L, R);
3705 // L operator>>(L, R);
3706 //
3707 // where LR is the result of the usual arithmetic conversions
3708 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003709 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003710 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003711 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003712 Right < LastPromotedIntegralType; ++Right) {
3713 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3714 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3715 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003716 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003717 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3718 }
3719 }
3720 break;
3721
3722 case OO_Equal:
3723 // C++ [over.built]p20:
3724 //
3725 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003726 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003727 // empty, there exist candidate operator functions of the form
3728 //
3729 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003730 for (BuiltinCandidateTypeSet::iterator
3731 Enum = CandidateTypes.enumeration_begin(),
3732 EnumEnd = CandidateTypes.enumeration_end();
3733 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003734 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003735 CandidateSet);
3736 for (BuiltinCandidateTypeSet::iterator
3737 MemPtr = CandidateTypes.member_pointer_begin(),
3738 MemPtrEnd = CandidateTypes.member_pointer_end();
3739 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003740 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003741 CandidateSet);
3742 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003743
3744 case OO_PlusEqual:
3745 case OO_MinusEqual:
3746 // C++ [over.built]p19:
3747 //
3748 // For every pair (T, VQ), where T is any type and VQ is either
3749 // volatile or empty, there exist candidate operator functions
3750 // of the form
3751 //
3752 // T*VQ& operator=(T*VQ&, T*);
3753 //
3754 // C++ [over.built]p21:
3755 //
3756 // For every pair (T, VQ), where T is a cv-qualified or
3757 // cv-unqualified object type and VQ is either volatile or
3758 // empty, there exist candidate operator functions of the form
3759 //
3760 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3761 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3762 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3763 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3764 QualType ParamTypes[2];
3765 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3766
3767 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003768 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003769 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3770 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003771
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003772 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3773 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003774 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003775 ParamTypes[0]
3776 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003777 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3778 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003779 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003780 }
3781 // Fall through.
3782
3783 case OO_StarEqual:
3784 case OO_SlashEqual:
3785 // C++ [over.built]p18:
3786 //
3787 // For every triple (L, VQ, R), where L is an arithmetic type,
3788 // VQ is either volatile or empty, and R is a promoted
3789 // arithmetic type, there exist candidate operator functions of
3790 // the form
3791 //
3792 // VQ L& operator=(VQ L&, R);
3793 // VQ L& operator*=(VQ L&, R);
3794 // VQ L& operator/=(VQ L&, R);
3795 // VQ L& operator+=(VQ L&, R);
3796 // VQ L& operator-=(VQ L&, R);
3797 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003798 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003799 Right < LastPromotedArithmeticType; ++Right) {
3800 QualType ParamTypes[2];
3801 ParamTypes[1] = ArithmeticTypes[Right];
3802
3803 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003804 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003805 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3806 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003807
3808 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003809 if (VisibleTypeConversionsQuals.hasVolatile()) {
3810 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3811 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3812 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3813 /*IsAssigmentOperator=*/Op == OO_Equal);
3814 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003815 }
3816 }
3817 break;
3818
3819 case OO_PercentEqual:
3820 case OO_LessLessEqual:
3821 case OO_GreaterGreaterEqual:
3822 case OO_AmpEqual:
3823 case OO_CaretEqual:
3824 case OO_PipeEqual:
3825 // C++ [over.built]p22:
3826 //
3827 // For every triple (L, VQ, R), where L is an integral type, VQ
3828 // is either volatile or empty, and R is a promoted integral
3829 // type, there exist candidate operator functions of the form
3830 //
3831 // VQ L& operator%=(VQ L&, R);
3832 // VQ L& operator<<=(VQ L&, R);
3833 // VQ L& operator>>=(VQ L&, R);
3834 // VQ L& operator&=(VQ L&, R);
3835 // VQ L& operator^=(VQ L&, R);
3836 // VQ L& operator|=(VQ L&, R);
3837 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003838 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003839 Right < LastPromotedIntegralType; ++Right) {
3840 QualType ParamTypes[2];
3841 ParamTypes[1] = ArithmeticTypes[Right];
3842
3843 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003844 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003845 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003846 if (VisibleTypeConversionsQuals.hasVolatile()) {
3847 // Add this built-in operator as a candidate (VQ is 'volatile').
3848 ParamTypes[0] = ArithmeticTypes[Left];
3849 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3850 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3851 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3852 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003853 }
3854 }
3855 break;
3856
Douglas Gregord08452f2008-11-19 15:42:04 +00003857 case OO_Exclaim: {
3858 // C++ [over.operator]p23:
3859 //
3860 // There also exist candidate operator functions of the form
3861 //
Mike Stump11289f42009-09-09 15:08:12 +00003862 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003863 // bool operator&&(bool, bool); [BELOW]
3864 // bool operator||(bool, bool); [BELOW]
3865 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003866 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3867 /*IsAssignmentOperator=*/false,
3868 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003869 break;
3870 }
3871
Douglas Gregora11693b2008-11-12 17:17:38 +00003872 case OO_AmpAmp:
3873 case OO_PipePipe: {
3874 // C++ [over.operator]p23:
3875 //
3876 // There also exist candidate operator functions of the form
3877 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003878 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003879 // bool operator&&(bool, bool);
3880 // bool operator||(bool, bool);
3881 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003882 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3883 /*IsAssignmentOperator=*/false,
3884 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003885 break;
3886 }
3887
3888 case OO_Subscript:
3889 // C++ [over.built]p13:
3890 //
3891 // For every cv-qualified or cv-unqualified object type T there
3892 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003893 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003894 // T* operator+(T*, ptrdiff_t); [ABOVE]
3895 // T& operator[](T*, ptrdiff_t);
3896 // T* operator-(T*, ptrdiff_t); [ABOVE]
3897 // T* operator+(ptrdiff_t, T*); [ABOVE]
3898 // T& operator[](ptrdiff_t, T*);
3899 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3900 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3901 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003902 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003903 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003904
3905 // T& operator[](T*, ptrdiff_t)
3906 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3907
3908 // T& operator[](ptrdiff_t, T*);
3909 ParamTypes[0] = ParamTypes[1];
3910 ParamTypes[1] = *Ptr;
3911 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3912 }
3913 break;
3914
3915 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003916 // C++ [over.built]p11:
3917 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3918 // C1 is the same type as C2 or is a derived class of C2, T is an object
3919 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3920 // there exist candidate operator functions of the form
3921 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3922 // where CV12 is the union of CV1 and CV2.
3923 {
3924 for (BuiltinCandidateTypeSet::iterator Ptr =
3925 CandidateTypes.pointer_begin();
3926 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3927 QualType C1Ty = (*Ptr);
3928 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003929 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003930 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003931 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003932 if (!isa<RecordType>(C1))
3933 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003934 // heuristic to reduce number of builtin candidates in the set.
3935 // Add volatile/restrict version only if there are conversions to a
3936 // volatile/restrict type.
3937 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3938 continue;
3939 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3940 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003941 }
3942 for (BuiltinCandidateTypeSet::iterator
3943 MemPtr = CandidateTypes.member_pointer_begin(),
3944 MemPtrEnd = CandidateTypes.member_pointer_end();
3945 MemPtr != MemPtrEnd; ++MemPtr) {
3946 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3947 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00003948 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003949 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3950 break;
3951 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3952 // build CV12 T&
3953 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003954 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3955 T.isVolatileQualified())
3956 continue;
3957 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3958 T.isRestrictQualified())
3959 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003960 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003961 QualType ResultTy = Context.getLValueReferenceType(T);
3962 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3963 }
3964 }
3965 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003966 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003967
3968 case OO_Conditional:
3969 // Note that we don't consider the first argument, since it has been
3970 // contextually converted to bool long ago. The candidates below are
3971 // therefore added as binary.
3972 //
3973 // C++ [over.built]p24:
3974 // For every type T, where T is a pointer or pointer-to-member type,
3975 // there exist candidate operator functions of the form
3976 //
3977 // T operator?(bool, T, T);
3978 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003979 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3980 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3981 QualType ParamTypes[2] = { *Ptr, *Ptr };
3982 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3983 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003984 for (BuiltinCandidateTypeSet::iterator Ptr =
3985 CandidateTypes.member_pointer_begin(),
3986 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3987 QualType ParamTypes[2] = { *Ptr, *Ptr };
3988 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3989 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003990 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003991 }
3992}
3993
Douglas Gregore254f902009-02-04 00:32:51 +00003994/// \brief Add function candidates found via argument-dependent lookup
3995/// to the set of overloading candidates.
3996///
3997/// This routine performs argument-dependent name lookup based on the
3998/// given function name (which may also be an operator name) and adds
3999/// all of the overload candidates found by ADL to the overload
4000/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004001void
Douglas Gregore254f902009-02-04 00:32:51 +00004002Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4003 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004004 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004005 OverloadCandidateSet& CandidateSet,
4006 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004007 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00004008
Douglas Gregorcabea402009-09-22 15:41:20 +00004009 // FIXME: Should we be trafficking in canonical function decls throughout?
4010
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004011 // Record all of the function candidates that we've already
4012 // added to the overload set, so that we don't add those same
4013 // candidates a second time.
4014 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4015 CandEnd = CandidateSet.end();
4016 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004017 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004018 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004019 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4020 Functions.insert(FunTmpl);
4021 }
Douglas Gregore254f902009-02-04 00:32:51 +00004022
Douglas Gregorcabea402009-09-22 15:41:20 +00004023 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00004024 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00004025
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004026 // Erase all of the candidates we already knew about.
4027 // FIXME: This is suboptimal. Is there a better way?
4028 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4029 CandEnd = CandidateSet.end();
4030 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004031 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004032 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004033 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4034 Functions.erase(FunTmpl);
4035 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004036
4037 // For each of the ADL candidates we found, add it to the overload
4038 // set.
4039 for (FunctionSet::iterator Func = Functions.begin(),
4040 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00004041 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004042 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCall6b51f282009-11-23 01:53:49 +00004043 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004044 continue;
4045
4046 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4047 false, false, PartialOverloading);
4048 } else
Mike Stump11289f42009-09-09 15:08:12 +00004049 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00004050 ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004051 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004052 }
Douglas Gregore254f902009-02-04 00:32:51 +00004053}
4054
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004055/// isBetterOverloadCandidate - Determines whether the first overload
4056/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004057bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004058Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00004059 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004060 // Define viable functions to be better candidates than non-viable
4061 // functions.
4062 if (!Cand2.Viable)
4063 return Cand1.Viable;
4064 else if (!Cand1.Viable)
4065 return false;
4066
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004067 // C++ [over.match.best]p1:
4068 //
4069 // -- if F is a static member function, ICS1(F) is defined such
4070 // that ICS1(F) is neither better nor worse than ICS1(G) for
4071 // any function G, and, symmetrically, ICS1(G) is neither
4072 // better nor worse than ICS1(F).
4073 unsigned StartArg = 0;
4074 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4075 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004076
Douglas Gregord3cb3562009-07-07 23:38:56 +00004077 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004078 // A viable function F1 is defined to be a better function than another
4079 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004080 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004081 unsigned NumArgs = Cand1.Conversions.size();
4082 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4083 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004084 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004085 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4086 Cand2.Conversions[ArgIdx])) {
4087 case ImplicitConversionSequence::Better:
4088 // Cand1 has a better conversion sequence.
4089 HasBetterConversion = true;
4090 break;
4091
4092 case ImplicitConversionSequence::Worse:
4093 // Cand1 can't be better than Cand2.
4094 return false;
4095
4096 case ImplicitConversionSequence::Indistinguishable:
4097 // Do nothing.
4098 break;
4099 }
4100 }
4101
Mike Stump11289f42009-09-09 15:08:12 +00004102 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004103 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004104 if (HasBetterConversion)
4105 return true;
4106
Mike Stump11289f42009-09-09 15:08:12 +00004107 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004108 // specialization, or, if not that,
4109 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4110 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4111 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004112
4113 // -- F1 and F2 are function template specializations, and the function
4114 // template for F1 is more specialized than the template for F2
4115 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004116 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004117 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4118 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004119 if (FunctionTemplateDecl *BetterTemplate
4120 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4121 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004122 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4123 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004124 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004125
Douglas Gregora1f013e2008-11-07 22:36:19 +00004126 // -- the context is an initialization by user-defined conversion
4127 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4128 // from the return type of F1 to the destination type (i.e.,
4129 // the type of the entity being initialized) is a better
4130 // conversion sequence than the standard conversion sequence
4131 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004132 if (Cand1.Function && Cand2.Function &&
4133 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004134 isa<CXXConversionDecl>(Cand2.Function)) {
4135 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4136 Cand2.FinalConversion)) {
4137 case ImplicitConversionSequence::Better:
4138 // Cand1 has a better conversion sequence.
4139 return true;
4140
4141 case ImplicitConversionSequence::Worse:
4142 // Cand1 can't be better than Cand2.
4143 return false;
4144
4145 case ImplicitConversionSequence::Indistinguishable:
4146 // Do nothing
4147 break;
4148 }
4149 }
4150
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004151 return false;
4152}
4153
Mike Stump11289f42009-09-09 15:08:12 +00004154/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004155/// within an overload candidate set.
4156///
4157/// \param CandidateSet the set of candidate functions.
4158///
4159/// \param Loc the location of the function name (or operator symbol) for
4160/// which overload resolution occurs.
4161///
Mike Stump11289f42009-09-09 15:08:12 +00004162/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004163/// function, Best points to the candidate function found.
4164///
4165/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00004166Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004167Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004168 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004169 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004170 // Find the best viable function.
4171 Best = CandidateSet.end();
4172 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4173 Cand != CandidateSet.end(); ++Cand) {
4174 if (Cand->Viable) {
4175 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4176 Best = Cand;
4177 }
4178 }
4179
4180 // If we didn't find any viable functions, abort.
4181 if (Best == CandidateSet.end())
4182 return OR_No_Viable_Function;
4183
4184 // Make sure that this function is better than every other viable
4185 // function. If not, we have an ambiguity.
4186 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4187 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004188 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004189 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004190 !isBetterOverloadCandidate(*Best, *Cand)) {
4191 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004192 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004193 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004194 }
Mike Stump11289f42009-09-09 15:08:12 +00004195
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004196 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004197 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004198 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004199 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004200 return OR_Deleted;
4201
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004202 // C++ [basic.def.odr]p2:
4203 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004204 // when referred to from a potentially-evaluated expression. [Note: this
4205 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004206 // (clause 13), user-defined conversions (12.3.2), allocation function for
4207 // placement new (5.3.4), as well as non-default initialization (8.5).
4208 if (Best->Function)
4209 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004210 return OR_Success;
4211}
4212
4213/// PrintOverloadCandidates - When overload resolution fails, prints
4214/// diagnostic messages containing the candidates in the candidate
4215/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00004216void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004217Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004218 bool OnlyViable,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004219 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004220 SourceLocation OpLoc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004221 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4222 LastCand = CandidateSet.end();
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004223 bool Reported = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004224 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004225 if (Cand->Viable || !OnlyViable) {
4226 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004227 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004228 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004229 // Deleted or "unavailable" function.
4230 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4231 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00004232 } else if (FunctionTemplateDecl *FunTmpl
4233 = Cand->Function->getPrimaryTemplate()) {
4234 // Function template specialization
4235 // FIXME: Give a better reason!
4236 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4237 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4238 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00004239 } else {
4240 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00004241 bool errReported = false;
4242 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4243 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4244 const ImplicitConversionSequence &Conversion =
4245 Cand->Conversions[i];
4246 if ((Conversion.ConversionKind !=
4247 ImplicitConversionSequence::BadConversion) ||
4248 Conversion.ConversionFunctionSet.size() == 0)
4249 continue;
4250 Diag(Cand->Function->getLocation(),
4251 diag::err_ovl_candidate_not_viable) << (i+1);
4252 errReported = true;
4253 for (int j = Conversion.ConversionFunctionSet.size()-1;
4254 j >= 0; j--) {
4255 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4256 Diag(Func->getLocation(), diag::err_ovl_candidate);
4257 }
4258 }
4259 }
4260 if (!errReported)
4261 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004262 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004263 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004264 // Desugar the type of the surrogate down to a function type,
4265 // retaining as many typedefs as possible while still showing
4266 // the function type (and, therefore, its parameter types).
4267 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004268 bool isLValueReference = false;
4269 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004270 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004271 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004272 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004273 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004274 isLValueReference = true;
4275 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004276 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004277 FnType = FnTypeRef->getPointeeType();
4278 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004279 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004280 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004281 FnType = FnTypePtr->getPointeeType();
4282 isPointer = true;
4283 }
4284 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00004285 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004286 // Reconstruct the pointer/reference as appropriate.
4287 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004288 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4289 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004290
Douglas Gregorab7897a2008-11-19 22:57:39 +00004291 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004292 << FnType;
Douglas Gregor66950a32009-09-30 21:46:01 +00004293 } else if (OnlyViable) {
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004294 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanian0fe5e032009-10-09 17:09:58 +00004295 "builtin-binary-operator-not-binary");
Fariborz Jahanian956127d2009-10-16 23:25:02 +00004296 std::string TypeStr("operator");
4297 TypeStr += Opc;
4298 TypeStr += "(";
4299 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4300 if (Cand->Conversions.size() == 1) {
4301 TypeStr += ")";
4302 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4303 }
4304 else {
4305 TypeStr += ", ";
4306 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4307 TypeStr += ")";
4308 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4309 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004310 }
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004311 else if (!Cand->Viable && !Reported) {
4312 // Non-viability might be due to ambiguous user-defined conversions,
4313 // needed for built-in operators. Report them as well, but only once
4314 // as we have typically many built-in candidates.
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004315 unsigned NoOperands = Cand->Conversions.size();
4316 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004317 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4318 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4319 ICS.ConversionFunctionSet.empty())
4320 continue;
4321 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4322 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4323 QualType FromTy =
4324 QualType(
4325 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4326 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4327 << FromTy << Func->getConversionType();
4328 }
4329 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4330 FunctionDecl *Func =
4331 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4332 Diag(Func->getLocation(),diag::err_ovl_candidate);
4333 }
4334 }
4335 Reported = true;
4336 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004337 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004338 }
4339}
4340
Douglas Gregorcd695e52008-11-10 20:40:00 +00004341/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4342/// an overloaded function (C++ [over.over]), where @p From is an
4343/// expression with overloaded function type and @p ToType is the type
4344/// we're trying to resolve to. For example:
4345///
4346/// @code
4347/// int f(double);
4348/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004349///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004350/// int (*pfd)(double) = f; // selects f(double)
4351/// @endcode
4352///
4353/// This routine returns the resulting FunctionDecl if it could be
4354/// resolved, and NULL otherwise. When @p Complain is true, this
4355/// routine will emit diagnostics if there is an error.
4356FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004357Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004358 bool Complain) {
4359 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004360 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004361 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004362 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004363 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004364 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004365 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004366 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004367 FunctionType = MemTypePtr->getPointeeType();
4368 IsMember = true;
4369 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004370
4371 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004372 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004373 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004374 return 0;
4375
4376 // Find the actual overloaded function declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004377
Douglas Gregorcd695e52008-11-10 20:40:00 +00004378 // C++ [over.over]p1:
4379 // [...] [Note: any redundant set of parentheses surrounding the
4380 // overloaded function name is ignored (5.1). ]
4381 Expr *OvlExpr = From->IgnoreParens();
4382
4383 // C++ [over.over]p1:
4384 // [...] The overloaded function name can be preceded by the &
4385 // operator.
4386 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4387 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4388 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4389 }
4390
Anders Carlssonb68b0282009-10-20 22:53:47 +00004391 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004392 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCalld14a8642009-11-21 08:51:07 +00004393
4394 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004395
John McCall10eae182009-11-30 22:42:35 +00004396 // Look into the overloaded expression.
John McCalle66edc12009-11-24 19:00:30 +00004397 if (UnresolvedLookupExpr *UL
John McCalld14a8642009-11-21 08:51:07 +00004398 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4399 Fns.append(UL->decls_begin(), UL->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00004400 if (UL->hasExplicitTemplateArgs()) {
4401 HasExplicitTemplateArgs = true;
4402 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4403 }
John McCall10eae182009-11-30 22:42:35 +00004404 } else if (UnresolvedMemberExpr *ME
4405 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4406 Fns.append(ME->decls_begin(), ME->decls_end());
4407 if (ME->hasExplicitTemplateArgs()) {
4408 HasExplicitTemplateArgs = true;
John McCall6b51f282009-11-23 01:53:49 +00004409 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004410 }
Douglas Gregor9b146582009-07-08 20:55:45 +00004411 }
Mike Stump11289f42009-09-09 15:08:12 +00004412
John McCalld14a8642009-11-21 08:51:07 +00004413 // If we didn't actually find anything, we're done.
4414 if (Fns.empty())
4415 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004416
Douglas Gregorcd695e52008-11-10 20:40:00 +00004417 // Look through all of the overloaded functions, searching for one
4418 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004419 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004420 bool FoundNonTemplateFunction = false;
John McCalld14a8642009-11-21 08:51:07 +00004421 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4422 E = Fns.end(); I != E; ++I) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004423 // C++ [over.over]p3:
4424 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004425 // targets of type "pointer-to-function" or "reference-to-function."
4426 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004427 // type "pointer-to-member-function."
4428 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004429
Mike Stump11289f42009-09-09 15:08:12 +00004430 if (FunctionTemplateDecl *FunctionTemplate
John McCalld14a8642009-11-21 08:51:07 +00004431 = dyn_cast<FunctionTemplateDecl>(*I)) {
Mike Stump11289f42009-09-09 15:08:12 +00004432 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004433 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004434 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004435 // static when converting to member pointer.
4436 if (Method->isStatic() == IsMember)
4437 continue;
4438 } else if (IsMember)
4439 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004440
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004441 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004442 // If the name is a function template, template argument deduction is
4443 // done (14.8.2.2), and if the argument deduction succeeds, the
4444 // resulting template argument list is used to generate a single
4445 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004446 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004447 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004448 FunctionDecl *Specialization = 0;
4449 TemplateDeductionInfo Info(Context);
4450 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004451 = DeduceTemplateArguments(FunctionTemplate,
4452 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor9b146582009-07-08 20:55:45 +00004453 FunctionType, Specialization, Info)) {
4454 // FIXME: make a note of the failed deduction for diagnostics.
4455 (void)Result;
4456 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004457 // FIXME: If the match isn't exact, shouldn't we just drop this as
4458 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004459 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004460 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004461 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004462 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004463 }
John McCalld14a8642009-11-21 08:51:07 +00004464
4465 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00004466 }
Mike Stump11289f42009-09-09 15:08:12 +00004467
John McCalld14a8642009-11-21 08:51:07 +00004468 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004469 // Skip non-static functions when converting to pointer, and static
4470 // when converting to member pointer.
4471 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004472 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004473
4474 // If we have explicit template arguments, skip non-templates.
4475 if (HasExplicitTemplateArgs)
4476 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004477 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004478 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004479
John McCalld14a8642009-11-21 08:51:07 +00004480 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*I)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00004481 QualType ResultTy;
4482 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4483 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4484 ResultTy)) {
John McCalld14a8642009-11-21 08:51:07 +00004485 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004486 FoundNonTemplateFunction = true;
4487 }
Mike Stump11289f42009-09-09 15:08:12 +00004488 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004489 }
4490
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004491 // If there were 0 or 1 matches, we're done.
4492 if (Matches.empty())
4493 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004494 else if (Matches.size() == 1) {
4495 FunctionDecl *Result = *Matches.begin();
4496 MarkDeclarationReferenced(From->getLocStart(), Result);
4497 return Result;
4498 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004499
4500 // C++ [over.over]p4:
4501 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004502 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004503 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004504 // [...] and any given function template specialization F1 is
4505 // eliminated if the set contains a second function template
4506 // specialization whose function template is more specialized
4507 // than the function template of F1 according to the partial
4508 // ordering rules of 14.5.5.2.
4509
4510 // The algorithm specified above is quadratic. We instead use a
4511 // two-pass algorithm (similar to the one used to identify the
4512 // best viable function in an overload set) that identifies the
4513 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004514 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004515 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004516 FunctionDecl *Result =
4517 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4518 TPOC_Other, From->getLocStart(),
4519 PDiag(),
4520 PDiag(diag::err_addr_ovl_ambiguous)
4521 << TemplateMatches[0]->getDeclName(),
4522 PDiag(diag::err_ovl_template_candidate));
4523 MarkDeclarationReferenced(From->getLocStart(), Result);
4524 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004525 }
Mike Stump11289f42009-09-09 15:08:12 +00004526
Douglas Gregorfae1d712009-09-26 03:56:17 +00004527 // [...] any function template specializations in the set are
4528 // eliminated if the set also contains a non-template function, [...]
4529 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4530 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4531 if ((*M)->getPrimaryTemplate() == 0)
4532 RemainingMatches.push_back(*M);
4533
Mike Stump11289f42009-09-09 15:08:12 +00004534 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004535 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004536 if (RemainingMatches.size() == 1) {
4537 FunctionDecl *Result = RemainingMatches.front();
4538 MarkDeclarationReferenced(From->getLocStart(), Result);
4539 return Result;
4540 }
Mike Stump11289f42009-09-09 15:08:12 +00004541
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004542 // FIXME: We should probably return the same thing that BestViableFunction
4543 // returns (even if we issue the diagnostics here).
4544 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4545 << RemainingMatches[0]->getDeclName();
4546 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4547 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004548 return 0;
4549}
4550
Douglas Gregorcabea402009-09-22 15:41:20 +00004551/// \brief Add a single candidate to the overload set.
4552static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00004553 NamedDecl *Callee,
John McCall6b51f282009-11-23 01:53:49 +00004554 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004555 Expr **Args, unsigned NumArgs,
4556 OverloadCandidateSet &CandidateSet,
4557 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004558 if (isa<UsingShadowDecl>(Callee))
4559 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4560
Douglas Gregorcabea402009-09-22 15:41:20 +00004561 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004562 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorcabea402009-09-22 15:41:20 +00004563 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4564 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004565 return;
John McCalld14a8642009-11-21 08:51:07 +00004566 }
4567
4568 if (FunctionTemplateDecl *FuncTemplate
4569 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004570 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004571 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00004572 return;
4573 }
4574
4575 assert(false && "unhandled case in overloaded call candidate");
4576
4577 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00004578}
4579
4580/// \brief Add the overload candidates named by callee and/or found by argument
4581/// dependent lookup to the given overload set.
John McCalld14a8642009-11-21 08:51:07 +00004582void Sema::AddOverloadedCallCandidates(llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregorcabea402009-09-22 15:41:20 +00004583 DeclarationName &UnqualifiedName,
John McCall4b1f16e2009-11-21 09:38:42 +00004584 bool ArgumentDependentLookup,
John McCall6b51f282009-11-23 01:53:49 +00004585 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004586 Expr **Args, unsigned NumArgs,
4587 OverloadCandidateSet &CandidateSet,
4588 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004589
4590#ifndef NDEBUG
4591 // Verify that ArgumentDependentLookup is consistent with the rules
4592 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00004593 //
Douglas Gregorcabea402009-09-22 15:41:20 +00004594 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4595 // and let Y be the lookup set produced by argument dependent
4596 // lookup (defined as follows). If X contains
4597 //
4598 // -- a declaration of a class member, or
4599 //
4600 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00004601 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00004602 //
4603 // -- a declaration that is neither a function or a function
4604 // template
4605 //
4606 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00004607
4608 if (ArgumentDependentLookup) {
4609 for (unsigned I = 0; I < Fns.size(); ++I) {
4610 assert(!Fns[I]->getDeclContext()->isRecord());
4611 assert(isa<UsingShadowDecl>(Fns[I]) ||
4612 !Fns[I]->getDeclContext()->isFunctionOrMethod());
4613 assert(Fns[I]->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
4614 }
4615 }
4616#endif
4617
4618 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4619 E = Fns.end(); I != E; ++I)
John McCall6b51f282009-11-23 01:53:49 +00004620 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004621 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00004622 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00004623
Douglas Gregorcabea402009-09-22 15:41:20 +00004624 if (ArgumentDependentLookup)
4625 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004626 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004627 CandidateSet,
4628 PartialOverloading);
4629}
4630
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004631/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004632/// (which eventually refers to the declaration Func) and the call
4633/// arguments Args/NumArgs, attempt to resolve the function call down
4634/// to a specific function. If overload resolution succeeds, returns
4635/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004636/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004637/// arguments and Fn, and returns NULL.
John McCalld14a8642009-11-21 08:51:07 +00004638FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn,
4639 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004640 DeclarationName UnqualifiedName,
John McCall6b51f282009-11-23 01:53:49 +00004641 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004642 SourceLocation LParenLoc,
4643 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004644 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004645 SourceLocation RParenLoc,
John McCall4b1f16e2009-11-21 09:38:42 +00004646 bool ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004647 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004648
4649 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004650 // functions.
John McCalld14a8642009-11-21 08:51:07 +00004651 AddOverloadedCallCandidates(Fns, UnqualifiedName, ArgumentDependentLookup,
John McCall6b51f282009-11-23 01:53:49 +00004652 ExplicitTemplateArgs, Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004653 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004654 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004655 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004656 case OR_Success:
4657 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004658
4659 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004660 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004661 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004662 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004663 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4664 break;
4665
4666 case OR_Ambiguous:
4667 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004668 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004669 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4670 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004671
4672 case OR_Deleted:
4673 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4674 << Best->Function->isDeleted()
4675 << UnqualifiedName
4676 << Fn->getSourceRange();
4677 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4678 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004679 }
4680
4681 // Overload resolution failed. Destroy all of the subexpressions and
4682 // return NULL.
4683 Fn->Destroy(Context);
4684 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4685 Args[Arg]->Destroy(Context);
4686 return 0;
4687}
4688
John McCall283b9012009-11-22 00:44:51 +00004689static bool IsOverloaded(const Sema::FunctionSet &Functions) {
4690 return Functions.size() > 1 ||
4691 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
4692}
4693
Douglas Gregor084d8552009-03-13 23:49:33 +00004694/// \brief Create a unary operation that may resolve to an overloaded
4695/// operator.
4696///
4697/// \param OpLoc The location of the operator itself (e.g., '*').
4698///
4699/// \param OpcIn The UnaryOperator::Opcode that describes this
4700/// operator.
4701///
4702/// \param Functions The set of non-member functions that will be
4703/// considered by overload resolution. The caller needs to build this
4704/// set based on the context using, e.g.,
4705/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4706/// set should not contain any member functions; those will be added
4707/// by CreateOverloadedUnaryOp().
4708///
4709/// \param input The input argument.
4710Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4711 unsigned OpcIn,
4712 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004713 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004714 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4715 Expr *Input = (Expr *)input.get();
4716
4717 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4718 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4719 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4720
4721 Expr *Args[2] = { Input, 0 };
4722 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004723
Douglas Gregor084d8552009-03-13 23:49:33 +00004724 // For post-increment and post-decrement, add the implicit '0' as
4725 // the second argument, so that we know this is a post-increment or
4726 // post-decrement.
4727 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4728 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004729 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004730 SourceLocation());
4731 NumArgs = 2;
4732 }
4733
4734 if (Input->isTypeDependent()) {
John McCalld14a8642009-11-21 08:51:07 +00004735 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00004736 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4737 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00004738 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump11289f42009-09-09 15:08:12 +00004739 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004740 FuncEnd = Functions.end();
4741 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00004742 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00004743
Douglas Gregor084d8552009-03-13 23:49:33 +00004744 input.release();
4745 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4746 &Args[0], NumArgs,
4747 Context.DependentTy,
4748 OpLoc));
4749 }
4750
4751 // Build an empty overload set.
4752 OverloadCandidateSet CandidateSet;
4753
4754 // Add the candidates from the given function set.
4755 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4756
4757 // Add operator candidates that are member functions.
4758 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4759
4760 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004761 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00004762
4763 // Perform overload resolution.
4764 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004765 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004766 case OR_Success: {
4767 // We found a built-in operator or an overloaded operator.
4768 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004769
Douglas Gregor084d8552009-03-13 23:49:33 +00004770 if (FnDecl) {
4771 // We matched an overloaded operator. Build a call to that
4772 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004773
Douglas Gregor084d8552009-03-13 23:49:33 +00004774 // Convert the arguments.
4775 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4776 if (PerformObjectArgumentInitialization(Input, Method))
4777 return ExprError();
4778 } else {
4779 // Convert the arguments.
4780 if (PerformCopyInitialization(Input,
4781 FnDecl->getParamDecl(0)->getType(),
4782 "passing"))
4783 return ExprError();
4784 }
4785
4786 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004787 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004788
Douglas Gregor084d8552009-03-13 23:49:33 +00004789 // Build the actual expression node.
4790 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4791 SourceLocation());
4792 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004793
Douglas Gregor084d8552009-03-13 23:49:33 +00004794 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00004795 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004796 ExprOwningPtr<CallExpr> TheCall(this,
4797 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00004798 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004799
4800 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4801 FnDecl))
4802 return ExprError();
4803
4804 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00004805 } else {
4806 // We matched a built-in operator. Convert the arguments, then
4807 // break out so that we will build the appropriate built-in
4808 // operator node.
4809 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4810 Best->Conversions[0], "passing"))
4811 return ExprError();
4812
4813 break;
4814 }
4815 }
4816
4817 case OR_No_Viable_Function:
4818 // No viable function; fall through to handling this as a
4819 // built-in operator, which will produce an error message for us.
4820 break;
4821
4822 case OR_Ambiguous:
4823 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4824 << UnaryOperator::getOpcodeStr(Opc)
4825 << Input->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004826 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4827 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00004828 return ExprError();
4829
4830 case OR_Deleted:
4831 Diag(OpLoc, diag::err_ovl_deleted_oper)
4832 << Best->Function->isDeleted()
4833 << UnaryOperator::getOpcodeStr(Opc)
4834 << Input->getSourceRange();
4835 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4836 return ExprError();
4837 }
4838
4839 // Either we found no viable overloaded operator or we matched a
4840 // built-in operator. In either case, fall through to trying to
4841 // build a built-in operation.
4842 input.release();
4843 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4844}
4845
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004846/// \brief Create a binary operation that may resolve to an overloaded
4847/// operator.
4848///
4849/// \param OpLoc The location of the operator itself (e.g., '+').
4850///
4851/// \param OpcIn The BinaryOperator::Opcode that describes this
4852/// operator.
4853///
4854/// \param Functions The set of non-member functions that will be
4855/// considered by overload resolution. The caller needs to build this
4856/// set based on the context using, e.g.,
4857/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4858/// set should not contain any member functions; those will be added
4859/// by CreateOverloadedBinOp().
4860///
4861/// \param LHS Left-hand argument.
4862/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004863Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004864Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004865 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004866 FunctionSet &Functions,
4867 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004868 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004869 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004870
4871 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4872 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4873 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4874
4875 // If either side is type-dependent, create an appropriate dependent
4876 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004877 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00004878 if (Functions.empty()) {
4879 // If there are no functions to store, just build a dependent
4880 // BinaryOperator or CompoundAssignment.
4881 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4882 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4883 Context.DependentTy, OpLoc));
4884
4885 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4886 Context.DependentTy,
4887 Context.DependentTy,
4888 Context.DependentTy,
4889 OpLoc));
4890 }
4891
John McCalld14a8642009-11-21 08:51:07 +00004892 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00004893 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4894 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00004895 /* ADL */ true, IsOverloaded(Functions));
John McCalld14a8642009-11-21 08:51:07 +00004896
Mike Stump11289f42009-09-09 15:08:12 +00004897 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004898 FuncEnd = Functions.end();
4899 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00004900 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00004901
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004902 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004903 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004904 Context.DependentTy,
4905 OpLoc));
4906 }
4907
4908 // If this is the .* operator, which is not overloadable, just
4909 // create a built-in binary operator.
4910 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004911 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004912
Sebastian Redl6a96bf72009-11-18 23:10:33 +00004913 // If this is the assignment operator, we only perform overload resolution
4914 // if the left-hand side is a class or enumeration type. This is actually
4915 // a hack. The standard requires that we do overload resolution between the
4916 // various built-in candidates, but as DR507 points out, this can lead to
4917 // problems. So we do it this way, which pretty much follows what GCC does.
4918 // Note that we go the traditional code path for compound assignment forms.
4919 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00004920 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004921
Douglas Gregor084d8552009-03-13 23:49:33 +00004922 // Build an empty overload set.
4923 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004924
4925 // Add the candidates from the given function set.
4926 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4927
4928 // Add operator candidates that are member functions.
4929 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4930
4931 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004932 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004933
4934 // Perform overload resolution.
4935 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004936 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004937 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004938 // We found a built-in operator or an overloaded operator.
4939 FunctionDecl *FnDecl = Best->Function;
4940
4941 if (FnDecl) {
4942 // We matched an overloaded operator. Build a call to that
4943 // operator.
4944
4945 // Convert the arguments.
4946 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004947 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4948 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004949 "passing"))
4950 return ExprError();
4951 } else {
4952 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004953 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004954 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004955 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004956 "passing"))
4957 return ExprError();
4958 }
4959
4960 // Determine the result type
4961 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004962 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004963 ResultTy = ResultTy.getNonReferenceType();
4964
4965 // Build the actual expression node.
4966 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004967 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004968 UsualUnaryConversions(FnExpr);
4969
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00004970 ExprOwningPtr<CXXOperatorCallExpr>
4971 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4972 Args, 2, ResultTy,
4973 OpLoc));
4974
4975 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4976 FnDecl))
4977 return ExprError();
4978
4979 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004980 } else {
4981 // We matched a built-in operator. Convert the arguments, then
4982 // break out so that we will build the appropriate built-in
4983 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004984 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004985 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004986 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004987 Best->Conversions[1], "passing"))
4988 return ExprError();
4989
4990 break;
4991 }
4992 }
4993
Douglas Gregor66950a32009-09-30 21:46:01 +00004994 case OR_No_Viable_Function: {
4995 // C++ [over.match.oper]p9:
4996 // If the operator is the operator , [...] and there are no
4997 // viable functions, then the operator is assumed to be the
4998 // built-in operator and interpreted according to clause 5.
4999 if (Opc == BinaryOperator::Comma)
5000 break;
5001
Sebastian Redl027de2a2009-05-21 11:50:50 +00005002 // For class as left operand for assignment or compound assigment operator
5003 // do not fall through to handling in built-in, but report that no overloaded
5004 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005005 OwningExprResult Result = ExprError();
5006 if (Args[0]->getType()->isRecordType() &&
5007 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005008 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5009 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005010 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005011 } else {
5012 // No viable function; try to create a built-in operation, which will
5013 // produce an error. Then, show the non-viable candidates.
5014 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005015 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005016 assert(Result.isInvalid() &&
5017 "C++ binary operator overloading is missing candidates!");
5018 if (Result.isInvalid())
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005019 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5020 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005021 return move(Result);
5022 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005023
5024 case OR_Ambiguous:
5025 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5026 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005027 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005028 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5029 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005030 return ExprError();
5031
5032 case OR_Deleted:
5033 Diag(OpLoc, diag::err_ovl_deleted_oper)
5034 << Best->Function->isDeleted()
5035 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005036 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005037 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5038 return ExprError();
5039 }
5040
Douglas Gregor66950a32009-09-30 21:46:01 +00005041 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005042 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005043}
5044
Sebastian Redladba46e2009-10-29 20:17:01 +00005045Action::OwningExprResult
5046Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5047 SourceLocation RLoc,
5048 ExprArg Base, ExprArg Idx) {
5049 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5050 static_cast<Expr*>(Idx.get()) };
5051 DeclarationName OpName =
5052 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5053
5054 // If either side is type-dependent, create an appropriate dependent
5055 // expression.
5056 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5057
John McCalld14a8642009-11-21 08:51:07 +00005058 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005059 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5060 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005061 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005062 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005063
5064 Base.release();
5065 Idx.release();
5066 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5067 Args, 2,
5068 Context.DependentTy,
5069 RLoc));
5070 }
5071
5072 // Build an empty overload set.
5073 OverloadCandidateSet CandidateSet;
5074
5075 // Subscript can only be overloaded as a member function.
5076
5077 // Add operator candidates that are member functions.
5078 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5079
5080 // Add builtin operator candidates.
5081 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5082
5083 // Perform overload resolution.
5084 OverloadCandidateSet::iterator Best;
5085 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5086 case OR_Success: {
5087 // We found a built-in operator or an overloaded operator.
5088 FunctionDecl *FnDecl = Best->Function;
5089
5090 if (FnDecl) {
5091 // We matched an overloaded operator. Build a call to that
5092 // operator.
5093
5094 // Convert the arguments.
5095 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5096 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5097 PerformCopyInitialization(Args[1],
5098 FnDecl->getParamDecl(0)->getType(),
5099 "passing"))
5100 return ExprError();
5101
5102 // Determine the result type
5103 QualType ResultTy
5104 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5105 ResultTy = ResultTy.getNonReferenceType();
5106
5107 // Build the actual expression node.
5108 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5109 LLoc);
5110 UsualUnaryConversions(FnExpr);
5111
5112 Base.release();
5113 Idx.release();
5114 ExprOwningPtr<CXXOperatorCallExpr>
5115 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5116 FnExpr, Args, 2,
5117 ResultTy, RLoc));
5118
5119 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5120 FnDecl))
5121 return ExprError();
5122
5123 return MaybeBindToTemporary(TheCall.release());
5124 } else {
5125 // We matched a built-in operator. Convert the arguments, then
5126 // break out so that we will build the appropriate built-in
5127 // operator node.
5128 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5129 Best->Conversions[0], "passing") ||
5130 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5131 Best->Conversions[1], "passing"))
5132 return ExprError();
5133
5134 break;
5135 }
5136 }
5137
5138 case OR_No_Viable_Function: {
5139 // No viable function; try to create a built-in operation, which will
5140 // produce an error. Then, show the non-viable candidates.
5141 OwningExprResult Result =
5142 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5143 assert(Result.isInvalid() &&
5144 "C++ subscript operator overloading is missing candidates!");
5145 if (Result.isInvalid())
5146 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5147 "[]", LLoc);
5148 return move(Result);
5149 }
5150
5151 case OR_Ambiguous:
5152 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5153 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5154 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5155 "[]", LLoc);
5156 return ExprError();
5157
5158 case OR_Deleted:
5159 Diag(LLoc, diag::err_ovl_deleted_oper)
5160 << Best->Function->isDeleted() << "[]"
5161 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5162 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5163 return ExprError();
5164 }
5165
5166 // We matched a built-in operator; build it.
5167 Base.release();
5168 Idx.release();
5169 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5170 Owned(Args[1]), RLoc);
5171}
5172
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005173/// BuildCallToMemberFunction - Build a call to a member
5174/// function. MemExpr is the expression that refers to the member
5175/// function (and includes the object parameter), Args/NumArgs are the
5176/// arguments to the function call (not including the object
5177/// parameter). The caller needs to validate that the member
5178/// expression refers to a member function or an overloaded member
5179/// function.
John McCall2d74de92009-12-01 22:10:20 +00005180Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005181Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5182 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005183 unsigned NumArgs, SourceLocation *CommaLocs,
5184 SourceLocation RParenLoc) {
5185 // Dig out the member expression. This holds both the object
5186 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00005187 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5188
John McCall10eae182009-11-30 22:42:35 +00005189 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005190 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00005191 if (isa<MemberExpr>(NakedMemExpr)) {
5192 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00005193 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5194 } else {
5195 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCall2d74de92009-12-01 22:10:20 +00005196
John McCall6e9f8f62009-12-03 04:06:58 +00005197 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00005198
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005199 // Add overload candidates
5200 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00005201
John McCall2d74de92009-12-01 22:10:20 +00005202 // FIXME: avoid copy.
5203 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5204 if (UnresExpr->hasExplicitTemplateArgs()) {
5205 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5206 TemplateArgs = &TemplateArgsBuffer;
5207 }
5208
John McCall10eae182009-11-30 22:42:35 +00005209 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5210 E = UnresExpr->decls_end(); I != E; ++I) {
5211
John McCall6e9f8f62009-12-03 04:06:58 +00005212 NamedDecl *Func = *I;
5213 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5214 if (isa<UsingShadowDecl>(Func))
5215 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5216
John McCall10eae182009-11-30 22:42:35 +00005217 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00005218 // If explicit template arguments were provided, we can't call a
5219 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00005220 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00005221 continue;
5222
John McCall6e9f8f62009-12-03 04:06:58 +00005223 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5224 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005225 } else {
John McCall10eae182009-11-30 22:42:35 +00005226 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall6e9f8f62009-12-03 04:06:58 +00005227 ActingDC, TemplateArgs,
5228 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005229 CandidateSet,
5230 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005231 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005232 }
Mike Stump11289f42009-09-09 15:08:12 +00005233
John McCall10eae182009-11-30 22:42:35 +00005234 DeclarationName DeclName = UnresExpr->getMemberName();
5235
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005236 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00005237 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005238 case OR_Success:
5239 Method = cast<CXXMethodDecl>(Best->Function);
5240 break;
5241
5242 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00005243 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005244 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005245 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005246 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5247 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005248 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005249
5250 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00005251 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005252 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005253 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5254 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005255 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005256
5257 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00005258 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00005259 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005260 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005261 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5262 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005263 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005264 }
5265
Douglas Gregor51c538b2009-11-20 19:42:02 +00005266 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00005267
John McCall2d74de92009-12-01 22:10:20 +00005268 // If overload resolution picked a static member, build a
5269 // non-member call based on that function.
5270 if (Method->isStatic()) {
5271 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5272 Args, NumArgs, RParenLoc);
5273 }
5274
John McCall10eae182009-11-30 22:42:35 +00005275 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005276 }
5277
5278 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005279 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00005280 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005281 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005282 Method->getResultType().getNonReferenceType(),
5283 RParenLoc));
5284
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005285 // Check for a valid return type.
5286 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5287 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00005288 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005289
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005290 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00005291 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00005292 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005293 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCall2d74de92009-12-01 22:10:20 +00005294 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005295 MemExpr->setBase(ObjectArg);
5296
5297 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005298 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005299 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005300 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00005301 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005302
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005303 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00005304 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00005305
John McCall2d74de92009-12-01 22:10:20 +00005306 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005307}
5308
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005309/// BuildCallToObjectOfClassType - Build a call to an object of class
5310/// type (C++ [over.call.object]), which can end up invoking an
5311/// overloaded function call operator (@c operator()) or performing a
5312/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005313Sema::ExprResult
5314Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005315 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005316 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005317 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005318 SourceLocation RParenLoc) {
5319 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005320 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005321
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005322 // C++ [over.call.object]p1:
5323 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005324 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005325 // candidate functions includes at least the function call
5326 // operators of T. The function call operators of T are obtained by
5327 // ordinary lookup of the name operator() in the context of
5328 // (E).operator().
5329 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005330 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005331
5332 if (RequireCompleteType(LParenLoc, Object->getType(),
5333 PartialDiagnostic(diag::err_incomplete_object_call)
5334 << Object->getSourceRange()))
5335 return true;
5336
John McCall27b18f82009-11-17 02:14:36 +00005337 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5338 LookupQualifiedName(R, Record->getDecl());
5339 R.suppressDiagnostics();
5340
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005341 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00005342 Oper != OperEnd; ++Oper) {
John McCall6e9f8f62009-12-03 04:06:58 +00005343 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005344 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005345 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005346
Douglas Gregorab7897a2008-11-19 22:57:39 +00005347 // C++ [over.call.object]p2:
5348 // In addition, for each conversion function declared in T of the
5349 // form
5350 //
5351 // operator conversion-type-id () cv-qualifier;
5352 //
5353 // where cv-qualifier is the same cv-qualification as, or a
5354 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005355 // denotes the type "pointer to function of (P1,...,Pn) returning
5356 // R", or the type "reference to pointer to function of
5357 // (P1,...,Pn) returning R", or the type "reference to function
5358 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005359 // is also considered as a candidate function. Similarly,
5360 // surrogate call functions are added to the set of candidate
5361 // functions for each conversion function declared in an
5362 // accessible base class provided the function is not hidden
5363 // within T by another intervening declaration.
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005364 // FIXME: Look in base classes for more conversion operators!
John McCalld14a8642009-11-21 08:51:07 +00005365 const UnresolvedSet *Conversions
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005366 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00005367 for (UnresolvedSet::iterator I = Conversions->begin(),
5368 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00005369 NamedDecl *D = *I;
5370 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5371 if (isa<UsingShadowDecl>(D))
5372 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5373
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005374 // Skip over templated conversion functions; they aren't
5375 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00005376 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005377 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005378
John McCall6e9f8f62009-12-03 04:06:58 +00005379 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00005380
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005381 // Strip the reference type (if any) and then the pointer type (if
5382 // any) to get down to what might be a function type.
5383 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5384 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5385 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005386
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005387 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall6e9f8f62009-12-03 04:06:58 +00005388 AddSurrogateCandidate(Conv, ActingContext, Proto,
5389 Object->getType(), Args, NumArgs,
5390 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005391 }
Mike Stump11289f42009-09-09 15:08:12 +00005392
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005393 // Perform overload resolution.
5394 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005395 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005396 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005397 // Overload resolution succeeded; we'll build the appropriate call
5398 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005399 break;
5400
5401 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005402 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00005403 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00005404 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00005405 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005406 break;
5407
5408 case OR_Ambiguous:
5409 Diag(Object->getSourceRange().getBegin(),
5410 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005411 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005412 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5413 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005414
5415 case OR_Deleted:
5416 Diag(Object->getSourceRange().getBegin(),
5417 diag::err_ovl_deleted_object_call)
5418 << Best->Function->isDeleted()
5419 << Object->getType() << Object->getSourceRange();
5420 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5421 break;
Mike Stump11289f42009-09-09 15:08:12 +00005422 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005423
Douglas Gregorab7897a2008-11-19 22:57:39 +00005424 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005425 // We had an error; delete all of the subexpressions and return
5426 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005427 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005428 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005429 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005430 return true;
5431 }
5432
Douglas Gregorab7897a2008-11-19 22:57:39 +00005433 if (Best->Function == 0) {
5434 // Since there is no function declaration, this is one of the
5435 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00005436 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00005437 = cast<CXXConversionDecl>(
5438 Best->Conversions[0].UserDefined.ConversionFunction);
5439
5440 // We selected one of the surrogate functions that converts the
5441 // object parameter to a function pointer. Perform the conversion
5442 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005443
5444 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005445 // and then call it.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005446 CXXMemberCallExpr *CE =
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005447 BuildCXXMemberCallExpr(Object, Conv);
5448
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005449 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005450 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5451 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005452 }
5453
5454 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5455 // that calls this method, using Object for the implicit object
5456 // parameter and passing along the remaining arguments.
5457 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00005458 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005459
5460 unsigned NumArgsInProto = Proto->getNumArgs();
5461 unsigned NumArgsToCheck = NumArgs;
5462
5463 // Build the full argument list for the method call (the
5464 // implicit object parameter is placed at the beginning of the
5465 // list).
5466 Expr **MethodArgs;
5467 if (NumArgs < NumArgsInProto) {
5468 NumArgsToCheck = NumArgsInProto;
5469 MethodArgs = new Expr*[NumArgsInProto + 1];
5470 } else {
5471 MethodArgs = new Expr*[NumArgs + 1];
5472 }
5473 MethodArgs[0] = Object;
5474 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5475 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00005476
5477 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00005478 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005479 UsualUnaryConversions(NewFn);
5480
5481 // Once we've built TheCall, all of the expressions are properly
5482 // owned.
5483 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005484 ExprOwningPtr<CXXOperatorCallExpr>
5485 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005486 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005487 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005488 delete [] MethodArgs;
5489
Anders Carlsson3d5829c2009-10-13 21:49:31 +00005490 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5491 Method))
5492 return true;
5493
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005494 // We may have default arguments. If so, we need to allocate more
5495 // slots in the call for them.
5496 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005497 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005498 else if (NumArgs > NumArgsInProto)
5499 NumArgsToCheck = NumArgsInProto;
5500
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005501 bool IsError = false;
5502
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005503 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005504 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005505 TheCall->setArg(0, Object);
5506
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005507
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005508 // Check the argument types.
5509 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005510 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005511 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005512 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00005513
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005514 // Pass the argument.
5515 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005516 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005517 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00005518 OwningExprResult DefArg
5519 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5520 if (DefArg.isInvalid()) {
5521 IsError = true;
5522 break;
5523 }
5524
5525 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005526 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005527
5528 TheCall->setArg(i + 1, Arg);
5529 }
5530
5531 // If this is a variadic call, handle args passed through "...".
5532 if (Proto->isVariadic()) {
5533 // Promote the arguments (C99 6.5.2.2p7).
5534 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5535 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005536 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005537 TheCall->setArg(i + 1, Arg);
5538 }
5539 }
5540
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005541 if (IsError) return true;
5542
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005543 if (CheckFunctionCall(Method, TheCall.get()))
5544 return true;
5545
Anders Carlsson1c83deb2009-08-16 03:53:54 +00005546 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005547}
5548
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005549/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00005550/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005551/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00005552Sema::OwningExprResult
5553Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5554 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005555 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00005556
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005557 // C++ [over.ref]p1:
5558 //
5559 // [...] An expression x->m is interpreted as (x.operator->())->m
5560 // for a class object x of type T if T::operator->() exists and if
5561 // the operator is selected as the best match function by the
5562 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005563 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5564 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005565 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00005566
Eli Friedman132e70b2009-11-18 01:28:03 +00005567 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5568 PDiag(diag::err_typecheck_incomplete_tag)
5569 << Base->getSourceRange()))
5570 return ExprError();
5571
John McCall27b18f82009-11-17 02:14:36 +00005572 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5573 LookupQualifiedName(R, BaseRecord->getDecl());
5574 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00005575
5576 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00005577 Oper != OperEnd; ++Oper) {
5578 NamedDecl *D = *Oper;
5579 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5580 if (isa<UsingShadowDecl>(D))
5581 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5582
5583 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
5584 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005585 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00005586 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005587
5588 // Perform overload resolution.
5589 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005590 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005591 case OR_Success:
5592 // Overload resolution succeeded; we'll build the call below.
5593 break;
5594
5595 case OR_No_Viable_Function:
5596 if (CandidateSet.empty())
5597 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00005598 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005599 else
5600 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00005601 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005602 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00005603 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005604
5605 case OR_Ambiguous:
5606 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005607 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005608 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005609 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005610
5611 case OR_Deleted:
5612 Diag(OpLoc, diag::err_ovl_deleted_oper)
5613 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005614 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005615 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005616 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005617 }
5618
5619 // Convert the object parameter.
5620 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005621 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005622 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005623
5624 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005625 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005626
5627 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005628 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5629 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005630 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005631
5632 QualType ResultTy = Method->getResultType().getNonReferenceType();
5633 ExprOwningPtr<CXXOperatorCallExpr>
5634 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5635 &Base, 1, ResultTy, OpLoc));
5636
5637 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5638 Method))
5639 return ExprError();
5640 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005641}
5642
Douglas Gregorcd695e52008-11-10 20:40:00 +00005643/// FixOverloadedFunctionReference - E is an expression that refers to
5644/// a C++ overloaded function (possibly with some parentheses and
5645/// perhaps a '&' around it). We have resolved the overloaded function
5646/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005647/// refer (possibly indirectly) to Fn. Returns the new expr.
5648Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005649 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00005650 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5651 if (SubExpr == PE->getSubExpr())
5652 return PE->Retain();
5653
5654 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
5655 }
5656
5657 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5658 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00005659 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00005660 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00005661 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00005662 if (SubExpr == ICE->getSubExpr())
5663 return ICE->Retain();
5664
5665 return new (Context) ImplicitCastExpr(ICE->getType(),
5666 ICE->getCastKind(),
5667 SubExpr,
5668 ICE->isLvalueCast());
5669 }
5670
5671 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005672 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005673 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005674 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5675 if (Method->isStatic()) {
5676 // Do nothing: static member functions aren't any different
5677 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00005678 } else {
John McCalle66edc12009-11-24 19:00:30 +00005679 // Fix the sub expression, which really has to be an
5680 // UnresolvedLookupExpr holding an overloaded member function
5681 // or template.
John McCalld14a8642009-11-21 08:51:07 +00005682 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5683 if (SubExpr == UnOp->getSubExpr())
5684 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00005685
John McCalld14a8642009-11-21 08:51:07 +00005686 assert(isa<DeclRefExpr>(SubExpr)
5687 && "fixed to something other than a decl ref");
5688 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
5689 && "fixed to a member ref with no nested name qualifier");
5690
5691 // We have taken the address of a pointer to member
5692 // function. Perform the computation here so that we get the
5693 // appropriate pointer to member type.
5694 QualType ClassType
5695 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5696 QualType MemPtrType
5697 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
5698
5699 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5700 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005701 }
5702 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00005703 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5704 if (SubExpr == UnOp->getSubExpr())
5705 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005706
Douglas Gregor51c538b2009-11-20 19:42:02 +00005707 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5708 Context.getPointerType(SubExpr->getType()),
5709 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00005710 }
John McCalld14a8642009-11-21 08:51:07 +00005711
5712 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00005713 // FIXME: avoid copy.
5714 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00005715 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00005716 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
5717 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00005718 }
5719
John McCalld14a8642009-11-21 08:51:07 +00005720 return DeclRefExpr::Create(Context,
5721 ULE->getQualifier(),
5722 ULE->getQualifierRange(),
5723 Fn,
5724 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00005725 Fn->getType(),
5726 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00005727 }
5728
John McCall10eae182009-11-30 22:42:35 +00005729 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00005730 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00005731 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5732 if (MemExpr->hasExplicitTemplateArgs()) {
5733 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5734 TemplateArgs = &TemplateArgsBuffer;
5735 }
John McCall6b51f282009-11-23 01:53:49 +00005736
John McCall2d74de92009-12-01 22:10:20 +00005737 Expr *Base;
5738
5739 // If we're filling in
5740 if (MemExpr->isImplicitAccess()) {
5741 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
5742 return DeclRefExpr::Create(Context,
5743 MemExpr->getQualifier(),
5744 MemExpr->getQualifierRange(),
5745 Fn,
5746 MemExpr->getMemberLoc(),
5747 Fn->getType(),
5748 TemplateArgs);
5749 } else
5750 Base = new (Context) CXXThisExpr(SourceLocation(),
5751 MemExpr->getBaseType());
5752 } else
5753 Base = MemExpr->getBase()->Retain();
5754
5755 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00005756 MemExpr->isArrow(),
5757 MemExpr->getQualifier(),
5758 MemExpr->getQualifierRange(),
5759 Fn,
John McCall6b51f282009-11-23 01:53:49 +00005760 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00005761 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00005762 Fn->getType());
5763 }
5764
Douglas Gregor51c538b2009-11-20 19:42:02 +00005765 assert(false && "Invalid reference to overloaded function");
5766 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00005767}
5768
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005769} // end namespace clang