blob: 53e64dfc68521dc7eca37df019db18c68fec633d [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"
15#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000016#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000023#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000025#include "llvm/Support/Compiler.h"
26#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,
41 ICC_Qualification_Adjustment,
42 ICC_Promotion,
43 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000044 ICC_Promotion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000047 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000052 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000053 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000054 ICC_Conversion
55 };
56 return Category[(int)Kind];
57}
58
59/// GetConversionRank - Retrieve the implicit conversion rank
60/// corresponding to the given implicit conversion kind.
61ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
62 static const ImplicitConversionRank
63 Rank[(int)ICK_Num_Conversion_Kinds] = {
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Promotion,
70 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000071 ICR_Promotion,
72 ICR_Conversion,
73 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000074 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000079 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000080 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000081 ICR_Conversion
82 };
83 return Rank[(int)Kind];
84}
85
86/// GetImplicitConversionName - Return the name of this kind of
87/// implicit conversion.
88const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
89 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
90 "No conversion",
91 "Lvalue-to-rvalue",
92 "Array-to-pointer",
93 "Function-to-pointer",
94 "Qualification",
95 "Integral promotion",
96 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +000097 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000098 "Integral conversion",
99 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000102 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000103 "Pointer conversion",
104 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000105 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000106 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000107 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 };
109 return Name[Kind];
110}
111
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000112/// StandardConversionSequence - Set the standard conversion
113/// sequence to the identity conversion.
114void StandardConversionSequence::setAsIdentityConversion() {
115 First = ICK_Identity;
116 Second = ICK_Identity;
117 Third = ICK_Identity;
118 Deprecated = false;
119 ReferenceBinding = false;
120 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000121 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000122 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000123}
124
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000125/// getRank - Retrieve the rank of this standard conversion sequence
126/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
127/// implicit conversions.
128ImplicitConversionRank StandardConversionSequence::getRank() const {
129 ImplicitConversionRank Rank = ICR_Exact_Match;
130 if (GetConversionRank(First) > Rank)
131 Rank = GetConversionRank(First);
132 if (GetConversionRank(Second) > Rank)
133 Rank = GetConversionRank(Second);
134 if (GetConversionRank(Third) > Rank)
135 Rank = GetConversionRank(Third);
136 return Rank;
137}
138
139/// isPointerConversionToBool - Determines whether this conversion is
140/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000141/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000142/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000143bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000144 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
145 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
146
147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
151 if (ToType->isBooleanType() &&
Douglas Gregor033f56d2008-12-23 00:53:59 +0000152 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregor5c407d92008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000163bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregor5c407d92008-10-23 00:40:37 +0000166 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
175 if (Second == ICK_Pointer_Conversion)
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
185 bool PrintedSomething = false;
186 if (First != ICK_Identity) {
187 fprintf(stderr, "%s", GetImplicitConversionName(First));
188 PrintedSomething = true;
189 }
190
191 if (Second != ICK_Identity) {
192 if (PrintedSomething) {
193 fprintf(stderr, " -> ");
194 }
195 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor2fe98832008-11-03 19:09:14 +0000196
197 if (CopyConstructor) {
198 fprintf(stderr, " (by copy constructor)");
199 } else if (DirectBinding) {
200 fprintf(stderr, " (direct reference binding)");
201 } else if (ReferenceBinding) {
202 fprintf(stderr, " (reference binding)");
203 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000204 PrintedSomething = true;
205 }
206
207 if (Third != ICK_Identity) {
208 if (PrintedSomething) {
209 fprintf(stderr, " -> ");
210 }
211 fprintf(stderr, "%s", GetImplicitConversionName(Third));
212 PrintedSomething = true;
213 }
214
215 if (!PrintedSomething) {
216 fprintf(stderr, "No conversions required");
217 }
218}
219
220/// DebugPrint - Print this user-defined conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void UserDefinedConversionSequence::DebugPrint() const {
223 if (Before.First || Before.Second || Before.Third) {
224 Before.DebugPrint();
225 fprintf(stderr, " -> ");
226 }
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 if (After.First || After.Second || After.Third) {
229 fprintf(stderr, " -> ");
230 After.DebugPrint();
231 }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237 switch (ConversionKind) {
238 case StandardConversion:
239 fprintf(stderr, "Standard conversion: ");
240 Standard.DebugPrint();
241 break;
242 case UserDefinedConversion:
243 fprintf(stderr, "User-defined conversion: ");
244 UserDefined.DebugPrint();
245 break;
246 case EllipsisConversion:
247 fprintf(stderr, "Ellipsis conversion");
248 break;
249 case BadConversion:
250 fprintf(stderr, "Bad conversion");
251 break;
252 }
253
254 fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
Mike Stump11289f42009-09-09 15:08:12 +0000263// FunctionDecl that New cannot be overloaded with.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000264//
265// Example: Given the following input:
266//
267// void f(int, float); // #1
268// void f(int, int); // #2
269// int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000272// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000273//
274// When we process #2, Old is a FunctionDecl for #1. By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
Mike Stump11289f42009-09-09 15:08:12 +0000286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000288 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
289 // Is this new function an overload of every function in the
290 // overload set?
291 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
292 FuncEnd = Ovl->function_end();
293 for (; Func != FuncEnd; ++Func) {
294 if (!IsOverload(New, *Func, MatchedDecl)) {
295 MatchedDecl = Func;
296 return false;
297 }
298 }
299
300 // This function overloads every function in the overload set.
301 return true;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000302 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
303 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
304 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregor23061de2009-06-24 16:50:40 +0000305 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
Mike Stump11289f42009-09-09 15:08:12 +0000306 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
307
Douglas Gregor23061de2009-06-24 16:50:40 +0000308 // C++ [temp.fct]p2:
309 // A function template can be overloaded with other function templates
310 // and with normal (non-template) functions.
311 if ((OldTemplate == 0) != (NewTemplate == 0))
312 return true;
313
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000314 // Is the function New an overload of the function Old?
315 QualType OldQType = Context.getCanonicalType(Old->getType());
316 QualType NewQType = Context.getCanonicalType(New->getType());
317
318 // Compare the signatures (C++ 1.3.10) of the two functions to
319 // determine whether they are overloads. If we find any mismatch
320 // in the signature, they are overloads.
321
322 // If either of these functions is a K&R-style function (no
323 // prototype), then we consider them to have matching signatures.
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000324 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
325 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000326 return false;
327
Douglas Gregor23061de2009-06-24 16:50:40 +0000328 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
329 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000330
331 // The signature of a function includes the types of its
332 // parameters (C++ 1.3.10), which includes the presence or absence
333 // of the ellipsis; see C++ DR 357).
334 if (OldQType != NewQType &&
335 (OldType->getNumArgs() != NewType->getNumArgs() ||
336 OldType->isVariadic() != NewType->isVariadic() ||
337 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
338 NewType->arg_type_begin())))
339 return true;
340
Douglas Gregor23061de2009-06-24 16:50:40 +0000341 // C++ [temp.over.link]p4:
Mike Stump11289f42009-09-09 15:08:12 +0000342 // The signature of a function template consists of its function
Douglas Gregor23061de2009-06-24 16:50:40 +0000343 // signature, its return type and its template parameter list. The names
344 // of the template parameters are significant only for establishing the
Mike Stump11289f42009-09-09 15:08:12 +0000345 // relationship between the template parameters and the rest of the
Douglas Gregor23061de2009-06-24 16:50:40 +0000346 // signature.
347 //
348 // We check the return type and template parameter lists for function
349 // templates first; the remaining checks follow.
350 if (NewTemplate &&
Mike Stump11289f42009-09-09 15:08:12 +0000351 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
352 OldTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000353 false, TPL_TemplateMatch) ||
Douglas Gregor23061de2009-06-24 16:50:40 +0000354 OldType->getResultType() != NewType->getResultType()))
355 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000356
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000357 // If the function is a class member, its signature includes the
358 // cv-qualifiers (if any) on the function itself.
359 //
360 // As part of this, also check whether one of the member functions
361 // is static, in which case they are not overloads (C++
362 // 13.1p2). While not part of the definition of the signature,
363 // this check is important to determine whether these functions
364 // can be overloaded.
365 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
366 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Mike Stump11289f42009-09-09 15:08:12 +0000367 if (OldMethod && NewMethod &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000368 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb81897c2008-11-21 15:36:28 +0000369 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000370 return true;
371
372 // The signatures match; this is not an overload.
373 return false;
374 } else {
375 // (C++ 13p1):
376 // Only function declarations can be overloaded; object and type
377 // declarations cannot be overloaded.
378 return false;
379 }
380}
381
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000382/// TryImplicitConversion - Attempt to perform an implicit conversion
383/// from the given expression (Expr) to the given type (ToType). This
384/// function returns an implicit conversion sequence that can be used
385/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000386///
387/// void f(float f);
388/// void g(int i) { f(i); }
389///
390/// this routine would produce an implicit conversion sequence to
391/// describe the initialization of f from i, which will be a standard
392/// conversion sequence containing an lvalue-to-rvalue conversion (C++
393/// 4.1) followed by a floating-integral conversion (C++ 4.9).
394//
395/// Note that this routine only determines how the conversion can be
396/// performed; it does not actually perform the conversion. As such,
397/// it will not produce any diagnostics if no conversion is available,
398/// but will instead return an implicit conversion sequence of kind
399/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000400///
401/// If @p SuppressUserConversions, then user-defined conversions are
402/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000403/// If @p AllowExplicit, then explicit user-defined conversions are
404/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000405/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
406/// no matter its actual lvalueness.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000407/// If @p UserCast, the implicit conversion is being done for a user-specified
408/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000409ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000410Sema::TryImplicitConversion(Expr* From, QualType ToType,
411 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000412 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000413 bool InOverloadResolution,
414 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000415 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000416 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000417 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000418 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000419 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000420 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000421 (UserDefResult = IsUserDefinedConversion(From, ToType,
422 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000423 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000424 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000425 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000426 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000427 // C++ [over.ics.user]p4:
428 // A conversion of an expression of class type to the same class
429 // type is given Exact Match rank, and a conversion of an
430 // expression of class type to a base class of that type is
431 // given Conversion rank, in spite of the fact that a copy
432 // constructor (i.e., a user-defined conversion function) is
433 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000434 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000435 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000436 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000437 = Context.getCanonicalType(From->getType().getUnqualifiedType());
438 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
439 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000440 // Turn this into a "standard" conversion sequence, so that it
441 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000442 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
443 ICS.Standard.setAsIdentityConversion();
444 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
445 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000446 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000447 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000448 ICS.Standard.Second = ICK_Derived_To_Base;
449 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000450 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000451
452 // C++ [over.best.ics]p4:
453 // However, when considering the argument of a user-defined
454 // conversion function that is a candidate by 13.3.1.3 when
455 // invoked for the copying of the temporary in the second step
456 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
457 // 13.3.1.6 in all cases, only standard conversion sequences and
458 // ellipsis conversion sequences are allowed.
459 if (SuppressUserConversions &&
460 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
461 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000462 } else {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000463 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000464 if (UserDefResult == OR_Ambiguous) {
465 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
466 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian574de2c2009-10-12 17:51:19 +0000467 if (Cand->Viable)
468 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000469 }
470 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000471
472 return ICS;
473}
474
475/// IsStandardConversion - Determines whether there is a standard
476/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
477/// expression From to the type ToType. Standard conversion sequences
478/// only consider non-class types; for conversions that involve class
479/// types, use TryImplicitConversion. If a conversion exists, SCS will
480/// contain the standard conversion sequence required to perform this
481/// conversion and this routine will return true. Otherwise, this
482/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000483bool
484Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000485 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000486 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000487 QualType FromType = From->getType();
488
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000489 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000490 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000491 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000492 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000493 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000494 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000495
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000496 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000497 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000498 if (FromType->isRecordType() || ToType->isRecordType()) {
499 if (getLangOptions().CPlusPlus)
500 return false;
501
Mike Stump11289f42009-09-09 15:08:12 +0000502 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000503 }
504
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 // The first conversion can be an lvalue-to-rvalue conversion,
506 // array-to-pointer conversion, or function-to-pointer conversion
507 // (C++ 4p1).
508
Mike Stump11289f42009-09-09 15:08:12 +0000509 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000510 // An lvalue (3.10) of a non-function, non-array type T can be
511 // converted to an rvalue.
512 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000513 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000514 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000515 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000516 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000517
518 // If T is a non-class type, the type of the rvalue is the
519 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000520 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
521 // just strip the qualifiers because they don't matter.
522
523 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000524 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000525 } else if (FromType->isArrayType()) {
526 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000527 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528
529 // An lvalue or rvalue of type "array of N T" or "array of unknown
530 // bound of T" can be converted to an rvalue of type "pointer to
531 // T" (C++ 4.2p1).
532 FromType = Context.getArrayDecayedType(FromType);
533
534 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
535 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000536 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000537
538 // For the purpose of ranking in overload resolution
539 // (13.3.3.1.1), this conversion is considered an
540 // array-to-pointer conversion followed by a qualification
541 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000542 SCS.Second = ICK_Identity;
543 SCS.Third = ICK_Qualification;
544 SCS.ToTypePtr = ToType.getAsOpaquePtr();
545 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000546 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000547 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
548 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000549 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000550
551 // An lvalue of function type T can be converted to an rvalue of
552 // type "pointer to T." The result is a pointer to the
553 // function. (C++ 4.3p1).
554 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000555 } else if (FunctionDecl *Fn
Douglas Gregorcd695e52008-11-10 20:40:00 +0000556 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000557 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000558 SCS.First = ICK_Function_To_Pointer;
559
560 // We were able to resolve the address of the overloaded function,
561 // so we can convert to the type of that function.
562 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000563 if (ToType->isLValueReferenceType())
564 FromType = Context.getLValueReferenceType(FromType);
565 else if (ToType->isRValueReferenceType())
566 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000567 else if (ToType->isMemberPointerType()) {
568 // Resolve address only succeeds if both sides are member pointers,
569 // but it doesn't have to be the same class. See DR 247.
570 // Note that this means that the type of &Derived::fn can be
571 // Ret (Base::*)(Args) if the fn overload actually found is from the
572 // base class, even if it was brought into the derived class via a
573 // using declaration. The standard isn't clear on this issue at all.
574 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
575 FromType = Context.getMemberPointerType(FromType,
576 Context.getTypeDeclType(M->getParent()).getTypePtr());
577 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000578 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000579 } else {
580 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000581 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000582 }
583
584 // The second conversion can be an integral promotion, floating
585 // point promotion, integral conversion, floating point conversion,
586 // floating-integral conversion, pointer conversion,
587 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000588 // For overloading in C, this can also be a "compatible-type"
589 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000590 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000591 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000592 // The unqualified versions of the types are the same: there's no
593 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000594 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000595 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000596 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000597 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000598 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000599 } else if (IsFloatingPointPromotion(FromType, ToType)) {
600 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000601 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000602 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000603 } else if (IsComplexPromotion(FromType, ToType)) {
604 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000605 SCS.Second = ICK_Complex_Promotion;
606 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000607 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000608 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000609 // Integral conversions (C++ 4.7).
610 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000611 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000612 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000613 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
614 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000615 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000616 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000617 } else if (FromType->isComplexType() && ToType->isComplexType()) {
618 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000619 SCS.Second = ICK_Complex_Conversion;
620 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000621 } else if ((FromType->isFloatingType() &&
622 ToType->isIntegralType() && (!ToType->isBooleanType() &&
623 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000624 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000625 ToType->isFloatingType())) {
626 // Floating-integral conversions (C++ 4.9).
627 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000628 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000629 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000630 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
631 (ToType->isComplexType() && FromType->isArithmeticType())) {
632 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000633 SCS.Second = ICK_Complex_Real;
634 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000635 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
636 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000637 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000638 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000639 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000640 } else if (IsMemberPointerConversion(From, FromType, ToType,
641 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000642 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000643 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000644 } else if (ToType->isBooleanType() &&
645 (FromType->isArithmeticType() ||
646 FromType->isEnumeralType() ||
647 FromType->isPointerType() ||
648 FromType->isBlockPointerType() ||
649 FromType->isMemberPointerType() ||
650 FromType->isNullPtrType())) {
651 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000652 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000653 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000654 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000655 Context.typesAreCompatible(ToType, FromType)) {
656 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000657 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000658 } else {
659 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000660 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000661 }
662
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000663 QualType CanonFrom;
664 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000665 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000666 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000667 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000668 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000669 CanonFrom = Context.getCanonicalType(FromType);
670 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000671 } else {
672 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000673 SCS.Third = ICK_Identity;
674
Mike Stump11289f42009-09-09 15:08:12 +0000675 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000676 // [...] Any difference in top-level cv-qualification is
677 // subsumed by the initialization itself and does not constitute
678 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000679 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000680 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000681 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000682 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
683 FromType = ToType;
684 CanonFrom = CanonTo;
685 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000686 }
687
688 // If we have not converted the argument type to the parameter type,
689 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000690 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000691 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000692
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000693 SCS.ToTypePtr = FromType.getAsOpaquePtr();
694 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000695}
696
697/// IsIntegralPromotion - Determines whether the conversion from the
698/// expression From (whose potentially-adjusted type is FromType) to
699/// ToType is an integral promotion (C++ 4.5). If so, returns true and
700/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000701bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000702 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000703 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000704 if (!To) {
705 return false;
706 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000707
708 // An rvalue of type char, signed char, unsigned char, short int, or
709 // unsigned short int can be converted to an rvalue of type int if
710 // int can represent all the values of the source type; otherwise,
711 // the source rvalue can be converted to an rvalue of type unsigned
712 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000713 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000714 if (// We can promote any signed, promotable integer type to an int
715 (FromType->isSignedIntegerType() ||
716 // We can promote any unsigned integer type whose size is
717 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000718 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000719 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000720 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000721 }
722
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000723 return To->getKind() == BuiltinType::UInt;
724 }
725
726 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
727 // can be converted to an rvalue of the first of the following types
728 // that can represent all the values of its underlying type: int,
729 // unsigned int, long, or unsigned long (C++ 4.5p2).
730 if ((FromType->isEnumeralType() || FromType->isWideCharType())
731 && ToType->isIntegerType()) {
732 // Determine whether the type we're converting from is signed or
733 // unsigned.
734 bool FromIsSigned;
735 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall9dd450b2009-09-21 23:43:11 +0000736 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000737 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
738 FromIsSigned = UnderlyingType->isSignedIntegerType();
739 } else {
740 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
741 FromIsSigned = true;
742 }
743
744 // The types we'll try to promote to, in the appropriate
745 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000746 QualType PromoteTypes[6] = {
747 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000748 Context.LongTy, Context.UnsignedLongTy ,
749 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000750 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000751 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000752 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
753 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000754 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000755 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
756 // We found the type that we can promote to. If this is the
757 // type we wanted, we have a promotion. Otherwise, no
758 // promotion.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000759 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000760 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
761 }
762 }
763 }
764
765 // An rvalue for an integral bit-field (9.6) can be converted to an
766 // rvalue of type int if int can represent all the values of the
767 // bit-field; otherwise, it can be converted to unsigned int if
768 // unsigned int can represent all the values of the bit-field. If
769 // the bit-field is larger yet, no integral promotion applies to
770 // it. If the bit-field has an enumerated type, it is treated as any
771 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000772 // FIXME: We should delay checking of bit-fields until we actually perform the
773 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000774 using llvm::APSInt;
775 if (From)
776 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000777 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000778 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
779 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
780 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
781 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000782
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000783 // Are we promoting to an int from a bitfield that fits in an int?
784 if (BitWidth < ToSize ||
785 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
786 return To->getKind() == BuiltinType::Int;
787 }
Mike Stump11289f42009-09-09 15:08:12 +0000788
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000789 // Are we promoting to an unsigned int from an unsigned bitfield
790 // that fits into an unsigned int?
791 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
792 return To->getKind() == BuiltinType::UInt;
793 }
Mike Stump11289f42009-09-09 15:08:12 +0000794
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000795 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000796 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000797 }
Mike Stump11289f42009-09-09 15:08:12 +0000798
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000799 // An rvalue of type bool can be converted to an rvalue of type int,
800 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000801 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000802 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000803 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000804
805 return false;
806}
807
808/// IsFloatingPointPromotion - Determines whether the conversion from
809/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
810/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000811bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000812 /// An rvalue of type float can be converted to an rvalue of type
813 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000814 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
815 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816 if (FromBuiltin->getKind() == BuiltinType::Float &&
817 ToBuiltin->getKind() == BuiltinType::Double)
818 return true;
819
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000820 // C99 6.3.1.5p1:
821 // When a float is promoted to double or long double, or a
822 // double is promoted to long double [...].
823 if (!getLangOptions().CPlusPlus &&
824 (FromBuiltin->getKind() == BuiltinType::Float ||
825 FromBuiltin->getKind() == BuiltinType::Double) &&
826 (ToBuiltin->getKind() == BuiltinType::LongDouble))
827 return true;
828 }
829
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000830 return false;
831}
832
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000833/// \brief Determine if a conversion is a complex promotion.
834///
835/// A complex promotion is defined as a complex -> complex conversion
836/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000837/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000838bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000839 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000840 if (!FromComplex)
841 return false;
842
John McCall9dd450b2009-09-21 23:43:11 +0000843 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000844 if (!ToComplex)
845 return false;
846
847 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000848 ToComplex->getElementType()) ||
849 IsIntegralPromotion(0, FromComplex->getElementType(),
850 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000851}
852
Douglas Gregor237f96c2008-11-26 23:31:11 +0000853/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
854/// the pointer type FromPtr to a pointer to type ToPointee, with the
855/// same type qualifiers as FromPtr has on its pointee type. ToType,
856/// if non-empty, will be a pointer to ToType that may or may not have
857/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000858static QualType
859BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000860 QualType ToPointee, QualType ToType,
861 ASTContext &Context) {
862 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
863 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000864 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000865
866 // Exact qualifier match -> return the pointer type we're converting to.
John McCall8ccfcb52009-09-24 19:53:00 +0000867 if (CanonToPointee.getQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000868 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000869 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000870 return ToType;
871
872 // Build a pointer to ToPointee. It has the right qualifiers
873 // already.
874 return Context.getPointerType(ToPointee);
875 }
876
877 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000878 return Context.getPointerType(
879 Context.getQualifiedType(CanonToPointee.getUnqualifiedType(), Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000880}
881
Mike Stump11289f42009-09-09 15:08:12 +0000882static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000883 bool InOverloadResolution,
884 ASTContext &Context) {
885 // Handle value-dependent integral null pointer constants correctly.
886 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
887 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
888 Expr->getType()->isIntegralType())
889 return !InOverloadResolution;
890
Douglas Gregor56751b52009-09-25 04:25:58 +0000891 return Expr->isNullPointerConstant(Context,
892 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
893 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000894}
Mike Stump11289f42009-09-09 15:08:12 +0000895
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000896/// IsPointerConversion - Determines whether the conversion of the
897/// expression From, which has the (possibly adjusted) type FromType,
898/// can be converted to the type ToType via a pointer conversion (C++
899/// 4.10). If so, returns true and places the converted type (that
900/// might differ from ToType in its cv-qualifiers at some level) into
901/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000902///
Douglas Gregora29dc052008-11-27 01:19:21 +0000903/// This routine also supports conversions to and from block pointers
904/// and conversions with Objective-C's 'id', 'id<protocols...>', and
905/// pointers to interfaces. FIXME: Once we've determined the
906/// appropriate overloading rules for Objective-C, we may want to
907/// split the Objective-C checks into a different routine; however,
908/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000909/// conversions, so for now they live here. IncompatibleObjC will be
910/// set if the conversion is an allowed Objective-C conversion that
911/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000912bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000913 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000914 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000915 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000916 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000917 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
918 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000919
Mike Stump11289f42009-09-09 15:08:12 +0000920 // Conversion from a null pointer constant to any Objective-C pointer type.
921 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000922 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000923 ConvertedType = ToType;
924 return true;
925 }
926
Douglas Gregor231d1c62008-11-27 00:15:41 +0000927 // Blocks: Block pointers can be converted to void*.
928 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000929 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000930 ConvertedType = ToType;
931 return true;
932 }
933 // Blocks: A null pointer constant can be converted to a block
934 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000935 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000936 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000937 ConvertedType = ToType;
938 return true;
939 }
940
Sebastian Redl576fd422009-05-10 18:38:11 +0000941 // If the left-hand-side is nullptr_t, the right side can be a null
942 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000943 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000944 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000945 ConvertedType = ToType;
946 return true;
947 }
948
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000949 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000950 if (!ToTypePtr)
951 return false;
952
953 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000954 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000955 ConvertedType = ToType;
956 return true;
957 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000958
Douglas Gregor237f96c2008-11-26 23:31:11 +0000959 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000960 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000961 if (!FromTypePtr)
962 return false;
963
964 QualType FromPointeeType = FromTypePtr->getPointeeType();
965 QualType ToPointeeType = ToTypePtr->getPointeeType();
966
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000967 // An rvalue of type "pointer to cv T," where T is an object type,
968 // can be converted to an rvalue of type "pointer to cv void" (C++
969 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000970 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000971 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000972 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000973 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000974 return true;
975 }
976
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000977 // When we're overloading in C, we allow a special kind of pointer
978 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +0000979 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000980 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000981 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000982 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +0000983 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000984 return true;
985 }
986
Douglas Gregor5c407d92008-10-23 00:40:37 +0000987 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +0000988 //
Douglas Gregor5c407d92008-10-23 00:40:37 +0000989 // An rvalue of type "pointer to cv D," where D is a class type,
990 // can be converted to an rvalue of type "pointer to cv B," where
991 // B is a base class (clause 10) of D. If B is an inaccessible
992 // (clause 11) or ambiguous (10.2) base class of D, a program that
993 // necessitates this conversion is ill-formed. The result of the
994 // conversion is a pointer to the base class sub-object of the
995 // derived class object. The null pointer value is converted to
996 // the null pointer value of the destination type.
997 //
Douglas Gregor39c16d42008-10-24 04:54:22 +0000998 // Note that we do not check for ambiguity or inaccessibility
999 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001000 if (getLangOptions().CPlusPlus &&
1001 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001002 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001003 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001004 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001005 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001006 ToType, Context);
1007 return true;
1008 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001009
Douglas Gregora119f102008-12-19 19:13:09 +00001010 return false;
1011}
1012
1013/// isObjCPointerConversion - Determines whether this is an
1014/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1015/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001016bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001017 QualType& ConvertedType,
1018 bool &IncompatibleObjC) {
1019 if (!getLangOptions().ObjC1)
1020 return false;
1021
Steve Naroff7cae42b2009-07-10 23:34:53 +00001022 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001023 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001024 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001025 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001026
Steve Naroff7cae42b2009-07-10 23:34:53 +00001027 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001028 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001029 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001030 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001031 ConvertedType = ToType;
1032 return true;
1033 }
1034 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001035 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001036 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001037 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001038 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001039 ConvertedType = ToType;
1040 return true;
1041 }
1042 // Objective C++: We're able to convert from a pointer to an
1043 // interface to a pointer to a different interface.
1044 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1045 ConvertedType = ToType;
1046 return true;
1047 }
1048
1049 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1050 // Okay: this is some kind of implicit downcast of Objective-C
1051 // interfaces, which is permitted. However, we're going to
1052 // complain about it.
1053 IncompatibleObjC = true;
1054 ConvertedType = FromType;
1055 return true;
1056 }
Mike Stump11289f42009-09-09 15:08:12 +00001057 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001058 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001059 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001060 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001061 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001062 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001063 ToPointeeType = ToBlockPtr->getPointeeType();
1064 else
Douglas Gregora119f102008-12-19 19:13:09 +00001065 return false;
1066
Douglas Gregor033f56d2008-12-23 00:53:59 +00001067 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001068 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001069 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001070 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001071 FromPointeeType = FromBlockPtr->getPointeeType();
1072 else
Douglas Gregora119f102008-12-19 19:13:09 +00001073 return false;
1074
Douglas Gregora119f102008-12-19 19:13:09 +00001075 // If we have pointers to pointers, recursively check whether this
1076 // is an Objective-C conversion.
1077 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1078 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1079 IncompatibleObjC)) {
1080 // We always complain about this conversion.
1081 IncompatibleObjC = true;
1082 ConvertedType = ToType;
1083 return true;
1084 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001085 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001086 // differences in the argument and result types are in Objective-C
1087 // pointer conversions. If so, we permit the conversion (but
1088 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001089 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001090 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001091 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001092 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001093 if (FromFunctionType && ToFunctionType) {
1094 // If the function types are exactly the same, this isn't an
1095 // Objective-C pointer conversion.
1096 if (Context.getCanonicalType(FromPointeeType)
1097 == Context.getCanonicalType(ToPointeeType))
1098 return false;
1099
1100 // Perform the quick checks that will tell us whether these
1101 // function types are obviously different.
1102 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1103 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1104 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1105 return false;
1106
1107 bool HasObjCConversion = false;
1108 if (Context.getCanonicalType(FromFunctionType->getResultType())
1109 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1110 // Okay, the types match exactly. Nothing to do.
1111 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1112 ToFunctionType->getResultType(),
1113 ConvertedType, IncompatibleObjC)) {
1114 // Okay, we have an Objective-C pointer conversion.
1115 HasObjCConversion = true;
1116 } else {
1117 // Function types are too different. Abort.
1118 return false;
1119 }
Mike Stump11289f42009-09-09 15:08:12 +00001120
Douglas Gregora119f102008-12-19 19:13:09 +00001121 // Check argument types.
1122 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1123 ArgIdx != NumArgs; ++ArgIdx) {
1124 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1125 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1126 if (Context.getCanonicalType(FromArgType)
1127 == Context.getCanonicalType(ToArgType)) {
1128 // Okay, the types match exactly. Nothing to do.
1129 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1130 ConvertedType, IncompatibleObjC)) {
1131 // Okay, we have an Objective-C pointer conversion.
1132 HasObjCConversion = true;
1133 } else {
1134 // Argument types are too different. Abort.
1135 return false;
1136 }
1137 }
1138
1139 if (HasObjCConversion) {
1140 // We had an Objective-C conversion. Allow this pointer
1141 // conversion, but complain about it.
1142 ConvertedType = ToType;
1143 IncompatibleObjC = true;
1144 return true;
1145 }
1146 }
1147
Sebastian Redl72b597d2009-01-25 19:43:20 +00001148 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001149}
1150
Douglas Gregor39c16d42008-10-24 04:54:22 +00001151/// CheckPointerConversion - Check the pointer conversion from the
1152/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001153/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001154/// conversions for which IsPointerConversion has already returned
1155/// true. It returns true and produces a diagnostic if there was an
1156/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001157bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1158 CastExpr::CastKind &Kind) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001159 QualType FromType = From->getType();
1160
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001161 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1162 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001163 QualType FromPointeeType = FromPtrType->getPointeeType(),
1164 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001165
Douglas Gregor39c16d42008-10-24 04:54:22 +00001166 if (FromPointeeType->isRecordType() &&
1167 ToPointeeType->isRecordType()) {
1168 // We must have a derived-to-base conversion. Check an
1169 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001170 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1171 From->getExprLoc(),
1172 From->getSourceRange()))
1173 return true;
1174
1175 // The conversion was successful.
1176 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001177 }
1178 }
Mike Stump11289f42009-09-09 15:08:12 +00001179 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001180 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001181 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001182 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001183 // Objective-C++ conversions are always okay.
1184 // FIXME: We should have a different class of conversions for the
1185 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001186 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001187 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001188
Steve Naroff7cae42b2009-07-10 23:34:53 +00001189 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001190 return false;
1191}
1192
Sebastian Redl72b597d2009-01-25 19:43:20 +00001193/// IsMemberPointerConversion - Determines whether the conversion of the
1194/// expression From, which has the (possibly adjusted) type FromType, can be
1195/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1196/// If so, returns true and places the converted type (that might differ from
1197/// ToType in its cv-qualifiers at some level) into ConvertedType.
1198bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001199 QualType ToType,
1200 bool InOverloadResolution,
1201 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001202 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001203 if (!ToTypePtr)
1204 return false;
1205
1206 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001207 if (From->isNullPointerConstant(Context,
1208 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1209 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001210 ConvertedType = ToType;
1211 return true;
1212 }
1213
1214 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001215 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001216 if (!FromTypePtr)
1217 return false;
1218
1219 // A pointer to member of B can be converted to a pointer to member of D,
1220 // where D is derived from B (C++ 4.11p2).
1221 QualType FromClass(FromTypePtr->getClass(), 0);
1222 QualType ToClass(ToTypePtr->getClass(), 0);
1223 // FIXME: What happens when these are dependent? Is this function even called?
1224
1225 if (IsDerivedFrom(ToClass, FromClass)) {
1226 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1227 ToClass.getTypePtr());
1228 return true;
1229 }
1230
1231 return false;
1232}
1233
1234/// CheckMemberPointerConversion - Check the member pointer conversion from the
1235/// expression From to the type ToType. This routine checks for ambiguous or
1236/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1237/// for which IsMemberPointerConversion has already returned true. It returns
1238/// true and produces a diagnostic if there was an error, or returns false
1239/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001240bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Anders Carlssond7923c62009-08-22 23:33:40 +00001241 CastExpr::CastKind &Kind) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001242 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001243 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001244 if (!FromPtrType) {
1245 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001246 assert(From->isNullPointerConstant(Context,
1247 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001248 "Expr must be null pointer constant!");
1249 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001250 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001251 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001252
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001253 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001254 assert(ToPtrType && "No member pointer cast has a target type "
1255 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001256
Sebastian Redled8f2002009-01-28 18:33:18 +00001257 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1258 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001259
Sebastian Redled8f2002009-01-28 18:33:18 +00001260 // FIXME: What about dependent types?
1261 assert(FromClass->isRecordType() && "Pointer into non-class.");
1262 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001263
Douglas Gregor36d1b142009-10-06 17:59:45 +00001264 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1265 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001266 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1267 assert(DerivationOkay &&
1268 "Should not have been called if derivation isn't OK.");
1269 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001270
Sebastian Redled8f2002009-01-28 18:33:18 +00001271 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1272 getUnqualifiedType())) {
1273 // Derivation is ambiguous. Redo the check to find the exact paths.
1274 Paths.clear();
1275 Paths.setRecordingPaths(true);
1276 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1277 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1278 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001279
Sebastian Redled8f2002009-01-28 18:33:18 +00001280 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1281 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1282 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1283 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001284 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001285
Douglas Gregor89ee6822009-02-28 01:32:25 +00001286 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001287 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1288 << FromClass << ToClass << QualType(VBase, 0)
1289 << From->getSourceRange();
1290 return true;
1291 }
1292
Anders Carlssond7923c62009-08-22 23:33:40 +00001293 // Must be a base to derived member conversion.
1294 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001295 return false;
1296}
1297
Douglas Gregor9a657932008-10-21 23:43:52 +00001298/// IsQualificationConversion - Determines whether the conversion from
1299/// an rvalue of type FromType to ToType is a qualification conversion
1300/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001301bool
1302Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001303 FromType = Context.getCanonicalType(FromType);
1304 ToType = Context.getCanonicalType(ToType);
1305
1306 // If FromType and ToType are the same type, this is not a
1307 // qualification conversion.
1308 if (FromType == ToType)
1309 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001310
Douglas Gregor9a657932008-10-21 23:43:52 +00001311 // (C++ 4.4p4):
1312 // A conversion can add cv-qualifiers at levels other than the first
1313 // in multi-level pointers, subject to the following rules: [...]
1314 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001315 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001316 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001317 // Within each iteration of the loop, we check the qualifiers to
1318 // determine if this still looks like a qualification
1319 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001320 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001321 // until there are no more pointers or pointers-to-members left to
1322 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001323 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001324
1325 // -- for every j > 0, if const is in cv 1,j then const is in cv
1326 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001327 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001328 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001329
Douglas Gregor9a657932008-10-21 23:43:52 +00001330 // -- if the cv 1,j and cv 2,j are different, then const is in
1331 // every cv for 0 < k < j.
1332 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001333 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001334 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001335
Douglas Gregor9a657932008-10-21 23:43:52 +00001336 // Keep track of whether all prior cv-qualifiers in the "to" type
1337 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001338 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001339 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001340 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001341
1342 // We are left with FromType and ToType being the pointee types
1343 // after unwrapping the original FromType and ToType the same number
1344 // of types. If we unwrapped any pointers, and if FromType and
1345 // ToType have the same unqualified type (since we checked
1346 // qualifiers above), then this is a qualification conversion.
1347 return UnwrappedAnyPointer &&
1348 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1349}
1350
Douglas Gregor05155d82009-08-21 23:19:43 +00001351/// \brief Given a function template or function, extract the function template
1352/// declaration (if any) and the underlying function declaration.
1353template<typename T>
1354static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1355 FunctionTemplateDecl *&FunctionTemplate) {
1356 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1357 if (FunctionTemplate)
1358 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1359 else
1360 Function = cast<T>(Orig);
1361}
1362
Douglas Gregor576e98c2009-01-30 23:27:23 +00001363/// Determines whether there is a user-defined conversion sequence
1364/// (C++ [over.ics.user]) that converts expression From to the type
1365/// ToType. If such a conversion exists, User will contain the
1366/// user-defined conversion sequence that performs such a conversion
1367/// and this routine will return true. Otherwise, this routine returns
1368/// false and User is unspecified.
1369///
1370/// \param AllowConversionFunctions true if the conversion should
1371/// consider conversion functions at all. If false, only constructors
1372/// will be considered.
1373///
1374/// \param AllowExplicit true if the conversion should consider C++0x
1375/// "explicit" conversion functions as well as non-explicit conversion
1376/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001377///
1378/// \param ForceRValue true if the expression should be treated as an rvalue
1379/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001380/// \param UserCast true if looking for user defined conversion for a static
1381/// cast.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001382Sema::OverloadingResult Sema::IsUserDefinedConversion(
1383 Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001384 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001385 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001386 bool AllowConversionFunctions,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001387 bool AllowExplicit, bool ForceRValue,
1388 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001389 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001390 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1391 // We're not going to find any constructors.
1392 } else if (CXXRecordDecl *ToRecordDecl
1393 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001394 // C++ [over.match.ctor]p1:
1395 // When objects of class type are direct-initialized (8.5), or
1396 // copy-initialized from an expression of the same or a
1397 // derived class type (8.5), overload resolution selects the
1398 // constructor. [...] For copy-initialization, the candidate
1399 // functions are all the converting constructors (12.3.1) of
1400 // that class. The argument list is the expression-list within
1401 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001402 bool SuppressUserConversions = !UserCast;
1403 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1404 IsDerivedFrom(From->getType(), ToType)) {
1405 SuppressUserConversions = false;
1406 AllowConversionFunctions = false;
1407 }
1408
Mike Stump11289f42009-09-09 15:08:12 +00001409 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001410 = Context.DeclarationNames.getCXXConstructorName(
1411 Context.getCanonicalType(ToType).getUnqualifiedType());
1412 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001413 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001414 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001415 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001416 // Find the constructor (which may be a template).
1417 CXXConstructorDecl *Constructor = 0;
1418 FunctionTemplateDecl *ConstructorTmpl
1419 = dyn_cast<FunctionTemplateDecl>(*Con);
1420 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001421 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001422 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1423 else
1424 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001425
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001426 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001427 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001428 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001429 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001430 1, CandidateSet,
1431 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001432 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001433 // Allow one user-defined conversion when user specifies a
1434 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001435 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001436 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001437 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001438 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001439 }
1440 }
1441
Douglas Gregor576e98c2009-01-30 23:27:23 +00001442 if (!AllowConversionFunctions) {
1443 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001444 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1445 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001446 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001447 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001448 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001449 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001450 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001451 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1452 // Add all of the conversion functions as candidates.
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001453 OverloadedFunctionDecl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001454 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001455 for (OverloadedFunctionDecl::function_iterator Func
1456 = Conversions->function_begin();
1457 Func != Conversions->function_end(); ++Func) {
1458 CXXConversionDecl *Conv;
1459 FunctionTemplateDecl *ConvTemplate;
1460 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1461 if (ConvTemplate)
1462 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1463 else
1464 Conv = dyn_cast<CXXConversionDecl>(*Func);
1465
1466 if (AllowExplicit || !Conv->isExplicit()) {
1467 if (ConvTemplate)
1468 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1469 CandidateSet);
1470 else
1471 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1472 }
1473 }
1474 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001475 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001476
1477 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001478 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001479 case OR_Success:
1480 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001481 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001482 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1483 // C++ [over.ics.user]p1:
1484 // If the user-defined conversion is specified by a
1485 // constructor (12.3.1), the initial standard conversion
1486 // sequence converts the source type to the type required by
1487 // the argument of the constructor.
1488 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001489 QualType ThisType = Constructor->getThisType(Context);
Fariborz Jahanian55824512009-11-06 00:23:08 +00001490 if (Best->Conversions[0].ConversionKind ==
1491 ImplicitConversionSequence::EllipsisConversion)
1492 User.EllipsisConversion = true;
1493 else {
1494 User.Before = Best->Conversions[0].Standard;
1495 User.EllipsisConversion = false;
1496 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001497 User.ConversionFunction = Constructor;
1498 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001499 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001500 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001501 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001502 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001503 } else if (CXXConversionDecl *Conversion
1504 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1505 // C++ [over.ics.user]p1:
1506 //
1507 // [...] If the user-defined conversion is specified by a
1508 // conversion function (12.3.2), the initial standard
1509 // conversion sequence converts the source type to the
1510 // implicit object parameter of the conversion function.
1511 User.Before = Best->Conversions[0].Standard;
1512 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001513 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001514
1515 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001516 // The second standard conversion sequence converts the
1517 // result of the user-defined conversion to the target type
1518 // for the sequence. Since an implicit conversion sequence
1519 // is an initialization, the special rules for
1520 // initialization by user-defined conversion apply when
1521 // selecting the best user-defined conversion for a
1522 // user-defined conversion sequence (see 13.3.3 and
1523 // 13.3.3.1).
1524 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001525 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001526 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001527 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001528 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001529 }
Mike Stump11289f42009-09-09 15:08:12 +00001530
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001531 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001532 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001533 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001534 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001535 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001536
1537 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001538 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001539 }
1540
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001541 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001542}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001543
1544bool
1545Sema::DiagnoseAmbiguousUserDefinedConversion(Expr *From, QualType ToType) {
1546 ImplicitConversionSequence ICS;
1547 OverloadCandidateSet CandidateSet;
1548 OverloadingResult OvResult =
1549 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1550 CandidateSet, true, false, false);
1551 if (OvResult != OR_Ambiguous)
1552 return false;
1553 Diag(From->getSourceRange().getBegin(),
1554 diag::err_typecheck_ambiguous_condition)
1555 << From->getType() << ToType << From->getSourceRange();
1556 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1557 return true;
1558}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001559
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001560/// CompareImplicitConversionSequences - Compare two implicit
1561/// conversion sequences to determine whether one is better than the
1562/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001563ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001564Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1565 const ImplicitConversionSequence& ICS2)
1566{
1567 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1568 // conversion sequences (as defined in 13.3.3.1)
1569 // -- a standard conversion sequence (13.3.3.1.1) is a better
1570 // conversion sequence than a user-defined conversion sequence or
1571 // an ellipsis conversion sequence, and
1572 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1573 // conversion sequence than an ellipsis conversion sequence
1574 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001575 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001576 if (ICS1.ConversionKind < ICS2.ConversionKind)
1577 return ImplicitConversionSequence::Better;
1578 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1579 return ImplicitConversionSequence::Worse;
1580
1581 // Two implicit conversion sequences of the same form are
1582 // indistinguishable conversion sequences unless one of the
1583 // following rules apply: (C++ 13.3.3.2p3):
1584 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1585 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001586 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001587 ImplicitConversionSequence::UserDefinedConversion) {
1588 // User-defined conversion sequence U1 is a better conversion
1589 // sequence than another user-defined conversion sequence U2 if
1590 // they contain the same user-defined conversion function or
1591 // constructor and if the second standard conversion sequence of
1592 // U1 is better than the second standard conversion sequence of
1593 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001594 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001595 ICS2.UserDefined.ConversionFunction)
1596 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1597 ICS2.UserDefined.After);
1598 }
1599
1600 return ImplicitConversionSequence::Indistinguishable;
1601}
1602
1603/// CompareStandardConversionSequences - Compare two standard
1604/// conversion sequences to determine whether one is better than the
1605/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001606ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001607Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1608 const StandardConversionSequence& SCS2)
1609{
1610 // Standard conversion sequence S1 is a better conversion sequence
1611 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1612
1613 // -- S1 is a proper subsequence of S2 (comparing the conversion
1614 // sequences in the canonical form defined by 13.3.3.1.1,
1615 // excluding any Lvalue Transformation; the identity conversion
1616 // sequence is considered to be a subsequence of any
1617 // non-identity conversion sequence) or, if not that,
1618 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1619 // Neither is a proper subsequence of the other. Do nothing.
1620 ;
1621 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1622 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001623 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001624 SCS1.Third == ICK_Identity))
1625 // SCS1 is a proper subsequence of SCS2.
1626 return ImplicitConversionSequence::Better;
1627 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1628 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001629 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001630 SCS2.Third == ICK_Identity))
1631 // SCS2 is a proper subsequence of SCS1.
1632 return ImplicitConversionSequence::Worse;
1633
1634 // -- the rank of S1 is better than the rank of S2 (by the rules
1635 // defined below), or, if not that,
1636 ImplicitConversionRank Rank1 = SCS1.getRank();
1637 ImplicitConversionRank Rank2 = SCS2.getRank();
1638 if (Rank1 < Rank2)
1639 return ImplicitConversionSequence::Better;
1640 else if (Rank2 < Rank1)
1641 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001642
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001643 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1644 // are indistinguishable unless one of the following rules
1645 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001646
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001647 // A conversion that is not a conversion of a pointer, or
1648 // pointer to member, to bool is better than another conversion
1649 // that is such a conversion.
1650 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1651 return SCS2.isPointerConversionToBool()
1652 ? ImplicitConversionSequence::Better
1653 : ImplicitConversionSequence::Worse;
1654
Douglas Gregor5c407d92008-10-23 00:40:37 +00001655 // C++ [over.ics.rank]p4b2:
1656 //
1657 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001658 // conversion of B* to A* is better than conversion of B* to
1659 // void*, and conversion of A* to void* is better than conversion
1660 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001661 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001662 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001663 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001664 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001665 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1666 // Exactly one of the conversion sequences is a conversion to
1667 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001668 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1669 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001670 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1671 // Neither conversion sequence converts to a void pointer; compare
1672 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001673 if (ImplicitConversionSequence::CompareKind DerivedCK
1674 = CompareDerivedToBaseConversions(SCS1, SCS2))
1675 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001676 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1677 // Both conversion sequences are conversions to void
1678 // pointers. Compare the source types to determine if there's an
1679 // inheritance relationship in their sources.
1680 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1681 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1682
1683 // Adjust the types we're converting from via the array-to-pointer
1684 // conversion, if we need to.
1685 if (SCS1.First == ICK_Array_To_Pointer)
1686 FromType1 = Context.getArrayDecayedType(FromType1);
1687 if (SCS2.First == ICK_Array_To_Pointer)
1688 FromType2 = Context.getArrayDecayedType(FromType2);
1689
Mike Stump11289f42009-09-09 15:08:12 +00001690 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001691 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001692 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001693 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001694
1695 if (IsDerivedFrom(FromPointee2, FromPointee1))
1696 return ImplicitConversionSequence::Better;
1697 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1698 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001699
1700 // Objective-C++: If one interface is more specific than the
1701 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001702 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1703 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001704 if (FromIface1 && FromIface1) {
1705 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1706 return ImplicitConversionSequence::Better;
1707 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1708 return ImplicitConversionSequence::Worse;
1709 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001710 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001711
1712 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1713 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001714 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001715 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001716 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001717
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001718 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001719 // C++0x [over.ics.rank]p3b4:
1720 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1721 // implicit object parameter of a non-static member function declared
1722 // without a ref-qualifier, and S1 binds an rvalue reference to an
1723 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001724 // FIXME: We don't know if we're dealing with the implicit object parameter,
1725 // or if the member function in this case has a ref qualifier.
1726 // (Of course, we don't have ref qualifiers yet.)
1727 if (SCS1.RRefBinding != SCS2.RRefBinding)
1728 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1729 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001730
1731 // C++ [over.ics.rank]p3b4:
1732 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1733 // which the references refer are the same type except for
1734 // top-level cv-qualifiers, and the type to which the reference
1735 // initialized by S2 refers is more cv-qualified than the type
1736 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001737 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1738 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001739 T1 = Context.getCanonicalType(T1);
1740 T2 = Context.getCanonicalType(T2);
1741 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1742 if (T2.isMoreQualifiedThan(T1))
1743 return ImplicitConversionSequence::Better;
1744 else if (T1.isMoreQualifiedThan(T2))
1745 return ImplicitConversionSequence::Worse;
1746 }
1747 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001748
1749 return ImplicitConversionSequence::Indistinguishable;
1750}
1751
1752/// CompareQualificationConversions - Compares two standard conversion
1753/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001754/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1755ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001756Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001757 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001758 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001759 // -- S1 and S2 differ only in their qualification conversion and
1760 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1761 // cv-qualification signature of type T1 is a proper subset of
1762 // the cv-qualification signature of type T2, and S1 is not the
1763 // deprecated string literal array-to-pointer conversion (4.2).
1764 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1765 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1766 return ImplicitConversionSequence::Indistinguishable;
1767
1768 // FIXME: the example in the standard doesn't use a qualification
1769 // conversion (!)
1770 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1771 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1772 T1 = Context.getCanonicalType(T1);
1773 T2 = Context.getCanonicalType(T2);
1774
1775 // If the types are the same, we won't learn anything by unwrapped
1776 // them.
1777 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1778 return ImplicitConversionSequence::Indistinguishable;
1779
Mike Stump11289f42009-09-09 15:08:12 +00001780 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001781 = ImplicitConversionSequence::Indistinguishable;
1782 while (UnwrapSimilarPointerTypes(T1, T2)) {
1783 // Within each iteration of the loop, we check the qualifiers to
1784 // determine if this still looks like a qualification
1785 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001786 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001787 // until there are no more pointers or pointers-to-members left
1788 // to unwrap. This essentially mimics what
1789 // IsQualificationConversion does, but here we're checking for a
1790 // strict subset of qualifiers.
1791 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1792 // The qualifiers are the same, so this doesn't tell us anything
1793 // about how the sequences rank.
1794 ;
1795 else if (T2.isMoreQualifiedThan(T1)) {
1796 // T1 has fewer qualifiers, so it could be the better sequence.
1797 if (Result == ImplicitConversionSequence::Worse)
1798 // Neither has qualifiers that are a subset of the other's
1799 // qualifiers.
1800 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001801
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001802 Result = ImplicitConversionSequence::Better;
1803 } else if (T1.isMoreQualifiedThan(T2)) {
1804 // T2 has fewer qualifiers, so it could be the better sequence.
1805 if (Result == ImplicitConversionSequence::Better)
1806 // Neither has qualifiers that are a subset of the other's
1807 // qualifiers.
1808 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001809
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001810 Result = ImplicitConversionSequence::Worse;
1811 } else {
1812 // Qualifiers are disjoint.
1813 return ImplicitConversionSequence::Indistinguishable;
1814 }
1815
1816 // If the types after this point are equivalent, we're done.
1817 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1818 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001819 }
1820
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001821 // Check that the winning standard conversion sequence isn't using
1822 // the deprecated string literal array to pointer conversion.
1823 switch (Result) {
1824 case ImplicitConversionSequence::Better:
1825 if (SCS1.Deprecated)
1826 Result = ImplicitConversionSequence::Indistinguishable;
1827 break;
1828
1829 case ImplicitConversionSequence::Indistinguishable:
1830 break;
1831
1832 case ImplicitConversionSequence::Worse:
1833 if (SCS2.Deprecated)
1834 Result = ImplicitConversionSequence::Indistinguishable;
1835 break;
1836 }
1837
1838 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001839}
1840
Douglas Gregor5c407d92008-10-23 00:40:37 +00001841/// CompareDerivedToBaseConversions - Compares two standard conversion
1842/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001843/// various kinds of derived-to-base conversions (C++
1844/// [over.ics.rank]p4b3). As part of these checks, we also look at
1845/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001846ImplicitConversionSequence::CompareKind
1847Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1848 const StandardConversionSequence& SCS2) {
1849 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1850 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1851 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1852 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1853
1854 // Adjust the types we're converting from via the array-to-pointer
1855 // conversion, if we need to.
1856 if (SCS1.First == ICK_Array_To_Pointer)
1857 FromType1 = Context.getArrayDecayedType(FromType1);
1858 if (SCS2.First == ICK_Array_To_Pointer)
1859 FromType2 = Context.getArrayDecayedType(FromType2);
1860
1861 // Canonicalize all of the types.
1862 FromType1 = Context.getCanonicalType(FromType1);
1863 ToType1 = Context.getCanonicalType(ToType1);
1864 FromType2 = Context.getCanonicalType(FromType2);
1865 ToType2 = Context.getCanonicalType(ToType2);
1866
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001867 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001868 //
1869 // If class B is derived directly or indirectly from class A and
1870 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001871 //
1872 // For Objective-C, we let A, B, and C also be Objective-C
1873 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001874
1875 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001876 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001877 SCS2.Second == ICK_Pointer_Conversion &&
1878 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1879 FromType1->isPointerType() && FromType2->isPointerType() &&
1880 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001881 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001882 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001883 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001884 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001885 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001886 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001887 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001888 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001889
John McCall9dd450b2009-09-21 23:43:11 +00001890 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1891 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1892 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1893 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001894
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001895 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001896 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1897 if (IsDerivedFrom(ToPointee1, ToPointee2))
1898 return ImplicitConversionSequence::Better;
1899 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1900 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001901
1902 if (ToIface1 && ToIface2) {
1903 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1904 return ImplicitConversionSequence::Better;
1905 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1906 return ImplicitConversionSequence::Worse;
1907 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001908 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001909
1910 // -- conversion of B* to A* is better than conversion of C* to A*,
1911 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1912 if (IsDerivedFrom(FromPointee2, FromPointee1))
1913 return ImplicitConversionSequence::Better;
1914 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1915 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001916
Douglas Gregor237f96c2008-11-26 23:31:11 +00001917 if (FromIface1 && FromIface2) {
1918 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1919 return ImplicitConversionSequence::Better;
1920 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1921 return ImplicitConversionSequence::Worse;
1922 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001923 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001924 }
1925
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001926 // Compare based on reference bindings.
1927 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1928 SCS1.Second == ICK_Derived_To_Base) {
1929 // -- binding of an expression of type C to a reference of type
1930 // B& is better than binding an expression of type C to a
1931 // reference of type A&,
1932 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1933 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1934 if (IsDerivedFrom(ToType1, ToType2))
1935 return ImplicitConversionSequence::Better;
1936 else if (IsDerivedFrom(ToType2, ToType1))
1937 return ImplicitConversionSequence::Worse;
1938 }
1939
Douglas Gregor2fe98832008-11-03 19:09:14 +00001940 // -- binding of an expression of type B to a reference of type
1941 // A& is better than binding an expression of type C to a
1942 // reference of type A&,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001943 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1944 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1945 if (IsDerivedFrom(FromType2, FromType1))
1946 return ImplicitConversionSequence::Better;
1947 else if (IsDerivedFrom(FromType1, FromType2))
1948 return ImplicitConversionSequence::Worse;
1949 }
1950 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001951
1952 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001953 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1954 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1955 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1956 const MemberPointerType * FromMemPointer1 =
1957 FromType1->getAs<MemberPointerType>();
1958 const MemberPointerType * ToMemPointer1 =
1959 ToType1->getAs<MemberPointerType>();
1960 const MemberPointerType * FromMemPointer2 =
1961 FromType2->getAs<MemberPointerType>();
1962 const MemberPointerType * ToMemPointer2 =
1963 ToType2->getAs<MemberPointerType>();
1964 const Type *FromPointeeType1 = FromMemPointer1->getClass();
1965 const Type *ToPointeeType1 = ToMemPointer1->getClass();
1966 const Type *FromPointeeType2 = FromMemPointer2->getClass();
1967 const Type *ToPointeeType2 = ToMemPointer2->getClass();
1968 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1969 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
1970 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
1971 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001972 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001973 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1974 if (IsDerivedFrom(ToPointee1, ToPointee2))
1975 return ImplicitConversionSequence::Worse;
1976 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1977 return ImplicitConversionSequence::Better;
1978 }
1979 // conversion of B::* to C::* is better than conversion of A::* to C::*
1980 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
1981 if (IsDerivedFrom(FromPointee1, FromPointee2))
1982 return ImplicitConversionSequence::Better;
1983 else if (IsDerivedFrom(FromPointee2, FromPointee1))
1984 return ImplicitConversionSequence::Worse;
1985 }
1986 }
1987
Douglas Gregor2fe98832008-11-03 19:09:14 +00001988 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1989 SCS1.Second == ICK_Derived_To_Base) {
1990 // -- conversion of C to B is better than conversion of C to A,
1991 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1992 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1993 if (IsDerivedFrom(ToType1, ToType2))
1994 return ImplicitConversionSequence::Better;
1995 else if (IsDerivedFrom(ToType2, ToType1))
1996 return ImplicitConversionSequence::Worse;
1997 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001998
Douglas Gregor2fe98832008-11-03 19:09:14 +00001999 // -- conversion of B to A is better than conversion of C to A.
2000 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
2001 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
2002 if (IsDerivedFrom(FromType2, FromType1))
2003 return ImplicitConversionSequence::Better;
2004 else if (IsDerivedFrom(FromType1, FromType2))
2005 return ImplicitConversionSequence::Worse;
2006 }
2007 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002008
Douglas Gregor5c407d92008-10-23 00:40:37 +00002009 return ImplicitConversionSequence::Indistinguishable;
2010}
2011
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002012/// TryCopyInitialization - Try to copy-initialize a value of type
2013/// ToType from the expression From. Return the implicit conversion
2014/// sequence required to pass this argument, which may be a bad
2015/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002016/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002017/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2018/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002019ImplicitConversionSequence
2020Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002021 bool SuppressUserConversions, bool ForceRValue,
2022 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002023 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002024 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00002025 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002026 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002027 SuppressUserConversions,
2028 /*AllowExplicit=*/false,
2029 ForceRValue,
2030 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002031 return ICS;
2032 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002033 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002034 SuppressUserConversions,
2035 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002036 ForceRValue,
2037 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002038 }
2039}
2040
Sebastian Redl42e92c42009-04-12 17:16:29 +00002041/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2042/// the expression @p From. Returns true (and emits a diagnostic) if there was
2043/// an error, returns false if the initialization succeeded. Elidable should
2044/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2045/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002046bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002047 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002048 if (!getLangOptions().CPlusPlus) {
2049 // In C, argument passing is the same as performing an assignment.
2050 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002051
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002052 AssignConvertType ConvTy =
2053 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002054 if (ConvTy != Compatible &&
2055 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2056 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002057
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002058 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2059 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002060 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002061
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002062 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002063 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002064 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002065 /*SuppressUserConversions=*/false,
2066 /*AllowExplicit=*/false,
2067 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002068
Sebastian Redl42e92c42009-04-12 17:16:29 +00002069 if (!PerformImplicitConversion(From, ToType, Flavor,
2070 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002071 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002072 if (!DiagnoseAmbiguousUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002073 return Diag(From->getSourceRange().getBegin(),
2074 diag::err_typecheck_convert_incompatible)
2075 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002076 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002077}
2078
Douglas Gregor436424c2008-11-18 23:14:02 +00002079/// TryObjectArgumentInitialization - Try to initialize the object
2080/// parameter of the given member function (@c Method) from the
2081/// expression @p From.
2082ImplicitConversionSequence
2083Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2084 QualType ClassType = Context.getTypeDeclType(Method->getParent());
John McCall8ccfcb52009-09-24 19:53:00 +00002085 QualType ImplicitParamType
2086 = Context.getCVRQualifiedType(ClassType, Method->getTypeQualifiers());
Douglas Gregor436424c2008-11-18 23:14:02 +00002087
2088 // Set up the conversion sequence as a "bad" conversion, to allow us
2089 // to exit early.
2090 ImplicitConversionSequence ICS;
2091 ICS.Standard.setAsIdentityConversion();
2092 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2093
2094 // We need to have an object of class type.
2095 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002096 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002097 FromType = PT->getPointeeType();
2098
2099 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002100
2101 // The implicit object parmeter is has the type "reference to cv X",
2102 // where X is the class of which the function is a member
2103 // (C++ [over.match.funcs]p4). However, when finding an implicit
2104 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002105 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002106 // (C++ [over.match.funcs]p5). We perform a simplified version of
2107 // reference binding here, that allows class rvalues to bind to
2108 // non-constant references.
2109
2110 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2111 // with the implicit object parameter (C++ [over.match.funcs]p5).
2112 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor01df9462009-11-05 00:07:36 +00002113 if (ImplicitParamType.getCVRQualifiers() != FromTypeCanon.getCVRQualifiers() &&
2114 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor436424c2008-11-18 23:14:02 +00002115 return ICS;
2116
2117 // Check that we have either the same type or a derived type. It
2118 // affects the conversion rank.
2119 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2120 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2121 ICS.Standard.Second = ICK_Identity;
2122 else if (IsDerivedFrom(FromType, ClassType))
2123 ICS.Standard.Second = ICK_Derived_To_Base;
2124 else
2125 return ICS;
2126
2127 // Success. Mark this as a reference binding.
2128 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2129 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2130 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2131 ICS.Standard.ReferenceBinding = true;
2132 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002133 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002134 return ICS;
2135}
2136
2137/// PerformObjectArgumentInitialization - Perform initialization of
2138/// the implicit object parameter for the given Method with the given
2139/// expression.
2140bool
2141Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002142 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002143 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002144 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002145
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002146 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002147 FromRecordType = PT->getPointeeType();
2148 DestType = Method->getThisType(Context);
2149 } else {
2150 FromRecordType = From->getType();
2151 DestType = ImplicitParamRecordType;
2152 }
2153
Mike Stump11289f42009-09-09 15:08:12 +00002154 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002155 = TryObjectArgumentInitialization(From, Method);
2156 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2157 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002158 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002159 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002160
Douglas Gregor436424c2008-11-18 23:14:02 +00002161 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002162 CheckDerivedToBaseConversion(FromRecordType,
2163 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002164 From->getSourceRange().getBegin(),
2165 From->getSourceRange()))
2166 return true;
2167
Mike Stump11289f42009-09-09 15:08:12 +00002168 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002169 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002170 return false;
2171}
2172
Douglas Gregor5fb53972009-01-14 15:45:31 +00002173/// TryContextuallyConvertToBool - Attempt to contextually convert the
2174/// expression From to bool (C++0x [conv]p3).
2175ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002176 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002177 // FIXME: Are these flags correct?
2178 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002179 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002180 /*ForceRValue=*/false,
2181 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002182}
2183
2184/// PerformContextuallyConvertToBool - Perform a contextual conversion
2185/// of the expression From to bool (C++0x [conv]p3).
2186bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2187 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2188 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2189 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002190
2191 if (!DiagnoseAmbiguousUserDefinedConversion(From, Context.BoolTy))
2192 return Diag(From->getSourceRange().getBegin(),
2193 diag::err_typecheck_bool_condition)
2194 << From->getType() << From->getSourceRange();
2195 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002196}
2197
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002198/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002199/// candidate functions, using the given function call arguments. If
2200/// @p SuppressUserConversions, then don't allow user-defined
2201/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002202/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2203/// hacky way to implement the overloading rules for elidable copy
2204/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002205///
2206/// \para PartialOverloading true if we are performing "partial" overloading
2207/// based on an incomplete set of function arguments. This feature is used by
2208/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002209void
2210Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002211 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002212 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002213 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002214 bool ForceRValue,
2215 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002216 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002217 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002218 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002219 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002220 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002221 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002222 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002223
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002224 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002225 if (!isa<CXXConstructorDecl>(Method)) {
2226 // If we get here, it's because we're calling a member function
2227 // that is named without a member access expression (e.g.,
2228 // "this->f") that was either written explicitly or created
2229 // implicitly. This can happen with a qualified call to a member
2230 // function, e.g., X::f(). We use a NULL object as the implied
2231 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002232 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002233 SuppressUserConversions, ForceRValue);
2234 return;
2235 }
2236 // We treat a constructor like a non-member function, since its object
2237 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002238 }
2239
Douglas Gregorff7028a2009-11-13 23:59:09 +00002240 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002241 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002242
2243 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2244 // C++ [class.copy]p3:
2245 // A member function template is never instantiated to perform the copy
2246 // of a class object to an object of its class type.
2247 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2248 if (NumArgs == 1 &&
2249 Constructor->isCopyConstructorLikeSpecialization() &&
2250 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2251 return;
2252 }
2253
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002254 // Add this candidate
2255 CandidateSet.push_back(OverloadCandidate());
2256 OverloadCandidate& Candidate = CandidateSet.back();
2257 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002258 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002259 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002260 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002261
2262 unsigned NumArgsInProto = Proto->getNumArgs();
2263
2264 // (C++ 13.3.2p2): A candidate function having fewer than m
2265 // parameters is viable only if it has an ellipsis in its parameter
2266 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002267 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2268 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002269 Candidate.Viable = false;
2270 return;
2271 }
2272
2273 // (C++ 13.3.2p2): A candidate function having more than m parameters
2274 // is viable only if the (m+1)st parameter has a default argument
2275 // (8.3.6). For the purposes of overload resolution, the
2276 // parameter list is truncated on the right, so that there are
2277 // exactly m parameters.
2278 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002279 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002280 // Not enough arguments.
2281 Candidate.Viable = false;
2282 return;
2283 }
2284
2285 // Determine the implicit conversion sequences for each of the
2286 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002287 Candidate.Conversions.resize(NumArgs);
2288 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2289 if (ArgIdx < NumArgsInProto) {
2290 // (C++ 13.3.2p3): for F to be a viable function, there shall
2291 // exist for each argument an implicit conversion sequence
2292 // (13.3.3.1) that converts that argument to the corresponding
2293 // parameter of F.
2294 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002295 Candidate.Conversions[ArgIdx]
2296 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002297 SuppressUserConversions, ForceRValue,
2298 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002299 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002300 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002301 // 13.3.3.1-p10 If several different sequences of conversions exist that
2302 // each convert the argument to the parameter type, the implicit conversion
2303 // sequence associated with the parameter is defined to be the unique conversion
2304 // sequence designated the ambiguous conversion sequence. For the purpose of
2305 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2306 // conversion sequence is treated as a user-defined sequence that is
2307 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002308 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002309 Candidate.Conversions[ArgIdx].ConversionKind =
2310 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002311 // Set the conversion function to one of them. As due to ambiguity,
2312 // they carry the same weight and is needed for overload resolution
2313 // later.
2314 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2315 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2316 }
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002317 else {
2318 Candidate.Viable = false;
2319 break;
2320 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002321 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002322 } else {
2323 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2324 // argument for which there is no corresponding parameter is
2325 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002326 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002327 = ImplicitConversionSequence::EllipsisConversion;
2328 }
2329 }
2330}
2331
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002332/// \brief Add all of the function declarations in the given function set to
2333/// the overload canddiate set.
2334void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2335 Expr **Args, unsigned NumArgs,
2336 OverloadCandidateSet& CandidateSet,
2337 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002338 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002339 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002340 F != FEnd; ++F) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002341 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2342 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2343 AddMethodCandidate(cast<CXXMethodDecl>(FD),
2344 Args[0], Args + 1, NumArgs - 1,
2345 CandidateSet, SuppressUserConversions);
2346 else
2347 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2348 SuppressUserConversions);
2349 } else {
2350 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2351 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2352 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2353 AddMethodTemplateCandidate(FunTmpl,
Douglas Gregor89026b52009-06-30 23:57:56 +00002354 /*FIXME: explicit args */false, 0, 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002355 Args[0], Args + 1, NumArgs - 1,
2356 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002357 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002358 else
2359 AddTemplateOverloadCandidate(FunTmpl,
2360 /*FIXME: explicit args */false, 0, 0,
2361 Args, NumArgs, CandidateSet,
2362 SuppressUserConversions);
2363 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002364 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002365}
2366
Douglas Gregor436424c2008-11-18 23:14:02 +00002367/// AddMethodCandidate - Adds the given C++ member function to the set
2368/// of candidate functions, using the given function call arguments
2369/// and the object argument (@c Object). For example, in a call
2370/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2371/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2372/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002373/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2374/// a slightly hacky way to implement the overloading rules for elidable copy
2375/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002376void
Douglas Gregor436424c2008-11-18 23:14:02 +00002377Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2378 Expr **Args, unsigned NumArgs,
2379 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002380 bool SuppressUserConversions, bool ForceRValue) {
2381 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002382 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002383 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002384 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002385 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002386 assert(!isa<CXXConstructorDecl>(Method) &&
2387 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002388
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002389 if (!CandidateSet.isNewCandidate(Method))
2390 return;
2391
Douglas Gregor436424c2008-11-18 23:14:02 +00002392 // Add this candidate
2393 CandidateSet.push_back(OverloadCandidate());
2394 OverloadCandidate& Candidate = CandidateSet.back();
2395 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002396 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002397 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002398
2399 unsigned NumArgsInProto = Proto->getNumArgs();
2400
2401 // (C++ 13.3.2p2): A candidate function having fewer than m
2402 // parameters is viable only if it has an ellipsis in its parameter
2403 // list (8.3.5).
2404 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2405 Candidate.Viable = false;
2406 return;
2407 }
2408
2409 // (C++ 13.3.2p2): A candidate function having more than m parameters
2410 // is viable only if the (m+1)st parameter has a default argument
2411 // (8.3.6). For the purposes of overload resolution, the
2412 // parameter list is truncated on the right, so that there are
2413 // exactly m parameters.
2414 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2415 if (NumArgs < MinRequiredArgs) {
2416 // Not enough arguments.
2417 Candidate.Viable = false;
2418 return;
2419 }
2420
2421 Candidate.Viable = true;
2422 Candidate.Conversions.resize(NumArgs + 1);
2423
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002424 if (Method->isStatic() || !Object)
2425 // The implicit object argument is ignored.
2426 Candidate.IgnoreObjectArgument = true;
2427 else {
2428 // Determine the implicit conversion sequence for the object
2429 // parameter.
2430 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002431 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002432 == ImplicitConversionSequence::BadConversion) {
2433 Candidate.Viable = false;
2434 return;
2435 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002436 }
2437
2438 // Determine the implicit conversion sequences for each of the
2439 // arguments.
2440 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2441 if (ArgIdx < NumArgsInProto) {
2442 // (C++ 13.3.2p3): for F to be a viable function, there shall
2443 // exist for each argument an implicit conversion sequence
2444 // (13.3.3.1) that converts that argument to the corresponding
2445 // parameter of F.
2446 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002447 Candidate.Conversions[ArgIdx + 1]
2448 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002449 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002450 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002451 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002452 == ImplicitConversionSequence::BadConversion) {
2453 Candidate.Viable = false;
2454 break;
2455 }
2456 } else {
2457 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2458 // argument for which there is no corresponding parameter is
2459 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002460 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002461 = ImplicitConversionSequence::EllipsisConversion;
2462 }
2463 }
2464}
2465
Douglas Gregor97628d62009-08-21 00:16:32 +00002466/// \brief Add a C++ member function template as a candidate to the candidate
2467/// set, using template argument deduction to produce an appropriate member
2468/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002469void
Douglas Gregor97628d62009-08-21 00:16:32 +00002470Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2471 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00002472 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002473 unsigned NumExplicitTemplateArgs,
2474 Expr *Object, Expr **Args, unsigned NumArgs,
2475 OverloadCandidateSet& CandidateSet,
2476 bool SuppressUserConversions,
2477 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002478 if (!CandidateSet.isNewCandidate(MethodTmpl))
2479 return;
2480
Douglas Gregor97628d62009-08-21 00:16:32 +00002481 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002482 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002483 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002484 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002485 // candidate functions in the usual way.113) A given name can refer to one
2486 // or more function templates and also to a set of overloaded non-template
2487 // functions. In such a case, the candidate functions generated from each
2488 // function template are combined with the set of non-template candidate
2489 // functions.
2490 TemplateDeductionInfo Info(Context);
2491 FunctionDecl *Specialization = 0;
2492 if (TemplateDeductionResult Result
2493 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2494 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2495 Args, NumArgs, Specialization, Info)) {
2496 // FIXME: Record what happened with template argument deduction, so
2497 // that we can give the user a beautiful diagnostic.
2498 (void)Result;
2499 return;
2500 }
Mike Stump11289f42009-09-09 15:08:12 +00002501
Douglas Gregor97628d62009-08-21 00:16:32 +00002502 // Add the function template specialization produced by template argument
2503 // deduction as a candidate.
2504 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002505 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002506 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002507 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002508 CandidateSet, SuppressUserConversions, ForceRValue);
2509}
2510
Douglas Gregor05155d82009-08-21 23:19:43 +00002511/// \brief Add a C++ function template specialization as a candidate
2512/// in the candidate set, using template argument deduction to produce
2513/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002514void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002515Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor89026b52009-06-30 23:57:56 +00002516 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00002517 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002518 unsigned NumExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002519 Expr **Args, unsigned NumArgs,
2520 OverloadCandidateSet& CandidateSet,
2521 bool SuppressUserConversions,
2522 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002523 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2524 return;
2525
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002526 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002527 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002528 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002529 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002530 // candidate functions in the usual way.113) A given name can refer to one
2531 // or more function templates and also to a set of overloaded non-template
2532 // functions. In such a case, the candidate functions generated from each
2533 // function template are combined with the set of non-template candidate
2534 // functions.
2535 TemplateDeductionInfo Info(Context);
2536 FunctionDecl *Specialization = 0;
2537 if (TemplateDeductionResult Result
Douglas Gregor89026b52009-06-30 23:57:56 +00002538 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2539 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2540 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002541 // FIXME: Record what happened with template argument deduction, so
2542 // that we can give the user a beautiful diagnostic.
2543 (void)Result;
2544 return;
2545 }
Mike Stump11289f42009-09-09 15:08:12 +00002546
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002547 // Add the function template specialization produced by template argument
2548 // deduction as a candidate.
2549 assert(Specialization && "Missing function template specialization?");
2550 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2551 SuppressUserConversions, ForceRValue);
2552}
Mike Stump11289f42009-09-09 15:08:12 +00002553
Douglas Gregora1f013e2008-11-07 22:36:19 +00002554/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002555/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002556/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002557/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002558/// (which may or may not be the same type as the type that the
2559/// conversion function produces).
2560void
2561Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2562 Expr *From, QualType ToType,
2563 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002564 assert(!Conversion->getDescribedFunctionTemplate() &&
2565 "Conversion function templates use AddTemplateConversionCandidate");
2566
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002567 if (!CandidateSet.isNewCandidate(Conversion))
2568 return;
2569
Douglas Gregora1f013e2008-11-07 22:36:19 +00002570 // Add this candidate
2571 CandidateSet.push_back(OverloadCandidate());
2572 OverloadCandidate& Candidate = CandidateSet.back();
2573 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002574 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002575 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002576 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002577 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002578 = Conversion->getConversionType().getAsOpaquePtr();
2579 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2580
Douglas Gregor436424c2008-11-18 23:14:02 +00002581 // Determine the implicit conversion sequence for the implicit
2582 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002583 Candidate.Viable = true;
2584 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002585 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002586 // Conversion functions to a different type in the base class is visible in
2587 // the derived class. So, a derived to base conversion should not participate
2588 // in overload resolution.
2589 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2590 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002591 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002592 == ImplicitConversionSequence::BadConversion) {
2593 Candidate.Viable = false;
2594 return;
2595 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002596
2597 // We won't go through a user-define type conversion function to convert a
2598 // derived to base as such conversions are given Conversion Rank. They only
2599 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2600 QualType FromCanon
2601 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2602 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2603 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2604 Candidate.Viable = false;
2605 return;
2606 }
2607
Douglas Gregora1f013e2008-11-07 22:36:19 +00002608
2609 // To determine what the conversion from the result of calling the
2610 // conversion function to the type we're eventually trying to
2611 // convert to (ToType), we need to synthesize a call to the
2612 // conversion function and attempt copy initialization from it. This
2613 // makes sure that we get the right semantics with respect to
2614 // lvalues/rvalues and the type. Fortunately, we can allocate this
2615 // call on the stack and we don't need its arguments to be
2616 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002617 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregora1f013e2008-11-07 22:36:19 +00002618 SourceLocation());
2619 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002620 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002621 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002622
2623 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002624 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2625 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002626 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002627 Conversion->getConversionType().getNonReferenceType(),
2628 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002629 ImplicitConversionSequence ICS =
2630 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002631 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002632 /*ForceRValue=*/false,
2633 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002634
Douglas Gregora1f013e2008-11-07 22:36:19 +00002635 switch (ICS.ConversionKind) {
2636 case ImplicitConversionSequence::StandardConversion:
2637 Candidate.FinalConversion = ICS.Standard;
2638 break;
2639
2640 case ImplicitConversionSequence::BadConversion:
2641 Candidate.Viable = false;
2642 break;
2643
2644 default:
Mike Stump11289f42009-09-09 15:08:12 +00002645 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002646 "Can only end up with a standard conversion sequence or failure");
2647 }
2648}
2649
Douglas Gregor05155d82009-08-21 23:19:43 +00002650/// \brief Adds a conversion function template specialization
2651/// candidate to the overload set, using template argument deduction
2652/// to deduce the template arguments of the conversion function
2653/// template from the type that we are converting to (C++
2654/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002655void
Douglas Gregor05155d82009-08-21 23:19:43 +00002656Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2657 Expr *From, QualType ToType,
2658 OverloadCandidateSet &CandidateSet) {
2659 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2660 "Only conversion function templates permitted here");
2661
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002662 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2663 return;
2664
Douglas Gregor05155d82009-08-21 23:19:43 +00002665 TemplateDeductionInfo Info(Context);
2666 CXXConversionDecl *Specialization = 0;
2667 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002668 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002669 Specialization, Info)) {
2670 // FIXME: Record what happened with template argument deduction, so
2671 // that we can give the user a beautiful diagnostic.
2672 (void)Result;
2673 return;
2674 }
Mike Stump11289f42009-09-09 15:08:12 +00002675
Douglas Gregor05155d82009-08-21 23:19:43 +00002676 // Add the conversion function template specialization produced by
2677 // template argument deduction as a candidate.
2678 assert(Specialization && "Missing function template specialization?");
2679 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2680}
2681
Douglas Gregorab7897a2008-11-19 22:57:39 +00002682/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2683/// converts the given @c Object to a function pointer via the
2684/// conversion function @c Conversion, and then attempts to call it
2685/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2686/// the type of function that we'll eventually be calling.
2687void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002688 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002689 Expr *Object, Expr **Args, unsigned NumArgs,
2690 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002691 if (!CandidateSet.isNewCandidate(Conversion))
2692 return;
2693
Douglas Gregorab7897a2008-11-19 22:57:39 +00002694 CandidateSet.push_back(OverloadCandidate());
2695 OverloadCandidate& Candidate = CandidateSet.back();
2696 Candidate.Function = 0;
2697 Candidate.Surrogate = Conversion;
2698 Candidate.Viable = true;
2699 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002700 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002701 Candidate.Conversions.resize(NumArgs + 1);
2702
2703 // Determine the implicit conversion sequence for the implicit
2704 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002705 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002706 = TryObjectArgumentInitialization(Object, Conversion);
2707 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2708 Candidate.Viable = false;
2709 return;
2710 }
2711
2712 // The first conversion is actually a user-defined conversion whose
2713 // first conversion is ObjectInit's standard conversion (which is
2714 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002715 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002716 = ImplicitConversionSequence::UserDefinedConversion;
2717 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002718 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002719 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002720 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002721 = Candidate.Conversions[0].UserDefined.Before;
2722 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2723
Mike Stump11289f42009-09-09 15:08:12 +00002724 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002725 unsigned NumArgsInProto = Proto->getNumArgs();
2726
2727 // (C++ 13.3.2p2): A candidate function having fewer than m
2728 // parameters is viable only if it has an ellipsis in its parameter
2729 // list (8.3.5).
2730 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2731 Candidate.Viable = false;
2732 return;
2733 }
2734
2735 // Function types don't have any default arguments, so just check if
2736 // we have enough arguments.
2737 if (NumArgs < NumArgsInProto) {
2738 // Not enough arguments.
2739 Candidate.Viable = false;
2740 return;
2741 }
2742
2743 // Determine the implicit conversion sequences for each of the
2744 // arguments.
2745 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2746 if (ArgIdx < NumArgsInProto) {
2747 // (C++ 13.3.2p3): for F to be a viable function, there shall
2748 // exist for each argument an implicit conversion sequence
2749 // (13.3.3.1) that converts that argument to the corresponding
2750 // parameter of F.
2751 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002752 Candidate.Conversions[ArgIdx + 1]
2753 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002754 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002755 /*ForceRValue=*/false,
2756 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002757 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002758 == ImplicitConversionSequence::BadConversion) {
2759 Candidate.Viable = false;
2760 break;
2761 }
2762 } else {
2763 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2764 // argument for which there is no corresponding parameter is
2765 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002766 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002767 = ImplicitConversionSequence::EllipsisConversion;
2768 }
2769 }
2770}
2771
Mike Stump87c57ac2009-05-16 07:39:55 +00002772// FIXME: This will eventually be removed, once we've migrated all of the
2773// operator overloading logic over to the scheme used by binary operators, which
2774// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002775void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002776 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002777 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002778 OverloadCandidateSet& CandidateSet,
2779 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002780 FunctionSet Functions;
2781
2782 QualType T1 = Args[0]->getType();
2783 QualType T2;
2784 if (NumArgs > 1)
2785 T2 = Args[1]->getType();
2786
2787 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002788 if (S)
2789 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002790 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002791 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2792 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002793 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002794}
2795
2796/// \brief Add overload candidates for overloaded operators that are
2797/// member functions.
2798///
2799/// Add the overloaded operator candidates that are member functions
2800/// for the operator Op that was used in an operator expression such
2801/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2802/// CandidateSet will store the added overload candidates. (C++
2803/// [over.match.oper]).
2804void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2805 SourceLocation OpLoc,
2806 Expr **Args, unsigned NumArgs,
2807 OverloadCandidateSet& CandidateSet,
2808 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002809 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2810
2811 // C++ [over.match.oper]p3:
2812 // For a unary operator @ with an operand of a type whose
2813 // cv-unqualified version is T1, and for a binary operator @ with
2814 // a left operand of a type whose cv-unqualified version is T1 and
2815 // a right operand of a type whose cv-unqualified version is T2,
2816 // three sets of candidate functions, designated member
2817 // candidates, non-member candidates and built-in candidates, are
2818 // constructed as follows:
2819 QualType T1 = Args[0]->getType();
2820 QualType T2;
2821 if (NumArgs > 1)
2822 T2 = Args[1]->getType();
2823
2824 // -- If T1 is a class type, the set of member candidates is the
2825 // result of the qualified lookup of T1::operator@
2826 // (13.3.1.1.1); otherwise, the set of member candidates is
2827 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002828 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002829 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002830 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002831 return;
Mike Stump11289f42009-09-09 15:08:12 +00002832
John McCall9f3059a2009-10-09 21:13:30 +00002833 LookupResult Operators;
2834 LookupQualifiedName(Operators, T1Rec->getDecl(), OpName,
2835 LookupOrdinaryName, false);
Mike Stump11289f42009-09-09 15:08:12 +00002836 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002837 OperEnd = Operators.end();
2838 Oper != OperEnd;
Douglas Gregor4aa2dc42009-10-14 16:50:13 +00002839 ++Oper) {
2840 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Oper)) {
2841 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
2842 /*SuppressUserConversions=*/false);
2843 continue;
2844 }
2845
2846 assert(isa<FunctionTemplateDecl>(*Oper) &&
2847 isa<CXXMethodDecl>(cast<FunctionTemplateDecl>(*Oper)
2848 ->getTemplatedDecl()) &&
2849 "Expected a member function template");
2850 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Oper), false, 0, 0,
2851 Args[0], Args+1, NumArgs - 1, CandidateSet,
2852 /*SuppressUserConversions=*/false);
2853 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002854 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002855}
2856
Douglas Gregora11693b2008-11-12 17:17:38 +00002857/// AddBuiltinCandidate - Add a candidate for a built-in
2858/// operator. ResultTy and ParamTys are the result and parameter types
2859/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002860/// arguments being passed to the candidate. IsAssignmentOperator
2861/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002862/// operator. NumContextualBoolArguments is the number of arguments
2863/// (at the beginning of the argument list) that will be contextually
2864/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002865void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002866 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002867 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002868 bool IsAssignmentOperator,
2869 unsigned NumContextualBoolArguments) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002870 // Add this candidate
2871 CandidateSet.push_back(OverloadCandidate());
2872 OverloadCandidate& Candidate = CandidateSet.back();
2873 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002874 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002875 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002876 Candidate.BuiltinTypes.ResultTy = ResultTy;
2877 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2878 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2879
2880 // Determine the implicit conversion sequences for each of the
2881 // arguments.
2882 Candidate.Viable = true;
2883 Candidate.Conversions.resize(NumArgs);
2884 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002885 // C++ [over.match.oper]p4:
2886 // For the built-in assignment operators, conversions of the
2887 // left operand are restricted as follows:
2888 // -- no temporaries are introduced to hold the left operand, and
2889 // -- no user-defined conversions are applied to the left
2890 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002891 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002892 //
2893 // We block these conversions by turning off user-defined
2894 // conversions, since that is the only way that initialization of
2895 // a reference to a non-class type can occur from something that
2896 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002897 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002898 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002899 "Contextual conversion to bool requires bool type");
2900 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2901 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002902 Candidate.Conversions[ArgIdx]
2903 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002904 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002905 /*ForceRValue=*/false,
2906 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002907 }
Mike Stump11289f42009-09-09 15:08:12 +00002908 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002909 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002910 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002911 break;
2912 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002913 }
2914}
2915
2916/// BuiltinCandidateTypeSet - A set of types that will be used for the
2917/// candidate operator functions for built-in operators (C++
2918/// [over.built]). The types are separated into pointer types and
2919/// enumeration types.
2920class BuiltinCandidateTypeSet {
2921 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002922 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002923
2924 /// PointerTypes - The set of pointer types that will be used in the
2925 /// built-in candidates.
2926 TypeSet PointerTypes;
2927
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002928 /// MemberPointerTypes - The set of member pointer types that will be
2929 /// used in the built-in candidates.
2930 TypeSet MemberPointerTypes;
2931
Douglas Gregora11693b2008-11-12 17:17:38 +00002932 /// EnumerationTypes - The set of enumeration types that will be
2933 /// used in the built-in candidates.
2934 TypeSet EnumerationTypes;
2935
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002936 /// Sema - The semantic analysis instance where we are building the
2937 /// candidate type set.
2938 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002939
Douglas Gregora11693b2008-11-12 17:17:38 +00002940 /// Context - The AST context in which we will build the type sets.
2941 ASTContext &Context;
2942
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00002943 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2944 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002945 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002946
2947public:
2948 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002949 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002950
Mike Stump11289f42009-09-09 15:08:12 +00002951 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002952 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002953
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002954 void AddTypesConvertedFrom(QualType Ty,
2955 SourceLocation Loc,
2956 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00002957 bool AllowExplicitConversions,
2958 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00002959
2960 /// pointer_begin - First pointer type found;
2961 iterator pointer_begin() { return PointerTypes.begin(); }
2962
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002963 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002964 iterator pointer_end() { return PointerTypes.end(); }
2965
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002966 /// member_pointer_begin - First member pointer type found;
2967 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2968
2969 /// member_pointer_end - Past the last member pointer type found;
2970 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2971
Douglas Gregora11693b2008-11-12 17:17:38 +00002972 /// enumeration_begin - First enumeration type found;
2973 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2974
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002975 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002976 iterator enumeration_end() { return EnumerationTypes.end(); }
2977};
2978
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002979/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00002980/// the set of pointer types along with any more-qualified variants of
2981/// that type. For example, if @p Ty is "int const *", this routine
2982/// will add "int const *", "int const volatile *", "int const
2983/// restrict *", and "int const volatile restrict *" to the set of
2984/// pointer types. Returns true if the add of @p Ty itself succeeded,
2985/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00002986///
2987/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002988bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002989BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2990 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00002991
Douglas Gregora11693b2008-11-12 17:17:38 +00002992 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002993 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002994 return false;
2995
John McCall8ccfcb52009-09-24 19:53:00 +00002996 const PointerType *PointerTy = Ty->getAs<PointerType>();
2997 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00002998
John McCall8ccfcb52009-09-24 19:53:00 +00002999 QualType PointeeTy = PointerTy->getPointeeType();
3000 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003001 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003002 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003003 bool hasVolatile = VisibleQuals.hasVolatile();
3004 bool hasRestrict = VisibleQuals.hasRestrict();
3005
John McCall8ccfcb52009-09-24 19:53:00 +00003006 // Iterate through all strict supersets of BaseCVR.
3007 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3008 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003009 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3010 // in the types.
3011 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3012 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003013 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3014 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003015 }
3016
3017 return true;
3018}
3019
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003020/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3021/// to the set of pointer types along with any more-qualified variants of
3022/// that type. For example, if @p Ty is "int const *", this routine
3023/// will add "int const *", "int const volatile *", "int const
3024/// restrict *", and "int const volatile restrict *" to the set of
3025/// pointer types. Returns true if the add of @p Ty itself succeeded,
3026/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003027///
3028/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003029bool
3030BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3031 QualType Ty) {
3032 // Insert this type.
3033 if (!MemberPointerTypes.insert(Ty))
3034 return false;
3035
John McCall8ccfcb52009-09-24 19:53:00 +00003036 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3037 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003038
John McCall8ccfcb52009-09-24 19:53:00 +00003039 QualType PointeeTy = PointerTy->getPointeeType();
3040 const Type *ClassTy = PointerTy->getClass();
3041
3042 // Iterate through all strict supersets of the pointee type's CVR
3043 // qualifiers.
3044 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3045 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3046 if ((CVR | BaseCVR) != CVR) continue;
3047
3048 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3049 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003050 }
3051
3052 return true;
3053}
3054
Douglas Gregora11693b2008-11-12 17:17:38 +00003055/// AddTypesConvertedFrom - Add each of the types to which the type @p
3056/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003057/// primarily interested in pointer types and enumeration types. We also
3058/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003059/// AllowUserConversions is true if we should look at the conversion
3060/// functions of a class type, and AllowExplicitConversions if we
3061/// should also include the explicit conversion functions of a class
3062/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003063void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003064BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003065 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003066 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003067 bool AllowExplicitConversions,
3068 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003069 // Only deal with canonical types.
3070 Ty = Context.getCanonicalType(Ty);
3071
3072 // Look through reference types; they aren't part of the type of an
3073 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003074 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003075 Ty = RefTy->getPointeeType();
3076
3077 // We don't care about qualifiers on the type.
3078 Ty = Ty.getUnqualifiedType();
3079
Sebastian Redl65ae2002009-11-05 16:36:20 +00003080 // If we're dealing with an array type, decay to the pointer.
3081 if (Ty->isArrayType())
3082 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3083
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003084 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003085 QualType PointeeTy = PointerTy->getPointeeType();
3086
3087 // Insert our type, and its more-qualified variants, into the set
3088 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003089 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003090 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003091 } else if (Ty->isMemberPointerType()) {
3092 // Member pointers are far easier, since the pointee can't be converted.
3093 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3094 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003095 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003096 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003097 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003098 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003099 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003100 // No conversion functions in incomplete types.
3101 return;
3102 }
Mike Stump11289f42009-09-09 15:08:12 +00003103
Douglas Gregora11693b2008-11-12 17:17:38 +00003104 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003105 OverloadedFunctionDecl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003106 = ClassDecl->getVisibleConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00003107 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregora11693b2008-11-12 17:17:38 +00003108 = Conversions->function_begin();
3109 Func != Conversions->function_end(); ++Func) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003110 CXXConversionDecl *Conv;
3111 FunctionTemplateDecl *ConvTemplate;
3112 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
3113
Mike Stump11289f42009-09-09 15:08:12 +00003114 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003115 // about which builtin types we can convert to.
3116 if (ConvTemplate)
3117 continue;
3118
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003119 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003120 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003121 VisibleQuals);
3122 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003123 }
3124 }
3125 }
3126}
3127
Douglas Gregor84605ae2009-08-24 13:43:27 +00003128/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3129/// the volatile- and non-volatile-qualified assignment operators for the
3130/// given type to the candidate set.
3131static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3132 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003133 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003134 unsigned NumArgs,
3135 OverloadCandidateSet &CandidateSet) {
3136 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003137
Douglas Gregor84605ae2009-08-24 13:43:27 +00003138 // T& operator=(T&, T)
3139 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3140 ParamTypes[1] = T;
3141 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3142 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003143
Douglas Gregor84605ae2009-08-24 13:43:27 +00003144 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3145 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003146 ParamTypes[0]
3147 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003148 ParamTypes[1] = T;
3149 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003150 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003151 }
3152}
Mike Stump11289f42009-09-09 15:08:12 +00003153
Sebastian Redl1054fae2009-10-25 17:03:50 +00003154/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3155/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003156static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3157 Qualifiers VRQuals;
3158 const RecordType *TyRec;
3159 if (const MemberPointerType *RHSMPType =
3160 ArgExpr->getType()->getAs<MemberPointerType>())
3161 TyRec = cast<RecordType>(RHSMPType->getClass());
3162 else
3163 TyRec = ArgExpr->getType()->getAs<RecordType>();
3164 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003165 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003166 VRQuals.addVolatile();
3167 VRQuals.addRestrict();
3168 return VRQuals;
3169 }
3170
3171 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3172 OverloadedFunctionDecl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003173 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003174
3175 for (OverloadedFunctionDecl::function_iterator Func
3176 = Conversions->function_begin();
3177 Func != Conversions->function_end(); ++Func) {
3178 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*Func)) {
3179 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3180 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3181 CanTy = ResTypeRef->getPointeeType();
3182 // Need to go down the pointer/mempointer chain and add qualifiers
3183 // as see them.
3184 bool done = false;
3185 while (!done) {
3186 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3187 CanTy = ResTypePtr->getPointeeType();
3188 else if (const MemberPointerType *ResTypeMPtr =
3189 CanTy->getAs<MemberPointerType>())
3190 CanTy = ResTypeMPtr->getPointeeType();
3191 else
3192 done = true;
3193 if (CanTy.isVolatileQualified())
3194 VRQuals.addVolatile();
3195 if (CanTy.isRestrictQualified())
3196 VRQuals.addRestrict();
3197 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3198 return VRQuals;
3199 }
3200 }
3201 }
3202 return VRQuals;
3203}
3204
Douglas Gregord08452f2008-11-19 15:42:04 +00003205/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3206/// operator overloads to the candidate set (C++ [over.built]), based
3207/// on the operator @p Op and the arguments given. For example, if the
3208/// operator is a binary '+', this routine might add "int
3209/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003210void
Mike Stump11289f42009-09-09 15:08:12 +00003211Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003212 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003213 Expr **Args, unsigned NumArgs,
3214 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003215 // The set of "promoted arithmetic types", which are the arithmetic
3216 // types are that preserved by promotion (C++ [over.built]p2). Note
3217 // that the first few of these types are the promoted integral
3218 // types; these types need to be first.
3219 // FIXME: What about complex?
3220 const unsigned FirstIntegralType = 0;
3221 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003222 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003223 LastPromotedIntegralType = 13;
3224 const unsigned FirstPromotedArithmeticType = 7,
3225 LastPromotedArithmeticType = 16;
3226 const unsigned NumArithmeticTypes = 16;
3227 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003228 Context.BoolTy, Context.CharTy, Context.WCharTy,
3229// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003230 Context.SignedCharTy, Context.ShortTy,
3231 Context.UnsignedCharTy, Context.UnsignedShortTy,
3232 Context.IntTy, Context.LongTy, Context.LongLongTy,
3233 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3234 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3235 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003236 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3237 "Invalid first promoted integral type");
3238 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3239 == Context.UnsignedLongLongTy &&
3240 "Invalid last promoted integral type");
3241 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3242 "Invalid first promoted arithmetic type");
3243 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3244 == Context.LongDoubleTy &&
3245 "Invalid last promoted arithmetic type");
3246
Douglas Gregora11693b2008-11-12 17:17:38 +00003247 // Find all of the types that the arguments can convert to, but only
3248 // if the operator we're looking at has built-in operator candidates
3249 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003250 Qualifiers VisibleTypeConversionsQuals;
3251 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003252 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3253 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3254
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003255 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003256 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3257 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003258 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003259 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003260 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003261 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003262 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003263 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003264 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003265 true,
3266 (Op == OO_Exclaim ||
3267 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003268 Op == OO_PipePipe),
3269 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003270 }
3271
3272 bool isComparison = false;
3273 switch (Op) {
3274 case OO_None:
3275 case NUM_OVERLOADED_OPERATORS:
3276 assert(false && "Expected an overloaded operator");
3277 break;
3278
Douglas Gregord08452f2008-11-19 15:42:04 +00003279 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003280 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003281 goto UnaryStar;
3282 else
3283 goto BinaryStar;
3284 break;
3285
3286 case OO_Plus: // '+' is either unary or binary
3287 if (NumArgs == 1)
3288 goto UnaryPlus;
3289 else
3290 goto BinaryPlus;
3291 break;
3292
3293 case OO_Minus: // '-' is either unary or binary
3294 if (NumArgs == 1)
3295 goto UnaryMinus;
3296 else
3297 goto BinaryMinus;
3298 break;
3299
3300 case OO_Amp: // '&' is either unary or binary
3301 if (NumArgs == 1)
3302 goto UnaryAmp;
3303 else
3304 goto BinaryAmp;
3305
3306 case OO_PlusPlus:
3307 case OO_MinusMinus:
3308 // C++ [over.built]p3:
3309 //
3310 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3311 // is either volatile or empty, there exist candidate operator
3312 // functions of the form
3313 //
3314 // VQ T& operator++(VQ T&);
3315 // T operator++(VQ T&, int);
3316 //
3317 // C++ [over.built]p4:
3318 //
3319 // For every pair (T, VQ), where T is an arithmetic type other
3320 // than bool, and VQ is either volatile or empty, there exist
3321 // candidate operator functions of the form
3322 //
3323 // VQ T& operator--(VQ T&);
3324 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003325 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003326 Arith < NumArithmeticTypes; ++Arith) {
3327 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003328 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003329 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003330
3331 // Non-volatile version.
3332 if (NumArgs == 1)
3333 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3334 else
3335 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003336 // heuristic to reduce number of builtin candidates in the set.
3337 // Add volatile version only if there are conversions to a volatile type.
3338 if (VisibleTypeConversionsQuals.hasVolatile()) {
3339 // Volatile version
3340 ParamTypes[0]
3341 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3342 if (NumArgs == 1)
3343 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3344 else
3345 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3346 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003347 }
3348
3349 // C++ [over.built]p5:
3350 //
3351 // For every pair (T, VQ), where T is a cv-qualified or
3352 // cv-unqualified object type, and VQ is either volatile or
3353 // empty, there exist candidate operator functions of the form
3354 //
3355 // T*VQ& operator++(T*VQ&);
3356 // T*VQ& operator--(T*VQ&);
3357 // T* operator++(T*VQ&, int);
3358 // T* operator--(T*VQ&, int);
3359 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3360 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3361 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003362 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003363 continue;
3364
Mike Stump11289f42009-09-09 15:08:12 +00003365 QualType ParamTypes[2] = {
3366 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003367 };
Mike Stump11289f42009-09-09 15:08:12 +00003368
Douglas Gregord08452f2008-11-19 15:42:04 +00003369 // Without volatile
3370 if (NumArgs == 1)
3371 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3372 else
3373 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3374
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003375 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3376 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003377 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003378 ParamTypes[0]
3379 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003380 if (NumArgs == 1)
3381 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3382 else
3383 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3384 }
3385 }
3386 break;
3387
3388 UnaryStar:
3389 // C++ [over.built]p6:
3390 // For every cv-qualified or cv-unqualified object type T, there
3391 // exist candidate operator functions of the form
3392 //
3393 // T& operator*(T*);
3394 //
3395 // C++ [over.built]p7:
3396 // For every function type T, there exist candidate operator
3397 // functions of the form
3398 // T& operator*(T*);
3399 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3400 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3401 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003402 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003403 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003404 &ParamTy, Args, 1, CandidateSet);
3405 }
3406 break;
3407
3408 UnaryPlus:
3409 // C++ [over.built]p8:
3410 // For every type T, there exist candidate operator functions of
3411 // the form
3412 //
3413 // T* operator+(T*);
3414 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3415 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3416 QualType ParamTy = *Ptr;
3417 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3418 }
Mike Stump11289f42009-09-09 15:08:12 +00003419
Douglas Gregord08452f2008-11-19 15:42:04 +00003420 // Fall through
3421
3422 UnaryMinus:
3423 // C++ [over.built]p9:
3424 // For every promoted arithmetic type T, there exist candidate
3425 // operator functions of the form
3426 //
3427 // T operator+(T);
3428 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003429 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003430 Arith < LastPromotedArithmeticType; ++Arith) {
3431 QualType ArithTy = ArithmeticTypes[Arith];
3432 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3433 }
3434 break;
3435
3436 case OO_Tilde:
3437 // C++ [over.built]p10:
3438 // For every promoted integral type T, there exist candidate
3439 // operator functions of the form
3440 //
3441 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003442 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003443 Int < LastPromotedIntegralType; ++Int) {
3444 QualType IntTy = ArithmeticTypes[Int];
3445 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3446 }
3447 break;
3448
Douglas Gregora11693b2008-11-12 17:17:38 +00003449 case OO_New:
3450 case OO_Delete:
3451 case OO_Array_New:
3452 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003453 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003454 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003455 break;
3456
3457 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003458 UnaryAmp:
3459 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003460 // C++ [over.match.oper]p3:
3461 // -- For the operator ',', the unary operator '&', or the
3462 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003463 break;
3464
Douglas Gregor84605ae2009-08-24 13:43:27 +00003465 case OO_EqualEqual:
3466 case OO_ExclaimEqual:
3467 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003468 // For every pointer to member type T, there exist candidate operator
3469 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003470 //
3471 // bool operator==(T,T);
3472 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003473 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003474 MemPtr = CandidateTypes.member_pointer_begin(),
3475 MemPtrEnd = CandidateTypes.member_pointer_end();
3476 MemPtr != MemPtrEnd;
3477 ++MemPtr) {
3478 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3479 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3480 }
Mike Stump11289f42009-09-09 15:08:12 +00003481
Douglas Gregor84605ae2009-08-24 13:43:27 +00003482 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003483
Douglas Gregora11693b2008-11-12 17:17:38 +00003484 case OO_Less:
3485 case OO_Greater:
3486 case OO_LessEqual:
3487 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003488 // C++ [over.built]p15:
3489 //
3490 // For every pointer or enumeration type T, there exist
3491 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003492 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003493 // bool operator<(T, T);
3494 // bool operator>(T, T);
3495 // bool operator<=(T, T);
3496 // bool operator>=(T, T);
3497 // bool operator==(T, T);
3498 // bool operator!=(T, T);
3499 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3500 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3501 QualType ParamTypes[2] = { *Ptr, *Ptr };
3502 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3503 }
Mike Stump11289f42009-09-09 15:08:12 +00003504 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003505 = CandidateTypes.enumeration_begin();
3506 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3507 QualType ParamTypes[2] = { *Enum, *Enum };
3508 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3509 }
3510
3511 // Fall through.
3512 isComparison = true;
3513
Douglas Gregord08452f2008-11-19 15:42:04 +00003514 BinaryPlus:
3515 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003516 if (!isComparison) {
3517 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3518
3519 // C++ [over.built]p13:
3520 //
3521 // For every cv-qualified or cv-unqualified object type T
3522 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003523 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003524 // T* operator+(T*, ptrdiff_t);
3525 // T& operator[](T*, ptrdiff_t); [BELOW]
3526 // T* operator-(T*, ptrdiff_t);
3527 // T* operator+(ptrdiff_t, T*);
3528 // T& operator[](ptrdiff_t, T*); [BELOW]
3529 //
3530 // C++ [over.built]p14:
3531 //
3532 // For every T, where T is a pointer to object type, there
3533 // exist candidate operator functions of the form
3534 //
3535 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003536 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003537 = CandidateTypes.pointer_begin();
3538 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3539 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3540
3541 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3542 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3543
3544 if (Op == OO_Plus) {
3545 // T* operator+(ptrdiff_t, T*);
3546 ParamTypes[0] = ParamTypes[1];
3547 ParamTypes[1] = *Ptr;
3548 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3549 } else {
3550 // ptrdiff_t operator-(T, T);
3551 ParamTypes[1] = *Ptr;
3552 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3553 Args, 2, CandidateSet);
3554 }
3555 }
3556 }
3557 // Fall through
3558
Douglas Gregora11693b2008-11-12 17:17:38 +00003559 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003560 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003561 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003562 // C++ [over.built]p12:
3563 //
3564 // For every pair of promoted arithmetic types L and R, there
3565 // exist candidate operator functions of the form
3566 //
3567 // LR operator*(L, R);
3568 // LR operator/(L, R);
3569 // LR operator+(L, R);
3570 // LR operator-(L, R);
3571 // bool operator<(L, R);
3572 // bool operator>(L, R);
3573 // bool operator<=(L, R);
3574 // bool operator>=(L, R);
3575 // bool operator==(L, R);
3576 // bool operator!=(L, R);
3577 //
3578 // where LR is the result of the usual arithmetic conversions
3579 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003580 //
3581 // C++ [over.built]p24:
3582 //
3583 // For every pair of promoted arithmetic types L and R, there exist
3584 // candidate operator functions of the form
3585 //
3586 // LR operator?(bool, L, R);
3587 //
3588 // where LR is the result of the usual arithmetic conversions
3589 // between types L and R.
3590 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003591 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003592 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003593 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003594 Right < LastPromotedArithmeticType; ++Right) {
3595 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003596 QualType Result
3597 = isComparison
3598 ? Context.BoolTy
3599 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003600 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3601 }
3602 }
3603 break;
3604
3605 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003606 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003607 case OO_Caret:
3608 case OO_Pipe:
3609 case OO_LessLess:
3610 case OO_GreaterGreater:
3611 // C++ [over.built]p17:
3612 //
3613 // For every pair of promoted integral types L and R, there
3614 // exist candidate operator functions of the form
3615 //
3616 // LR operator%(L, R);
3617 // LR operator&(L, R);
3618 // LR operator^(L, R);
3619 // LR operator|(L, R);
3620 // L operator<<(L, R);
3621 // L operator>>(L, R);
3622 //
3623 // where LR is the result of the usual arithmetic conversions
3624 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003625 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003626 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003627 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003628 Right < LastPromotedIntegralType; ++Right) {
3629 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3630 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3631 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003632 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003633 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3634 }
3635 }
3636 break;
3637
3638 case OO_Equal:
3639 // C++ [over.built]p20:
3640 //
3641 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003642 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003643 // empty, there exist candidate operator functions of the form
3644 //
3645 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003646 for (BuiltinCandidateTypeSet::iterator
3647 Enum = CandidateTypes.enumeration_begin(),
3648 EnumEnd = CandidateTypes.enumeration_end();
3649 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003650 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003651 CandidateSet);
3652 for (BuiltinCandidateTypeSet::iterator
3653 MemPtr = CandidateTypes.member_pointer_begin(),
3654 MemPtrEnd = CandidateTypes.member_pointer_end();
3655 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003656 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003657 CandidateSet);
3658 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003659
3660 case OO_PlusEqual:
3661 case OO_MinusEqual:
3662 // C++ [over.built]p19:
3663 //
3664 // For every pair (T, VQ), where T is any type and VQ is either
3665 // volatile or empty, there exist candidate operator functions
3666 // of the form
3667 //
3668 // T*VQ& operator=(T*VQ&, T*);
3669 //
3670 // C++ [over.built]p21:
3671 //
3672 // For every pair (T, VQ), where T is a cv-qualified or
3673 // cv-unqualified object type and VQ is either volatile or
3674 // empty, there exist candidate operator functions of the form
3675 //
3676 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3677 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3678 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3679 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3680 QualType ParamTypes[2];
3681 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3682
3683 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003684 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003685 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3686 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003687
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003688 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3689 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003690 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003691 ParamTypes[0]
3692 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003693 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3694 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003695 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003696 }
3697 // Fall through.
3698
3699 case OO_StarEqual:
3700 case OO_SlashEqual:
3701 // C++ [over.built]p18:
3702 //
3703 // For every triple (L, VQ, R), where L is an arithmetic type,
3704 // VQ is either volatile or empty, and R is a promoted
3705 // arithmetic type, there exist candidate operator functions of
3706 // the form
3707 //
3708 // VQ L& operator=(VQ L&, R);
3709 // VQ L& operator*=(VQ L&, R);
3710 // VQ L& operator/=(VQ L&, R);
3711 // VQ L& operator+=(VQ L&, R);
3712 // VQ L& operator-=(VQ L&, R);
3713 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003714 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003715 Right < LastPromotedArithmeticType; ++Right) {
3716 QualType ParamTypes[2];
3717 ParamTypes[1] = ArithmeticTypes[Right];
3718
3719 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003720 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003721 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3722 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003723
3724 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003725 if (VisibleTypeConversionsQuals.hasVolatile()) {
3726 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3727 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3728 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3729 /*IsAssigmentOperator=*/Op == OO_Equal);
3730 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003731 }
3732 }
3733 break;
3734
3735 case OO_PercentEqual:
3736 case OO_LessLessEqual:
3737 case OO_GreaterGreaterEqual:
3738 case OO_AmpEqual:
3739 case OO_CaretEqual:
3740 case OO_PipeEqual:
3741 // C++ [over.built]p22:
3742 //
3743 // For every triple (L, VQ, R), where L is an integral type, VQ
3744 // is either volatile or empty, and R is a promoted integral
3745 // type, there exist candidate operator functions of the form
3746 //
3747 // VQ L& operator%=(VQ L&, R);
3748 // VQ L& operator<<=(VQ L&, R);
3749 // VQ L& operator>>=(VQ L&, R);
3750 // VQ L& operator&=(VQ L&, R);
3751 // VQ L& operator^=(VQ L&, R);
3752 // VQ L& operator|=(VQ L&, R);
3753 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003754 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003755 Right < LastPromotedIntegralType; ++Right) {
3756 QualType ParamTypes[2];
3757 ParamTypes[1] = ArithmeticTypes[Right];
3758
3759 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003760 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003761 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003762 if (VisibleTypeConversionsQuals.hasVolatile()) {
3763 // Add this built-in operator as a candidate (VQ is 'volatile').
3764 ParamTypes[0] = ArithmeticTypes[Left];
3765 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3766 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3767 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3768 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003769 }
3770 }
3771 break;
3772
Douglas Gregord08452f2008-11-19 15:42:04 +00003773 case OO_Exclaim: {
3774 // C++ [over.operator]p23:
3775 //
3776 // There also exist candidate operator functions of the form
3777 //
Mike Stump11289f42009-09-09 15:08:12 +00003778 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003779 // bool operator&&(bool, bool); [BELOW]
3780 // bool operator||(bool, bool); [BELOW]
3781 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003782 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3783 /*IsAssignmentOperator=*/false,
3784 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003785 break;
3786 }
3787
Douglas Gregora11693b2008-11-12 17:17:38 +00003788 case OO_AmpAmp:
3789 case OO_PipePipe: {
3790 // C++ [over.operator]p23:
3791 //
3792 // There also exist candidate operator functions of the form
3793 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003794 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003795 // bool operator&&(bool, bool);
3796 // bool operator||(bool, bool);
3797 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003798 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3799 /*IsAssignmentOperator=*/false,
3800 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003801 break;
3802 }
3803
3804 case OO_Subscript:
3805 // C++ [over.built]p13:
3806 //
3807 // For every cv-qualified or cv-unqualified object type T there
3808 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003809 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003810 // T* operator+(T*, ptrdiff_t); [ABOVE]
3811 // T& operator[](T*, ptrdiff_t);
3812 // T* operator-(T*, ptrdiff_t); [ABOVE]
3813 // T* operator+(ptrdiff_t, T*); [ABOVE]
3814 // T& operator[](ptrdiff_t, T*);
3815 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3816 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3817 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003818 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003819 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003820
3821 // T& operator[](T*, ptrdiff_t)
3822 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3823
3824 // T& operator[](ptrdiff_t, T*);
3825 ParamTypes[0] = ParamTypes[1];
3826 ParamTypes[1] = *Ptr;
3827 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3828 }
3829 break;
3830
3831 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003832 // C++ [over.built]p11:
3833 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3834 // C1 is the same type as C2 or is a derived class of C2, T is an object
3835 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3836 // there exist candidate operator functions of the form
3837 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3838 // where CV12 is the union of CV1 and CV2.
3839 {
3840 for (BuiltinCandidateTypeSet::iterator Ptr =
3841 CandidateTypes.pointer_begin();
3842 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3843 QualType C1Ty = (*Ptr);
3844 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003845 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003846 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003847 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003848 if (!isa<RecordType>(C1))
3849 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003850 // heuristic to reduce number of builtin candidates in the set.
3851 // Add volatile/restrict version only if there are conversions to a
3852 // volatile/restrict type.
3853 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3854 continue;
3855 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3856 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003857 }
3858 for (BuiltinCandidateTypeSet::iterator
3859 MemPtr = CandidateTypes.member_pointer_begin(),
3860 MemPtrEnd = CandidateTypes.member_pointer_end();
3861 MemPtr != MemPtrEnd; ++MemPtr) {
3862 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3863 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00003864 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003865 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3866 break;
3867 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3868 // build CV12 T&
3869 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003870 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3871 T.isVolatileQualified())
3872 continue;
3873 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3874 T.isRestrictQualified())
3875 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003876 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003877 QualType ResultTy = Context.getLValueReferenceType(T);
3878 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3879 }
3880 }
3881 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003882 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003883
3884 case OO_Conditional:
3885 // Note that we don't consider the first argument, since it has been
3886 // contextually converted to bool long ago. The candidates below are
3887 // therefore added as binary.
3888 //
3889 // C++ [over.built]p24:
3890 // For every type T, where T is a pointer or pointer-to-member type,
3891 // there exist candidate operator functions of the form
3892 //
3893 // T operator?(bool, T, T);
3894 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003895 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3896 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3897 QualType ParamTypes[2] = { *Ptr, *Ptr };
3898 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3899 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003900 for (BuiltinCandidateTypeSet::iterator Ptr =
3901 CandidateTypes.member_pointer_begin(),
3902 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3903 QualType ParamTypes[2] = { *Ptr, *Ptr };
3904 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3905 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003906 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003907 }
3908}
3909
Douglas Gregore254f902009-02-04 00:32:51 +00003910/// \brief Add function candidates found via argument-dependent lookup
3911/// to the set of overloading candidates.
3912///
3913/// This routine performs argument-dependent name lookup based on the
3914/// given function name (which may also be an operator name) and adds
3915/// all of the overload candidates found by ADL to the overload
3916/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003917void
Douglas Gregore254f902009-02-04 00:32:51 +00003918Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3919 Expr **Args, unsigned NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003920 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00003921 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003922 unsigned NumExplicitTemplateArgs,
3923 OverloadCandidateSet& CandidateSet,
3924 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003925 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003926
Douglas Gregorcabea402009-09-22 15:41:20 +00003927 // FIXME: Should we be trafficking in canonical function decls throughout?
3928
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003929 // Record all of the function candidates that we've already
3930 // added to the overload set, so that we don't add those same
3931 // candidates a second time.
3932 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3933 CandEnd = CandidateSet.end();
3934 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003935 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003936 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003937 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3938 Functions.insert(FunTmpl);
3939 }
Douglas Gregore254f902009-02-04 00:32:51 +00003940
Douglas Gregorcabea402009-09-22 15:41:20 +00003941 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00003942 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003943
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003944 // Erase all of the candidates we already knew about.
3945 // FIXME: This is suboptimal. Is there a better way?
3946 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3947 CandEnd = CandidateSet.end();
3948 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003949 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003950 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003951 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3952 Functions.erase(FunTmpl);
3953 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003954
3955 // For each of the ADL candidates we found, add it to the overload
3956 // set.
3957 for (FunctionSet::iterator Func = Functions.begin(),
3958 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00003959 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003960 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3961 if (HasExplicitTemplateArgs)
3962 continue;
3963
3964 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3965 false, false, PartialOverloading);
3966 } else
Mike Stump11289f42009-09-09 15:08:12 +00003967 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00003968 HasExplicitTemplateArgs,
3969 ExplicitTemplateArgs,
3970 NumExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003971 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00003972 }
Douglas Gregore254f902009-02-04 00:32:51 +00003973}
3974
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003975/// isBetterOverloadCandidate - Determines whether the first overload
3976/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00003977bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003978Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00003979 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003980 // Define viable functions to be better candidates than non-viable
3981 // functions.
3982 if (!Cand2.Viable)
3983 return Cand1.Viable;
3984 else if (!Cand1.Viable)
3985 return false;
3986
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003987 // C++ [over.match.best]p1:
3988 //
3989 // -- if F is a static member function, ICS1(F) is defined such
3990 // that ICS1(F) is neither better nor worse than ICS1(G) for
3991 // any function G, and, symmetrically, ICS1(G) is neither
3992 // better nor worse than ICS1(F).
3993 unsigned StartArg = 0;
3994 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3995 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003996
Douglas Gregord3cb3562009-07-07 23:38:56 +00003997 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00003998 // A viable function F1 is defined to be a better function than another
3999 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004000 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004001 unsigned NumArgs = Cand1.Conversions.size();
4002 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4003 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004004 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004005 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4006 Cand2.Conversions[ArgIdx])) {
4007 case ImplicitConversionSequence::Better:
4008 // Cand1 has a better conversion sequence.
4009 HasBetterConversion = true;
4010 break;
4011
4012 case ImplicitConversionSequence::Worse:
4013 // Cand1 can't be better than Cand2.
4014 return false;
4015
4016 case ImplicitConversionSequence::Indistinguishable:
4017 // Do nothing.
4018 break;
4019 }
4020 }
4021
Mike Stump11289f42009-09-09 15:08:12 +00004022 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004023 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004024 if (HasBetterConversion)
4025 return true;
4026
Mike Stump11289f42009-09-09 15:08:12 +00004027 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004028 // specialization, or, if not that,
4029 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4030 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4031 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004032
4033 // -- F1 and F2 are function template specializations, and the function
4034 // template for F1 is more specialized than the template for F2
4035 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004036 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004037 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4038 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004039 if (FunctionTemplateDecl *BetterTemplate
4040 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4041 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004042 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4043 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004044 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004045
Douglas Gregora1f013e2008-11-07 22:36:19 +00004046 // -- the context is an initialization by user-defined conversion
4047 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4048 // from the return type of F1 to the destination type (i.e.,
4049 // the type of the entity being initialized) is a better
4050 // conversion sequence than the standard conversion sequence
4051 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004052 if (Cand1.Function && Cand2.Function &&
4053 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004054 isa<CXXConversionDecl>(Cand2.Function)) {
4055 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4056 Cand2.FinalConversion)) {
4057 case ImplicitConversionSequence::Better:
4058 // Cand1 has a better conversion sequence.
4059 return true;
4060
4061 case ImplicitConversionSequence::Worse:
4062 // Cand1 can't be better than Cand2.
4063 return false;
4064
4065 case ImplicitConversionSequence::Indistinguishable:
4066 // Do nothing
4067 break;
4068 }
4069 }
4070
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004071 return false;
4072}
4073
Mike Stump11289f42009-09-09 15:08:12 +00004074/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004075/// within an overload candidate set.
4076///
4077/// \param CandidateSet the set of candidate functions.
4078///
4079/// \param Loc the location of the function name (or operator symbol) for
4080/// which overload resolution occurs.
4081///
Mike Stump11289f42009-09-09 15:08:12 +00004082/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004083/// function, Best points to the candidate function found.
4084///
4085/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00004086Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004087Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004088 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004089 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004090 // Find the best viable function.
4091 Best = CandidateSet.end();
4092 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4093 Cand != CandidateSet.end(); ++Cand) {
4094 if (Cand->Viable) {
4095 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4096 Best = Cand;
4097 }
4098 }
4099
4100 // If we didn't find any viable functions, abort.
4101 if (Best == CandidateSet.end())
4102 return OR_No_Viable_Function;
4103
4104 // Make sure that this function is better than every other viable
4105 // function. If not, we have an ambiguity.
4106 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4107 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004108 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004109 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004110 !isBetterOverloadCandidate(*Best, *Cand)) {
4111 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004112 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004113 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004114 }
Mike Stump11289f42009-09-09 15:08:12 +00004115
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004116 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004117 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004118 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004119 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004120 return OR_Deleted;
4121
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004122 // C++ [basic.def.odr]p2:
4123 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004124 // when referred to from a potentially-evaluated expression. [Note: this
4125 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004126 // (clause 13), user-defined conversions (12.3.2), allocation function for
4127 // placement new (5.3.4), as well as non-default initialization (8.5).
4128 if (Best->Function)
4129 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004130 return OR_Success;
4131}
4132
4133/// PrintOverloadCandidates - When overload resolution fails, prints
4134/// diagnostic messages containing the candidates in the candidate
4135/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00004136void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004137Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004138 bool OnlyViable,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004139 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004140 SourceLocation OpLoc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004141 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4142 LastCand = CandidateSet.end();
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004143 bool Reported = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004144 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004145 if (Cand->Viable || !OnlyViable) {
4146 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004147 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004148 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004149 // Deleted or "unavailable" function.
4150 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4151 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00004152 } else if (FunctionTemplateDecl *FunTmpl
4153 = Cand->Function->getPrimaryTemplate()) {
4154 // Function template specialization
4155 // FIXME: Give a better reason!
4156 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4157 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4158 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00004159 } else {
4160 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00004161 bool errReported = false;
4162 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4163 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4164 const ImplicitConversionSequence &Conversion =
4165 Cand->Conversions[i];
4166 if ((Conversion.ConversionKind !=
4167 ImplicitConversionSequence::BadConversion) ||
4168 Conversion.ConversionFunctionSet.size() == 0)
4169 continue;
4170 Diag(Cand->Function->getLocation(),
4171 diag::err_ovl_candidate_not_viable) << (i+1);
4172 errReported = true;
4173 for (int j = Conversion.ConversionFunctionSet.size()-1;
4174 j >= 0; j--) {
4175 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4176 Diag(Func->getLocation(), diag::err_ovl_candidate);
4177 }
4178 }
4179 }
4180 if (!errReported)
4181 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004182 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004183 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004184 // Desugar the type of the surrogate down to a function type,
4185 // retaining as many typedefs as possible while still showing
4186 // the function type (and, therefore, its parameter types).
4187 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004188 bool isLValueReference = false;
4189 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004190 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004191 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004192 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004193 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004194 isLValueReference = true;
4195 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004196 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004197 FnType = FnTypeRef->getPointeeType();
4198 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004199 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004200 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004201 FnType = FnTypePtr->getPointeeType();
4202 isPointer = true;
4203 }
4204 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00004205 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004206 // Reconstruct the pointer/reference as appropriate.
4207 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004208 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4209 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004210
Douglas Gregorab7897a2008-11-19 22:57:39 +00004211 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004212 << FnType;
Douglas Gregor66950a32009-09-30 21:46:01 +00004213 } else if (OnlyViable) {
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004214 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanian0fe5e032009-10-09 17:09:58 +00004215 "builtin-binary-operator-not-binary");
Fariborz Jahanian956127d2009-10-16 23:25:02 +00004216 std::string TypeStr("operator");
4217 TypeStr += Opc;
4218 TypeStr += "(";
4219 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4220 if (Cand->Conversions.size() == 1) {
4221 TypeStr += ")";
4222 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4223 }
4224 else {
4225 TypeStr += ", ";
4226 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4227 TypeStr += ")";
4228 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4229 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004230 }
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004231 else if (!Cand->Viable && !Reported) {
4232 // Non-viability might be due to ambiguous user-defined conversions,
4233 // needed for built-in operators. Report them as well, but only once
4234 // as we have typically many built-in candidates.
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004235 unsigned NoOperands = Cand->Conversions.size();
4236 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004237 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4238 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4239 ICS.ConversionFunctionSet.empty())
4240 continue;
4241 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4242 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4243 QualType FromTy =
4244 QualType(
4245 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4246 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4247 << FromTy << Func->getConversionType();
4248 }
4249 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4250 FunctionDecl *Func =
4251 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4252 Diag(Func->getLocation(),diag::err_ovl_candidate);
4253 }
4254 }
4255 Reported = true;
4256 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004257 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004258 }
4259}
4260
Douglas Gregorcd695e52008-11-10 20:40:00 +00004261/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4262/// an overloaded function (C++ [over.over]), where @p From is an
4263/// expression with overloaded function type and @p ToType is the type
4264/// we're trying to resolve to. For example:
4265///
4266/// @code
4267/// int f(double);
4268/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004269///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004270/// int (*pfd)(double) = f; // selects f(double)
4271/// @endcode
4272///
4273/// This routine returns the resulting FunctionDecl if it could be
4274/// resolved, and NULL otherwise. When @p Complain is true, this
4275/// routine will emit diagnostics if there is an error.
4276FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004277Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004278 bool Complain) {
4279 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004280 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004281 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004282 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004283 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004284 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004285 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004286 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004287 FunctionType = MemTypePtr->getPointeeType();
4288 IsMember = true;
4289 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004290
4291 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004292 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004293 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004294 return 0;
4295
4296 // Find the actual overloaded function declaration.
4297 OverloadedFunctionDecl *Ovl = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004298
Douglas Gregorcd695e52008-11-10 20:40:00 +00004299 // C++ [over.over]p1:
4300 // [...] [Note: any redundant set of parentheses surrounding the
4301 // overloaded function name is ignored (5.1). ]
4302 Expr *OvlExpr = From->IgnoreParens();
4303
4304 // C++ [over.over]p1:
4305 // [...] The overloaded function name can be preceded by the &
4306 // operator.
4307 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4308 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4309 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4310 }
4311
Anders Carlssonb68b0282009-10-20 22:53:47 +00004312 bool HasExplicitTemplateArgs = false;
John McCall0ad16662009-10-29 08:12:44 +00004313 const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004314 unsigned NumExplicitTemplateArgs = 0;
4315
Douglas Gregorcd695e52008-11-10 20:40:00 +00004316 // Try to dig out the overloaded function.
Douglas Gregor9b146582009-07-08 20:55:45 +00004317 FunctionTemplateDecl *FunctionTemplate = 0;
4318 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004319 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor9b146582009-07-08 20:55:45 +00004320 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
Douglas Gregord3319842009-10-24 04:59:53 +00004321 HasExplicitTemplateArgs = DR->hasExplicitTemplateArgumentList();
4322 ExplicitTemplateArgs = DR->getTemplateArgs();
4323 NumExplicitTemplateArgs = DR->getNumTemplateArgs();
Anders Carlsson6c966c42009-10-07 22:26:29 +00004324 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(OvlExpr)) {
4325 Ovl = dyn_cast<OverloadedFunctionDecl>(ME->getMemberDecl());
4326 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(ME->getMemberDecl());
Douglas Gregord3319842009-10-24 04:59:53 +00004327 HasExplicitTemplateArgs = ME->hasExplicitTemplateArgumentList();
4328 ExplicitTemplateArgs = ME->getTemplateArgs();
4329 NumExplicitTemplateArgs = ME->getNumTemplateArgs();
Anders Carlssonb68b0282009-10-20 22:53:47 +00004330 } else if (TemplateIdRefExpr *TIRE = dyn_cast<TemplateIdRefExpr>(OvlExpr)) {
4331 TemplateName Name = TIRE->getTemplateName();
4332 Ovl = Name.getAsOverloadedFunctionDecl();
4333 FunctionTemplate =
4334 dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4335
4336 HasExplicitTemplateArgs = true;
4337 ExplicitTemplateArgs = TIRE->getTemplateArgs();
4338 NumExplicitTemplateArgs = TIRE->getNumTemplateArgs();
Douglas Gregor9b146582009-07-08 20:55:45 +00004339 }
Anders Carlssonb68b0282009-10-20 22:53:47 +00004340
Mike Stump11289f42009-09-09 15:08:12 +00004341 // If there's no overloaded function declaration or function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00004342 // we're done.
4343 if (!Ovl && !FunctionTemplate)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004344 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004345
Douglas Gregor9b146582009-07-08 20:55:45 +00004346 OverloadIterator Fun;
4347 if (Ovl)
4348 Fun = Ovl;
4349 else
4350 Fun = FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00004351
Douglas Gregorcd695e52008-11-10 20:40:00 +00004352 // Look through all of the overloaded functions, searching for one
4353 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004354 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004355 bool FoundNonTemplateFunction = false;
Douglas Gregor9b146582009-07-08 20:55:45 +00004356 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004357 // C++ [over.over]p3:
4358 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004359 // targets of type "pointer-to-function" or "reference-to-function."
4360 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004361 // type "pointer-to-member-function."
4362 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004363
Mike Stump11289f42009-09-09 15:08:12 +00004364 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor9b146582009-07-08 20:55:45 +00004365 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump11289f42009-09-09 15:08:12 +00004366 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004367 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004368 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004369 // static when converting to member pointer.
4370 if (Method->isStatic() == IsMember)
4371 continue;
4372 } else if (IsMember)
4373 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004374
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004375 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004376 // If the name is a function template, template argument deduction is
4377 // done (14.8.2.2), and if the argument deduction succeeds, the
4378 // resulting template argument list is used to generate a single
4379 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004380 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004381 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004382 FunctionDecl *Specialization = 0;
4383 TemplateDeductionInfo Info(Context);
4384 if (TemplateDeductionResult Result
Anders Carlssonb68b0282009-10-20 22:53:47 +00004385 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
4386 ExplicitTemplateArgs,
4387 NumExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00004388 FunctionType, Specialization, Info)) {
4389 // FIXME: make a note of the failed deduction for diagnostics.
4390 (void)Result;
4391 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004392 // FIXME: If the match isn't exact, shouldn't we just drop this as
4393 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004394 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004395 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004396 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004397 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004398 }
4399 }
Mike Stump11289f42009-09-09 15:08:12 +00004400
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004401 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4402 // Skip non-static functions when converting to pointer, and static
4403 // when converting to member pointer.
4404 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004405 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004406
4407 // If we have explicit template arguments, skip non-templates.
4408 if (HasExplicitTemplateArgs)
4409 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004410 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004411 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004412
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004413 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004414 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004415 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004416 FoundNonTemplateFunction = true;
4417 }
Mike Stump11289f42009-09-09 15:08:12 +00004418 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004419 }
4420
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004421 // If there were 0 or 1 matches, we're done.
4422 if (Matches.empty())
4423 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004424 else if (Matches.size() == 1) {
4425 FunctionDecl *Result = *Matches.begin();
4426 MarkDeclarationReferenced(From->getLocStart(), Result);
4427 return Result;
4428 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004429
4430 // C++ [over.over]p4:
4431 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004432 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004433 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004434 // [...] and any given function template specialization F1 is
4435 // eliminated if the set contains a second function template
4436 // specialization whose function template is more specialized
4437 // than the function template of F1 according to the partial
4438 // ordering rules of 14.5.5.2.
4439
4440 // The algorithm specified above is quadratic. We instead use a
4441 // two-pass algorithm (similar to the one used to identify the
4442 // best viable function in an overload set) that identifies the
4443 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004444 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004445 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004446 FunctionDecl *Result =
4447 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4448 TPOC_Other, From->getLocStart(),
4449 PDiag(),
4450 PDiag(diag::err_addr_ovl_ambiguous)
4451 << TemplateMatches[0]->getDeclName(),
4452 PDiag(diag::err_ovl_template_candidate));
4453 MarkDeclarationReferenced(From->getLocStart(), Result);
4454 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004455 }
Mike Stump11289f42009-09-09 15:08:12 +00004456
Douglas Gregorfae1d712009-09-26 03:56:17 +00004457 // [...] any function template specializations in the set are
4458 // eliminated if the set also contains a non-template function, [...]
4459 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4460 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4461 if ((*M)->getPrimaryTemplate() == 0)
4462 RemainingMatches.push_back(*M);
4463
Mike Stump11289f42009-09-09 15:08:12 +00004464 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004465 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004466 if (RemainingMatches.size() == 1) {
4467 FunctionDecl *Result = RemainingMatches.front();
4468 MarkDeclarationReferenced(From->getLocStart(), Result);
4469 return Result;
4470 }
Mike Stump11289f42009-09-09 15:08:12 +00004471
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004472 // FIXME: We should probably return the same thing that BestViableFunction
4473 // returns (even if we issue the diagnostics here).
4474 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4475 << RemainingMatches[0]->getDeclName();
4476 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4477 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004478 return 0;
4479}
4480
Douglas Gregorcabea402009-09-22 15:41:20 +00004481/// \brief Add a single candidate to the overload set.
4482static void AddOverloadedCallCandidate(Sema &S,
4483 AnyFunctionDecl Callee,
4484 bool &ArgumentDependentLookup,
4485 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00004486 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004487 unsigned NumExplicitTemplateArgs,
4488 Expr **Args, unsigned NumArgs,
4489 OverloadCandidateSet &CandidateSet,
4490 bool PartialOverloading) {
4491 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4492 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4493 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4494 PartialOverloading);
4495
4496 if (Func->getDeclContext()->isRecord() ||
4497 Func->getDeclContext()->isFunctionOrMethod())
4498 ArgumentDependentLookup = false;
4499 return;
4500 }
4501
4502 FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4503 S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4504 ExplicitTemplateArgs,
4505 NumExplicitTemplateArgs,
4506 Args, NumArgs, CandidateSet);
4507
4508 if (FuncTemplate->getDeclContext()->isRecord())
4509 ArgumentDependentLookup = false;
4510}
4511
4512/// \brief Add the overload candidates named by callee and/or found by argument
4513/// dependent lookup to the given overload set.
4514void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4515 DeclarationName &UnqualifiedName,
4516 bool &ArgumentDependentLookup,
4517 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00004518 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004519 unsigned NumExplicitTemplateArgs,
4520 Expr **Args, unsigned NumArgs,
4521 OverloadCandidateSet &CandidateSet,
4522 bool PartialOverloading) {
4523 // Add the functions denoted by Callee to the set of candidate
4524 // functions. While we're doing so, track whether argument-dependent
4525 // lookup still applies, per:
4526 //
4527 // C++0x [basic.lookup.argdep]p3:
4528 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4529 // and let Y be the lookup set produced by argument dependent
4530 // lookup (defined as follows). If X contains
4531 //
4532 // -- a declaration of a class member, or
4533 //
4534 // -- a block-scope function declaration that is not a
4535 // using-declaration (FIXME: check for using declaration), or
4536 //
4537 // -- a declaration that is neither a function or a function
4538 // template
4539 //
4540 // then Y is empty.
4541 if (!Callee) {
4542 // Nothing to do.
4543 } else if (OverloadedFunctionDecl *Ovl
4544 = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4545 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4546 FuncEnd = Ovl->function_end();
4547 Func != FuncEnd; ++Func)
4548 AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4549 HasExplicitTemplateArgs,
4550 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4551 Args, NumArgs, CandidateSet,
4552 PartialOverloading);
4553 } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4554 AddOverloadedCallCandidate(*this,
4555 AnyFunctionDecl::getFromNamedDecl(Callee),
4556 ArgumentDependentLookup,
4557 HasExplicitTemplateArgs,
4558 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4559 Args, NumArgs, CandidateSet,
4560 PartialOverloading);
4561 // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4562 // checking dynamically.
4563
4564 if (Callee)
4565 UnqualifiedName = Callee->getDeclName();
4566
4567 if (ArgumentDependentLookup)
4568 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4569 HasExplicitTemplateArgs,
4570 ExplicitTemplateArgs,
4571 NumExplicitTemplateArgs,
4572 CandidateSet,
4573 PartialOverloading);
4574}
4575
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004576/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004577/// (which eventually refers to the declaration Func) and the call
4578/// arguments Args/NumArgs, attempt to resolve the function call down
4579/// to a specific function. If overload resolution succeeds, returns
4580/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004581/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004582/// arguments and Fn, and returns NULL.
Douglas Gregore254f902009-02-04 00:32:51 +00004583FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004584 DeclarationName UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00004585 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00004586 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004587 unsigned NumExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004588 SourceLocation LParenLoc,
4589 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004590 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004591 SourceLocation RParenLoc,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004592 bool &ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004593 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004594
4595 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004596 // functions.
4597 AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4598 HasExplicitTemplateArgs, ExplicitTemplateArgs,
4599 NumExplicitTemplateArgs, Args, NumArgs,
4600 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004601 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004602 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004603 case OR_Success:
4604 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004605
4606 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004607 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004608 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004609 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004610 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4611 break;
4612
4613 case OR_Ambiguous:
4614 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004615 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004616 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4617 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004618
4619 case OR_Deleted:
4620 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4621 << Best->Function->isDeleted()
4622 << UnqualifiedName
4623 << Fn->getSourceRange();
4624 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4625 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004626 }
4627
4628 // Overload resolution failed. Destroy all of the subexpressions and
4629 // return NULL.
4630 Fn->Destroy(Context);
4631 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4632 Args[Arg]->Destroy(Context);
4633 return 0;
4634}
4635
Douglas Gregor084d8552009-03-13 23:49:33 +00004636/// \brief Create a unary operation that may resolve to an overloaded
4637/// operator.
4638///
4639/// \param OpLoc The location of the operator itself (e.g., '*').
4640///
4641/// \param OpcIn The UnaryOperator::Opcode that describes this
4642/// operator.
4643///
4644/// \param Functions The set of non-member functions that will be
4645/// considered by overload resolution. The caller needs to build this
4646/// set based on the context using, e.g.,
4647/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4648/// set should not contain any member functions; those will be added
4649/// by CreateOverloadedUnaryOp().
4650///
4651/// \param input The input argument.
4652Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4653 unsigned OpcIn,
4654 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004655 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004656 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4657 Expr *Input = (Expr *)input.get();
4658
4659 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4660 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4661 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4662
4663 Expr *Args[2] = { Input, 0 };
4664 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004665
Douglas Gregor084d8552009-03-13 23:49:33 +00004666 // For post-increment and post-decrement, add the implicit '0' as
4667 // the second argument, so that we know this is a post-increment or
4668 // post-decrement.
4669 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4670 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004671 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004672 SourceLocation());
4673 NumArgs = 2;
4674 }
4675
4676 if (Input->isTypeDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00004677 OverloadedFunctionDecl *Overloads
Douglas Gregor084d8552009-03-13 23:49:33 +00004678 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004679 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004680 FuncEnd = Functions.end();
4681 Func != FuncEnd; ++Func)
4682 Overloads->addOverload(*Func);
4683
4684 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4685 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004686
Douglas Gregor084d8552009-03-13 23:49:33 +00004687 input.release();
4688 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4689 &Args[0], NumArgs,
4690 Context.DependentTy,
4691 OpLoc));
4692 }
4693
4694 // Build an empty overload set.
4695 OverloadCandidateSet CandidateSet;
4696
4697 // Add the candidates from the given function set.
4698 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4699
4700 // Add operator candidates that are member functions.
4701 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4702
4703 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004704 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00004705
4706 // Perform overload resolution.
4707 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004708 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004709 case OR_Success: {
4710 // We found a built-in operator or an overloaded operator.
4711 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004712
Douglas Gregor084d8552009-03-13 23:49:33 +00004713 if (FnDecl) {
4714 // We matched an overloaded operator. Build a call to that
4715 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004716
Douglas Gregor084d8552009-03-13 23:49:33 +00004717 // Convert the arguments.
4718 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4719 if (PerformObjectArgumentInitialization(Input, Method))
4720 return ExprError();
4721 } else {
4722 // Convert the arguments.
4723 if (PerformCopyInitialization(Input,
4724 FnDecl->getParamDecl(0)->getType(),
4725 "passing"))
4726 return ExprError();
4727 }
4728
4729 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004730 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004731
Douglas Gregor084d8552009-03-13 23:49:33 +00004732 // Build the actual expression node.
4733 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4734 SourceLocation());
4735 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004736
Douglas Gregor084d8552009-03-13 23:49:33 +00004737 input.release();
Mike Stump11289f42009-09-09 15:08:12 +00004738
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004739 ExprOwningPtr<CallExpr> TheCall(this,
4740 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4741 &Input, 1, ResultTy, OpLoc));
4742
4743 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4744 FnDecl))
4745 return ExprError();
4746
4747 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00004748 } else {
4749 // We matched a built-in operator. Convert the arguments, then
4750 // break out so that we will build the appropriate built-in
4751 // operator node.
4752 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4753 Best->Conversions[0], "passing"))
4754 return ExprError();
4755
4756 break;
4757 }
4758 }
4759
4760 case OR_No_Viable_Function:
4761 // No viable function; fall through to handling this as a
4762 // built-in operator, which will produce an error message for us.
4763 break;
4764
4765 case OR_Ambiguous:
4766 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4767 << UnaryOperator::getOpcodeStr(Opc)
4768 << Input->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004769 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4770 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00004771 return ExprError();
4772
4773 case OR_Deleted:
4774 Diag(OpLoc, diag::err_ovl_deleted_oper)
4775 << Best->Function->isDeleted()
4776 << UnaryOperator::getOpcodeStr(Opc)
4777 << Input->getSourceRange();
4778 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4779 return ExprError();
4780 }
4781
4782 // Either we found no viable overloaded operator or we matched a
4783 // built-in operator. In either case, fall through to trying to
4784 // build a built-in operation.
4785 input.release();
4786 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4787}
4788
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004789/// \brief Create a binary operation that may resolve to an overloaded
4790/// operator.
4791///
4792/// \param OpLoc The location of the operator itself (e.g., '+').
4793///
4794/// \param OpcIn The BinaryOperator::Opcode that describes this
4795/// operator.
4796///
4797/// \param Functions The set of non-member functions that will be
4798/// considered by overload resolution. The caller needs to build this
4799/// set based on the context using, e.g.,
4800/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4801/// set should not contain any member functions; those will be added
4802/// by CreateOverloadedBinOp().
4803///
4804/// \param LHS Left-hand argument.
4805/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004806Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004807Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004808 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004809 FunctionSet &Functions,
4810 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004811 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004812 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004813
4814 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4815 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4816 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4817
4818 // If either side is type-dependent, create an appropriate dependent
4819 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004820 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00004821 if (Functions.empty()) {
4822 // If there are no functions to store, just build a dependent
4823 // BinaryOperator or CompoundAssignment.
4824 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4825 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4826 Context.DependentTy, OpLoc));
4827
4828 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4829 Context.DependentTy,
4830 Context.DependentTy,
4831 Context.DependentTy,
4832 OpLoc));
4833 }
4834
Mike Stump11289f42009-09-09 15:08:12 +00004835 OverloadedFunctionDecl *Overloads
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004836 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004837 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004838 FuncEnd = Functions.end();
4839 Func != FuncEnd; ++Func)
4840 Overloads->addOverload(*Func);
4841
4842 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4843 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004844
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004845 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004846 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004847 Context.DependentTy,
4848 OpLoc));
4849 }
4850
4851 // If this is the .* operator, which is not overloadable, just
4852 // create a built-in binary operator.
4853 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004854 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004855
4856 // If this is one of the assignment operators, we only perform
4857 // overload resolution if the left-hand side is a class or
4858 // enumeration type (C++ [expr.ass]p3).
4859 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregore9899d92009-08-26 17:08:25 +00004860 !Args[0]->getType()->isOverloadableType())
4861 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004862
Douglas Gregor084d8552009-03-13 23:49:33 +00004863 // Build an empty overload set.
4864 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004865
4866 // Add the candidates from the given function set.
4867 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4868
4869 // Add operator candidates that are member functions.
4870 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4871
4872 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004873 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004874
4875 // Perform overload resolution.
4876 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004877 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004878 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004879 // We found a built-in operator or an overloaded operator.
4880 FunctionDecl *FnDecl = Best->Function;
4881
4882 if (FnDecl) {
4883 // We matched an overloaded operator. Build a call to that
4884 // operator.
4885
4886 // Convert the arguments.
4887 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004888 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4889 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004890 "passing"))
4891 return ExprError();
4892 } else {
4893 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004894 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004895 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004896 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004897 "passing"))
4898 return ExprError();
4899 }
4900
4901 // Determine the result type
4902 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004903 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004904 ResultTy = ResultTy.getNonReferenceType();
4905
4906 // Build the actual expression node.
4907 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004908 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004909 UsualUnaryConversions(FnExpr);
4910
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00004911 ExprOwningPtr<CXXOperatorCallExpr>
4912 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4913 Args, 2, ResultTy,
4914 OpLoc));
4915
4916 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4917 FnDecl))
4918 return ExprError();
4919
4920 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004921 } else {
4922 // We matched a built-in operator. Convert the arguments, then
4923 // break out so that we will build the appropriate built-in
4924 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004925 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004926 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004927 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004928 Best->Conversions[1], "passing"))
4929 return ExprError();
4930
4931 break;
4932 }
4933 }
4934
Douglas Gregor66950a32009-09-30 21:46:01 +00004935 case OR_No_Viable_Function: {
4936 // C++ [over.match.oper]p9:
4937 // If the operator is the operator , [...] and there are no
4938 // viable functions, then the operator is assumed to be the
4939 // built-in operator and interpreted according to clause 5.
4940 if (Opc == BinaryOperator::Comma)
4941 break;
4942
Sebastian Redl027de2a2009-05-21 11:50:50 +00004943 // For class as left operand for assignment or compound assigment operator
4944 // do not fall through to handling in built-in, but report that no overloaded
4945 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00004946 OwningExprResult Result = ExprError();
4947 if (Args[0]->getType()->isRecordType() &&
4948 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004949 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4950 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004951 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00004952 } else {
4953 // No viable function; try to create a built-in operation, which will
4954 // produce an error. Then, show the non-viable candidates.
4955 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00004956 }
Douglas Gregor66950a32009-09-30 21:46:01 +00004957 assert(Result.isInvalid() &&
4958 "C++ binary operator overloading is missing candidates!");
4959 if (Result.isInvalid())
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004960 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
4961 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00004962 return move(Result);
4963 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004964
4965 case OR_Ambiguous:
4966 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4967 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004968 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004969 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4970 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004971 return ExprError();
4972
4973 case OR_Deleted:
4974 Diag(OpLoc, diag::err_ovl_deleted_oper)
4975 << Best->Function->isDeleted()
4976 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004977 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004978 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4979 return ExprError();
4980 }
4981
Douglas Gregor66950a32009-09-30 21:46:01 +00004982 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00004983 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004984}
4985
Sebastian Redladba46e2009-10-29 20:17:01 +00004986Action::OwningExprResult
4987Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
4988 SourceLocation RLoc,
4989 ExprArg Base, ExprArg Idx) {
4990 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
4991 static_cast<Expr*>(Idx.get()) };
4992 DeclarationName OpName =
4993 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
4994
4995 // If either side is type-dependent, create an appropriate dependent
4996 // expression.
4997 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
4998
4999 OverloadedFunctionDecl *Overloads
5000 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
5001
5002 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
5003 LLoc, false, false);
5004
5005 Base.release();
5006 Idx.release();
5007 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5008 Args, 2,
5009 Context.DependentTy,
5010 RLoc));
5011 }
5012
5013 // Build an empty overload set.
5014 OverloadCandidateSet CandidateSet;
5015
5016 // Subscript can only be overloaded as a member function.
5017
5018 // Add operator candidates that are member functions.
5019 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5020
5021 // Add builtin operator candidates.
5022 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5023
5024 // Perform overload resolution.
5025 OverloadCandidateSet::iterator Best;
5026 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5027 case OR_Success: {
5028 // We found a built-in operator or an overloaded operator.
5029 FunctionDecl *FnDecl = Best->Function;
5030
5031 if (FnDecl) {
5032 // We matched an overloaded operator. Build a call to that
5033 // operator.
5034
5035 // Convert the arguments.
5036 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5037 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5038 PerformCopyInitialization(Args[1],
5039 FnDecl->getParamDecl(0)->getType(),
5040 "passing"))
5041 return ExprError();
5042
5043 // Determine the result type
5044 QualType ResultTy
5045 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5046 ResultTy = ResultTy.getNonReferenceType();
5047
5048 // Build the actual expression node.
5049 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5050 LLoc);
5051 UsualUnaryConversions(FnExpr);
5052
5053 Base.release();
5054 Idx.release();
5055 ExprOwningPtr<CXXOperatorCallExpr>
5056 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5057 FnExpr, Args, 2,
5058 ResultTy, RLoc));
5059
5060 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5061 FnDecl))
5062 return ExprError();
5063
5064 return MaybeBindToTemporary(TheCall.release());
5065 } else {
5066 // We matched a built-in operator. Convert the arguments, then
5067 // break out so that we will build the appropriate built-in
5068 // operator node.
5069 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5070 Best->Conversions[0], "passing") ||
5071 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5072 Best->Conversions[1], "passing"))
5073 return ExprError();
5074
5075 break;
5076 }
5077 }
5078
5079 case OR_No_Viable_Function: {
5080 // No viable function; try to create a built-in operation, which will
5081 // produce an error. Then, show the non-viable candidates.
5082 OwningExprResult Result =
5083 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5084 assert(Result.isInvalid() &&
5085 "C++ subscript operator overloading is missing candidates!");
5086 if (Result.isInvalid())
5087 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5088 "[]", LLoc);
5089 return move(Result);
5090 }
5091
5092 case OR_Ambiguous:
5093 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5094 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5095 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5096 "[]", LLoc);
5097 return ExprError();
5098
5099 case OR_Deleted:
5100 Diag(LLoc, diag::err_ovl_deleted_oper)
5101 << Best->Function->isDeleted() << "[]"
5102 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5103 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5104 return ExprError();
5105 }
5106
5107 // We matched a built-in operator; build it.
5108 Base.release();
5109 Idx.release();
5110 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5111 Owned(Args[1]), RLoc);
5112}
5113
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005114/// BuildCallToMemberFunction - Build a call to a member
5115/// function. MemExpr is the expression that refers to the member
5116/// function (and includes the object parameter), Args/NumArgs are the
5117/// arguments to the function call (not including the object
5118/// parameter). The caller needs to validate that the member
5119/// expression refers to a member function or an overloaded member
5120/// function.
5121Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005122Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5123 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005124 unsigned NumArgs, SourceLocation *CommaLocs,
5125 SourceLocation RParenLoc) {
5126 // Dig out the member expression. This holds both the object
5127 // argument and the member function we're referring to.
5128 MemberExpr *MemExpr = 0;
5129 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
5130 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
5131 else
5132 MemExpr = dyn_cast<MemberExpr>(MemExprE);
5133 assert(MemExpr && "Building member call without member expression");
5134
5135 // Extract the object argument.
5136 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005137
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005138 CXXMethodDecl *Method = 0;
Douglas Gregor97628d62009-08-21 00:16:32 +00005139 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
5140 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005141 // Add overload candidates
5142 OverloadCandidateSet CandidateSet;
Douglas Gregor97628d62009-08-21 00:16:32 +00005143 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005144
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005145 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
5146 Func != FuncEnd; ++Func) {
Douglas Gregord3319842009-10-24 04:59:53 +00005147 if ((Method = dyn_cast<CXXMethodDecl>(*Func))) {
5148 // If explicit template arguments were provided, we can't call a
5149 // non-template member function.
5150 if (MemExpr->hasExplicitTemplateArgumentList())
5151 continue;
5152
Mike Stump11289f42009-09-09 15:08:12 +00005153 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005154 /*SuppressUserConversions=*/false);
Douglas Gregord3319842009-10-24 04:59:53 +00005155 } else
Douglas Gregor84f14dd2009-09-01 00:37:14 +00005156 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
5157 MemExpr->hasExplicitTemplateArgumentList(),
5158 MemExpr->getTemplateArgs(),
5159 MemExpr->getNumTemplateArgs(),
5160 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005161 CandidateSet,
5162 /*SuppressUsedConversions=*/false);
5163 }
Mike Stump11289f42009-09-09 15:08:12 +00005164
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005165 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005166 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005167 case OR_Success:
5168 Method = cast<CXXMethodDecl>(Best->Function);
5169 break;
5170
5171 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005172 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005173 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005174 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005175 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5176 // FIXME: Leaking incoming expressions!
5177 return true;
5178
5179 case OR_Ambiguous:
Mike Stump11289f42009-09-09 15:08:12 +00005180 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005181 diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005182 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005183 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5184 // FIXME: Leaking incoming expressions!
5185 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005186
5187 case OR_Deleted:
Mike Stump11289f42009-09-09 15:08:12 +00005188 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00005189 diag::err_ovl_deleted_member_call)
5190 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005191 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005192 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5193 // FIXME: Leaking incoming expressions!
5194 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005195 }
5196
5197 FixOverloadedFunctionReference(MemExpr, Method);
5198 } else {
5199 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5200 }
5201
5202 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005203 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005204 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005205 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005206 Method->getResultType().getNonReferenceType(),
5207 RParenLoc));
5208
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005209 // Check for a valid return type.
5210 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5211 TheCall.get(), Method))
5212 return true;
5213
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005214 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00005215 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005216 PerformObjectArgumentInitialization(ObjectArg, Method))
5217 return true;
5218 MemExpr->setBase(ObjectArg);
5219
5220 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005221 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005222 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005223 RParenLoc))
5224 return true;
5225
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005226 if (CheckFunctionCall(Method, TheCall.get()))
5227 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00005228
5229 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005230}
5231
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005232/// BuildCallToObjectOfClassType - Build a call to an object of class
5233/// type (C++ [over.call.object]), which can end up invoking an
5234/// overloaded function call operator (@c operator()) or performing a
5235/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005236Sema::ExprResult
5237Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005238 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005239 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005240 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005241 SourceLocation RParenLoc) {
5242 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005243 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005244
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005245 // C++ [over.call.object]p1:
5246 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005247 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005248 // candidate functions includes at least the function call
5249 // operators of T. The function call operators of T are obtained by
5250 // ordinary lookup of the name operator() in the context of
5251 // (E).operator().
5252 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005253 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor55297ac2008-12-23 00:26:44 +00005254 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005255 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor358e7742009-11-07 17:23:56 +00005256 Oper != OperEnd; ++Oper) {
5257 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Oper)) {
5258 AddMethodTemplateCandidate(FunTmpl, false, 0, 0, Object, Args, NumArgs,
5259 CandidateSet,
5260 /*SuppressUserConversions=*/false);
5261 continue;
5262 }
5263
Mike Stump11289f42009-09-09 15:08:12 +00005264 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor55297ac2008-12-23 00:26:44 +00005265 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005266 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005267
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005268 if (RequireCompleteType(LParenLoc, Object->getType(),
5269 PartialDiagnostic(diag::err_incomplete_object_call)
5270 << Object->getSourceRange()))
5271 return true;
5272
Douglas Gregorab7897a2008-11-19 22:57:39 +00005273 // C++ [over.call.object]p2:
5274 // In addition, for each conversion function declared in T of the
5275 // form
5276 //
5277 // operator conversion-type-id () cv-qualifier;
5278 //
5279 // where cv-qualifier is the same cv-qualification as, or a
5280 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005281 // denotes the type "pointer to function of (P1,...,Pn) returning
5282 // R", or the type "reference to pointer to function of
5283 // (P1,...,Pn) returning R", or the type "reference to function
5284 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005285 // is also considered as a candidate function. Similarly,
5286 // surrogate call functions are added to the set of candidate
5287 // functions for each conversion function declared in an
5288 // accessible base class provided the function is not hidden
5289 // within T by another intervening declaration.
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005290 // FIXME: Look in base classes for more conversion operators!
5291 OverloadedFunctionDecl *Conversions
5292 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
5293 for (OverloadedFunctionDecl::function_iterator
5294 Func = Conversions->function_begin(),
5295 FuncEnd = Conversions->function_end();
5296 Func != FuncEnd; ++Func) {
5297 CXXConversionDecl *Conv;
5298 FunctionTemplateDecl *ConvTemplate;
5299 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Mike Stump11289f42009-09-09 15:08:12 +00005300
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005301 // Skip over templated conversion functions; they aren't
5302 // surrogates.
5303 if (ConvTemplate)
5304 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005305
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005306 // Strip the reference type (if any) and then the pointer type (if
5307 // any) to get down to what might be a function type.
5308 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5309 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5310 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005311
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005312 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
5313 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005314 }
Mike Stump11289f42009-09-09 15:08:12 +00005315
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005316 // Perform overload resolution.
5317 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005318 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005319 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005320 // Overload resolution succeeded; we'll build the appropriate call
5321 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005322 break;
5323
5324 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005325 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00005326 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00005327 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00005328 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005329 break;
5330
5331 case OR_Ambiguous:
5332 Diag(Object->getSourceRange().getBegin(),
5333 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005334 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005335 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5336 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005337
5338 case OR_Deleted:
5339 Diag(Object->getSourceRange().getBegin(),
5340 diag::err_ovl_deleted_object_call)
5341 << Best->Function->isDeleted()
5342 << Object->getType() << Object->getSourceRange();
5343 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5344 break;
Mike Stump11289f42009-09-09 15:08:12 +00005345 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005346
Douglas Gregorab7897a2008-11-19 22:57:39 +00005347 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005348 // We had an error; delete all of the subexpressions and return
5349 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005350 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005351 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005352 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005353 return true;
5354 }
5355
Douglas Gregorab7897a2008-11-19 22:57:39 +00005356 if (Best->Function == 0) {
5357 // Since there is no function declaration, this is one of the
5358 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00005359 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00005360 = cast<CXXConversionDecl>(
5361 Best->Conversions[0].UserDefined.ConversionFunction);
5362
5363 // We selected one of the surrogate functions that converts the
5364 // object parameter to a function pointer. Perform the conversion
5365 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005366
5367 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005368 // and then call it.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005369 CXXMemberCallExpr *CE =
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005370 BuildCXXMemberCallExpr(Object, Conv);
5371
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005372 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005373 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5374 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005375 }
5376
5377 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5378 // that calls this method, using Object for the implicit object
5379 // parameter and passing along the remaining arguments.
5380 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00005381 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005382
5383 unsigned NumArgsInProto = Proto->getNumArgs();
5384 unsigned NumArgsToCheck = NumArgs;
5385
5386 // Build the full argument list for the method call (the
5387 // implicit object parameter is placed at the beginning of the
5388 // list).
5389 Expr **MethodArgs;
5390 if (NumArgs < NumArgsInProto) {
5391 NumArgsToCheck = NumArgsInProto;
5392 MethodArgs = new Expr*[NumArgsInProto + 1];
5393 } else {
5394 MethodArgs = new Expr*[NumArgs + 1];
5395 }
5396 MethodArgs[0] = Object;
5397 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5398 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00005399
5400 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00005401 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005402 UsualUnaryConversions(NewFn);
5403
5404 // Once we've built TheCall, all of the expressions are properly
5405 // owned.
5406 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005407 ExprOwningPtr<CXXOperatorCallExpr>
5408 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005409 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005410 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005411 delete [] MethodArgs;
5412
Anders Carlsson3d5829c2009-10-13 21:49:31 +00005413 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5414 Method))
5415 return true;
5416
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005417 // We may have default arguments. If so, we need to allocate more
5418 // slots in the call for them.
5419 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005420 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005421 else if (NumArgs > NumArgsInProto)
5422 NumArgsToCheck = NumArgsInProto;
5423
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005424 bool IsError = false;
5425
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005426 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005427 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005428 TheCall->setArg(0, Object);
5429
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005430
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005431 // Check the argument types.
5432 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005433 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005434 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005435 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00005436
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005437 // Pass the argument.
5438 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005439 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005440 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00005441 OwningExprResult DefArg
5442 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5443 if (DefArg.isInvalid()) {
5444 IsError = true;
5445 break;
5446 }
5447
5448 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005449 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005450
5451 TheCall->setArg(i + 1, Arg);
5452 }
5453
5454 // If this is a variadic call, handle args passed through "...".
5455 if (Proto->isVariadic()) {
5456 // Promote the arguments (C99 6.5.2.2p7).
5457 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5458 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005459 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005460 TheCall->setArg(i + 1, Arg);
5461 }
5462 }
5463
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005464 if (IsError) return true;
5465
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005466 if (CheckFunctionCall(Method, TheCall.get()))
5467 return true;
5468
Anders Carlsson1c83deb2009-08-16 03:53:54 +00005469 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005470}
5471
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005472/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00005473/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005474/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00005475Sema::OwningExprResult
5476Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5477 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005478 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00005479
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005480 // C++ [over.ref]p1:
5481 //
5482 // [...] An expression x->m is interpreted as (x.operator->())->m
5483 // for a class object x of type T if T::operator->() exists and if
5484 // the operator is selected as the best match function by the
5485 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005486 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5487 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005488 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00005489
John McCall9f3059a2009-10-09 21:13:30 +00005490 LookupResult R;
5491 LookupQualifiedName(R, BaseRecord->getDecl(), OpName, LookupOrdinaryName);
Anders Carlsson78b54932009-09-10 23:18:36 +00005492
5493 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5494 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00005495 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005496 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005497
5498 // Perform overload resolution.
5499 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005500 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005501 case OR_Success:
5502 // Overload resolution succeeded; we'll build the call below.
5503 break;
5504
5505 case OR_No_Viable_Function:
5506 if (CandidateSet.empty())
5507 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00005508 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005509 else
5510 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00005511 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005512 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00005513 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005514
5515 case OR_Ambiguous:
5516 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005517 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005518 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005519 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005520
5521 case OR_Deleted:
5522 Diag(OpLoc, diag::err_ovl_deleted_oper)
5523 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005524 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005525 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005526 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005527 }
5528
5529 // Convert the object parameter.
5530 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005531 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005532 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005533
5534 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005535 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005536
5537 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005538 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5539 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005540 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005541
5542 QualType ResultTy = Method->getResultType().getNonReferenceType();
5543 ExprOwningPtr<CXXOperatorCallExpr>
5544 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5545 &Base, 1, ResultTy, OpLoc));
5546
5547 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5548 Method))
5549 return ExprError();
5550 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005551}
5552
Douglas Gregorcd695e52008-11-10 20:40:00 +00005553/// FixOverloadedFunctionReference - E is an expression that refers to
5554/// a C++ overloaded function (possibly with some parentheses and
5555/// perhaps a '&' around it). We have resolved the overloaded function
5556/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005557/// refer (possibly indirectly) to Fn. Returns the new expr.
5558Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005559 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005560 Expr *NewExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00005561 PE->setSubExpr(NewExpr);
5562 PE->setType(NewExpr->getType());
5563 } else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5564 Expr *NewExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
5565 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
5566 NewExpr->getType()) &&
5567 "Implicit cast type cannot be determined from overload");
5568 ICE->setSubExpr(NewExpr);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005569 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005570 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005571 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005572 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5573 if (Method->isStatic()) {
5574 // Do nothing: static member functions aren't any different
5575 // from non-member functions.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005576 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr())) {
5577 if (DRE->getQualifier()) {
5578 // We have taken the address of a pointer to member
5579 // function. Perform the computation here so that we get the
5580 // appropriate pointer to member type.
5581 DRE->setDecl(Fn);
5582 DRE->setType(Fn->getType());
5583 QualType ClassType
5584 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5585 E->setType(Context.getMemberPointerType(Fn->getType(),
5586 ClassType.getTypePtr()));
5587 return E;
5588 }
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005589 }
Douglas Gregor6a573fe2009-10-22 18:02:20 +00005590 // FIXME: TemplateIdRefExpr referring to a member function template
5591 // specialization!
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005592 }
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005593 Expr *NewExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5594 UnOp->setSubExpr(NewExpr);
5595 UnOp->setType(Context.getPointerType(NewExpr->getType()));
5596
5597 return UnOp;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005598 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor9b146582009-07-08 20:55:45 +00005599 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Douglas Gregor091f0422009-10-23 22:18:25 +00005600 isa<FunctionTemplateDecl>(DR->getDecl()) ||
5601 isa<FunctionDecl>(DR->getDecl())) &&
5602 "Expected function or function template");
Douglas Gregorcd695e52008-11-10 20:40:00 +00005603 DR->setDecl(Fn);
5604 E->setType(Fn->getType());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005605 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5606 MemExpr->setMemberDecl(Fn);
5607 E->setType(Fn->getType());
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005608 } else if (TemplateIdRefExpr *TID = dyn_cast<TemplateIdRefExpr>(E)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005609 E = DeclRefExpr::Create(Context,
5610 TID->getQualifier(), TID->getQualifierRange(),
5611 Fn, TID->getTemplateNameLoc(),
5612 true,
5613 TID->getLAngleLoc(),
5614 TID->getTemplateArgs(),
5615 TID->getNumTemplateArgs(),
5616 TID->getRAngleLoc(),
5617 Fn->getType(),
5618 /*FIXME?*/false, /*FIXME?*/false);
Douglas Gregor6a573fe2009-10-22 18:02:20 +00005619
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005620 // FIXME: Don't destroy TID here, since we need its template arguments
5621 // to survive.
5622 // TID->Destroy(Context);
Douglas Gregor091f0422009-10-23 22:18:25 +00005623 } else if (isa<UnresolvedFunctionNameExpr>(E)) {
5624 return DeclRefExpr::Create(Context,
5625 /*Qualifier=*/0,
5626 /*QualifierRange=*/SourceRange(),
5627 Fn, E->getLocStart(),
5628 Fn->getType(), false, false);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005629 } else {
5630 assert(false && "Invalid reference to overloaded function");
5631 }
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005632
5633 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005634}
5635
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005636} // end namespace clang