blob: 6200beb8630c5f831518d6c17e3a477ebb70bb08 [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"
Douglas Gregor39c16d42008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#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 Gregor23061de2009-06-24 16:50:40 +0000353 false, false, SourceLocation()) ||
354 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.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000407ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000408Sema::TryImplicitConversion(Expr* From, QualType ToType,
409 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000410 bool AllowExplicit, bool ForceRValue,
Mike Stump11289f42009-09-09 15:08:12 +0000411 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000412 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000413 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000414 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000415 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000416 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000417 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000418 (UserDefResult = IsUserDefinedConversion(From, ToType,
419 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000420 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000421 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000422 ForceRValue)) == OR_Success) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000423 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000424 // C++ [over.ics.user]p4:
425 // A conversion of an expression of class type to the same class
426 // type is given Exact Match rank, and a conversion of an
427 // expression of class type to a base class of that type is
428 // given Conversion rank, in spite of the fact that a copy
429 // constructor (i.e., a user-defined conversion function) is
430 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000431 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000432 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000433 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000434 = Context.getCanonicalType(From->getType().getUnqualifiedType());
435 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
436 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000437 // Turn this into a "standard" conversion sequence, so that it
438 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000439 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
440 ICS.Standard.setAsIdentityConversion();
441 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
442 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000443 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000444 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000445 ICS.Standard.Second = ICK_Derived_To_Base;
446 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000447 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000448
449 // C++ [over.best.ics]p4:
450 // However, when considering the argument of a user-defined
451 // conversion function that is a candidate by 13.3.1.3 when
452 // invoked for the copying of the temporary in the second step
453 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
454 // 13.3.1.6 in all cases, only standard conversion sequences and
455 // ellipsis conversion sequences are allowed.
456 if (SuppressUserConversions &&
457 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
458 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000459 } else {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000460 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000461 if (UserDefResult == OR_Ambiguous) {
462 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
463 Cand != Conversions.end(); ++Cand)
464 ICS.ConversionFunctionSet.push_back(Cand->Function);
465 }
466 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000467
468 return ICS;
469}
470
471/// IsStandardConversion - Determines whether there is a standard
472/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
473/// expression From to the type ToType. Standard conversion sequences
474/// only consider non-class types; for conversions that involve class
475/// types, use TryImplicitConversion. If a conversion exists, SCS will
476/// contain the standard conversion sequence required to perform this
477/// conversion and this routine will return true. Otherwise, this
478/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000479bool
480Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000481 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000482 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000483 QualType FromType = From->getType();
484
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000485 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000486 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000487 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000488 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000489 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000490 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000492 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000493 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000494 if (FromType->isRecordType() || ToType->isRecordType()) {
495 if (getLangOptions().CPlusPlus)
496 return false;
497
Mike Stump11289f42009-09-09 15:08:12 +0000498 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000499 }
500
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501 // The first conversion can be an lvalue-to-rvalue conversion,
502 // array-to-pointer conversion, or function-to-pointer conversion
503 // (C++ 4p1).
504
Mike Stump11289f42009-09-09 15:08:12 +0000505 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506 // An lvalue (3.10) of a non-function, non-array type T can be
507 // converted to an rvalue.
508 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000509 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000510 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000511 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000512 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513
514 // If T is a non-class type, the type of the rvalue is the
515 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000516 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
517 // just strip the qualifiers because they don't matter.
518
519 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000520 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000521 } else if (FromType->isArrayType()) {
522 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000523 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524
525 // An lvalue or rvalue of type "array of N T" or "array of unknown
526 // bound of T" can be converted to an rvalue of type "pointer to
527 // T" (C++ 4.2p1).
528 FromType = Context.getArrayDecayedType(FromType);
529
530 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
531 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000532 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000533
534 // For the purpose of ranking in overload resolution
535 // (13.3.3.1.1), this conversion is considered an
536 // array-to-pointer conversion followed by a qualification
537 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000538 SCS.Second = ICK_Identity;
539 SCS.Third = ICK_Qualification;
540 SCS.ToTypePtr = ToType.getAsOpaquePtr();
541 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000543 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
544 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000545 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000546
547 // An lvalue of function type T can be converted to an rvalue of
548 // type "pointer to T." The result is a pointer to the
549 // function. (C++ 4.3p1).
550 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000551 } else if (FunctionDecl *Fn
Douglas Gregorcd695e52008-11-10 20:40:00 +0000552 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000553 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000554 SCS.First = ICK_Function_To_Pointer;
555
556 // We were able to resolve the address of the overloaded function,
557 // so we can convert to the type of that function.
558 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000559 if (ToType->isLValueReferenceType())
560 FromType = Context.getLValueReferenceType(FromType);
561 else if (ToType->isRValueReferenceType())
562 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000563 else if (ToType->isMemberPointerType()) {
564 // Resolve address only succeeds if both sides are member pointers,
565 // but it doesn't have to be the same class. See DR 247.
566 // Note that this means that the type of &Derived::fn can be
567 // Ret (Base::*)(Args) if the fn overload actually found is from the
568 // base class, even if it was brought into the derived class via a
569 // using declaration. The standard isn't clear on this issue at all.
570 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
571 FromType = Context.getMemberPointerType(FromType,
572 Context.getTypeDeclType(M->getParent()).getTypePtr());
573 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000574 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000575 } else {
576 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000577 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000578 }
579
580 // The second conversion can be an integral promotion, floating
581 // point promotion, integral conversion, floating point conversion,
582 // floating-integral conversion, pointer conversion,
583 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000584 // For overloading in C, this can also be a "compatible-type"
585 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000586 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000587 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000588 // The unqualified versions of the types are the same: there's no
589 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000590 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000591 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000592 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000593 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000594 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000595 } else if (IsFloatingPointPromotion(FromType, ToType)) {
596 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000597 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000598 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000599 } else if (IsComplexPromotion(FromType, ToType)) {
600 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000601 SCS.Second = ICK_Complex_Promotion;
602 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000603 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000604 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000605 // Integral conversions (C++ 4.7).
606 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000607 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000608 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000609 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
610 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000611 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000612 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000613 } else if (FromType->isComplexType() && ToType->isComplexType()) {
614 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000615 SCS.Second = ICK_Complex_Conversion;
616 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000617 } else if ((FromType->isFloatingType() &&
618 ToType->isIntegralType() && (!ToType->isBooleanType() &&
619 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000620 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000621 ToType->isFloatingType())) {
622 // Floating-integral conversions (C++ 4.9).
623 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000624 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000625 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000626 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
627 (ToType->isComplexType() && FromType->isArithmeticType())) {
628 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000629 SCS.Second = ICK_Complex_Real;
630 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000631 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
632 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000633 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000634 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000635 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stump12b8ce12009-08-04 21:02:39 +0000636 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
637 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000638 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000639 } else if (ToType->isBooleanType() &&
640 (FromType->isArithmeticType() ||
641 FromType->isEnumeralType() ||
642 FromType->isPointerType() ||
643 FromType->isBlockPointerType() ||
644 FromType->isMemberPointerType() ||
645 FromType->isNullPtrType())) {
646 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000647 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000648 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000649 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000650 Context.typesAreCompatible(ToType, FromType)) {
651 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000652 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000653 } else {
654 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000655 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000656 }
657
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000658 QualType CanonFrom;
659 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000660 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000661 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000662 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000663 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000664 CanonFrom = Context.getCanonicalType(FromType);
665 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000666 } else {
667 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000668 SCS.Third = ICK_Identity;
669
Mike Stump11289f42009-09-09 15:08:12 +0000670 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000671 // [...] Any difference in top-level cv-qualification is
672 // subsumed by the initialization itself and does not constitute
673 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000674 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000675 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000676 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000677 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
678 FromType = ToType;
679 CanonFrom = CanonTo;
680 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000681 }
682
683 // If we have not converted the argument type to the parameter type,
684 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000685 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000686 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000687
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000688 SCS.ToTypePtr = FromType.getAsOpaquePtr();
689 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000690}
691
692/// IsIntegralPromotion - Determines whether the conversion from the
693/// expression From (whose potentially-adjusted type is FromType) to
694/// ToType is an integral promotion (C++ 4.5). If so, returns true and
695/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000696bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000697 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000698 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000699 if (!To) {
700 return false;
701 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000702
703 // An rvalue of type char, signed char, unsigned char, short int, or
704 // unsigned short int can be converted to an rvalue of type int if
705 // int can represent all the values of the source type; otherwise,
706 // the source rvalue can be converted to an rvalue of type unsigned
707 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000708 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000709 if (// We can promote any signed, promotable integer type to an int
710 (FromType->isSignedIntegerType() ||
711 // We can promote any unsigned integer type whose size is
712 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000713 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000714 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000715 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000716 }
717
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000718 return To->getKind() == BuiltinType::UInt;
719 }
720
721 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
722 // can be converted to an rvalue of the first of the following types
723 // that can represent all the values of its underlying type: int,
724 // unsigned int, long, or unsigned long (C++ 4.5p2).
725 if ((FromType->isEnumeralType() || FromType->isWideCharType())
726 && ToType->isIntegerType()) {
727 // Determine whether the type we're converting from is signed or
728 // unsigned.
729 bool FromIsSigned;
730 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall9dd450b2009-09-21 23:43:11 +0000731 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000732 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
733 FromIsSigned = UnderlyingType->isSignedIntegerType();
734 } else {
735 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
736 FromIsSigned = true;
737 }
738
739 // The types we'll try to promote to, in the appropriate
740 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000741 QualType PromoteTypes[6] = {
742 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000743 Context.LongTy, Context.UnsignedLongTy ,
744 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000745 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000746 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000747 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
748 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000749 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000750 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
751 // We found the type that we can promote to. If this is the
752 // type we wanted, we have a promotion. Otherwise, no
753 // promotion.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000754 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000755 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
756 }
757 }
758 }
759
760 // An rvalue for an integral bit-field (9.6) can be converted to an
761 // rvalue of type int if int can represent all the values of the
762 // bit-field; otherwise, it can be converted to unsigned int if
763 // unsigned int can represent all the values of the bit-field. If
764 // the bit-field is larger yet, no integral promotion applies to
765 // it. If the bit-field has an enumerated type, it is treated as any
766 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000767 // FIXME: We should delay checking of bit-fields until we actually perform the
768 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000769 using llvm::APSInt;
770 if (From)
771 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000772 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000773 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
774 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
775 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
776 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000777
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000778 // Are we promoting to an int from a bitfield that fits in an int?
779 if (BitWidth < ToSize ||
780 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
781 return To->getKind() == BuiltinType::Int;
782 }
Mike Stump11289f42009-09-09 15:08:12 +0000783
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000784 // Are we promoting to an unsigned int from an unsigned bitfield
785 // that fits into an unsigned int?
786 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
787 return To->getKind() == BuiltinType::UInt;
788 }
Mike Stump11289f42009-09-09 15:08:12 +0000789
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000790 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000791 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000792 }
Mike Stump11289f42009-09-09 15:08:12 +0000793
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000794 // An rvalue of type bool can be converted to an rvalue of type int,
795 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000796 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000797 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000798 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000799
800 return false;
801}
802
803/// IsFloatingPointPromotion - Determines whether the conversion from
804/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
805/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000806bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000807 /// An rvalue of type float can be converted to an rvalue of type
808 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000809 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
810 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000811 if (FromBuiltin->getKind() == BuiltinType::Float &&
812 ToBuiltin->getKind() == BuiltinType::Double)
813 return true;
814
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000815 // C99 6.3.1.5p1:
816 // When a float is promoted to double or long double, or a
817 // double is promoted to long double [...].
818 if (!getLangOptions().CPlusPlus &&
819 (FromBuiltin->getKind() == BuiltinType::Float ||
820 FromBuiltin->getKind() == BuiltinType::Double) &&
821 (ToBuiltin->getKind() == BuiltinType::LongDouble))
822 return true;
823 }
824
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000825 return false;
826}
827
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000828/// \brief Determine if a conversion is a complex promotion.
829///
830/// A complex promotion is defined as a complex -> complex conversion
831/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000832/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000833bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000834 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000835 if (!FromComplex)
836 return false;
837
John McCall9dd450b2009-09-21 23:43:11 +0000838 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000839 if (!ToComplex)
840 return false;
841
842 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000843 ToComplex->getElementType()) ||
844 IsIntegralPromotion(0, FromComplex->getElementType(),
845 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000846}
847
Douglas Gregor237f96c2008-11-26 23:31:11 +0000848/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
849/// the pointer type FromPtr to a pointer to type ToPointee, with the
850/// same type qualifiers as FromPtr has on its pointee type. ToType,
851/// if non-empty, will be a pointer to ToType that may or may not have
852/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000853static QualType
854BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000855 QualType ToPointee, QualType ToType,
856 ASTContext &Context) {
857 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
858 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000859 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000860
861 // Exact qualifier match -> return the pointer type we're converting to.
John McCall8ccfcb52009-09-24 19:53:00 +0000862 if (CanonToPointee.getQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000863 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000864 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000865 return ToType;
866
867 // Build a pointer to ToPointee. It has the right qualifiers
868 // already.
869 return Context.getPointerType(ToPointee);
870 }
871
872 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000873 return Context.getPointerType(
874 Context.getQualifiedType(CanonToPointee.getUnqualifiedType(), Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000875}
876
Mike Stump11289f42009-09-09 15:08:12 +0000877static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000878 bool InOverloadResolution,
879 ASTContext &Context) {
880 // Handle value-dependent integral null pointer constants correctly.
881 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
882 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
883 Expr->getType()->isIntegralType())
884 return !InOverloadResolution;
885
886 return Expr->isNullPointerConstant(Context);
887}
Mike Stump11289f42009-09-09 15:08:12 +0000888
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000889/// IsPointerConversion - Determines whether the conversion of the
890/// expression From, which has the (possibly adjusted) type FromType,
891/// can be converted to the type ToType via a pointer conversion (C++
892/// 4.10). If so, returns true and places the converted type (that
893/// might differ from ToType in its cv-qualifiers at some level) into
894/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000895///
Douglas Gregora29dc052008-11-27 01:19:21 +0000896/// This routine also supports conversions to and from block pointers
897/// and conversions with Objective-C's 'id', 'id<protocols...>', and
898/// pointers to interfaces. FIXME: Once we've determined the
899/// appropriate overloading rules for Objective-C, we may want to
900/// split the Objective-C checks into a different routine; however,
901/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000902/// conversions, so for now they live here. IncompatibleObjC will be
903/// set if the conversion is an allowed Objective-C conversion that
904/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000905bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000906 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000907 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000908 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000909 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000910 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
911 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000912
Mike Stump11289f42009-09-09 15:08:12 +0000913 // Conversion from a null pointer constant to any Objective-C pointer type.
914 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000915 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000916 ConvertedType = ToType;
917 return true;
918 }
919
Douglas Gregor231d1c62008-11-27 00:15:41 +0000920 // Blocks: Block pointers can be converted to void*.
921 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000922 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000923 ConvertedType = ToType;
924 return true;
925 }
926 // Blocks: A null pointer constant can be converted to a block
927 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000928 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000929 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000930 ConvertedType = ToType;
931 return true;
932 }
933
Sebastian Redl576fd422009-05-10 18:38:11 +0000934 // If the left-hand-side is nullptr_t, the right side can be a null
935 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000936 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000937 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000938 ConvertedType = ToType;
939 return true;
940 }
941
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000942 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000943 if (!ToTypePtr)
944 return false;
945
946 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000947 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000948 ConvertedType = ToType;
949 return true;
950 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000951
Douglas Gregor237f96c2008-11-26 23:31:11 +0000952 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000953 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000954 if (!FromTypePtr)
955 return false;
956
957 QualType FromPointeeType = FromTypePtr->getPointeeType();
958 QualType ToPointeeType = ToTypePtr->getPointeeType();
959
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000960 // An rvalue of type "pointer to cv T," where T is an object type,
961 // can be converted to an rvalue of type "pointer to cv void" (C++
962 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000963 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000964 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000965 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000966 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000967 return true;
968 }
969
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000970 // When we're overloading in C, we allow a special kind of pointer
971 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +0000972 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000973 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000974 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000975 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +0000976 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000977 return true;
978 }
979
Douglas Gregor5c407d92008-10-23 00:40:37 +0000980 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +0000981 //
Douglas Gregor5c407d92008-10-23 00:40:37 +0000982 // An rvalue of type "pointer to cv D," where D is a class type,
983 // can be converted to an rvalue of type "pointer to cv B," where
984 // B is a base class (clause 10) of D. If B is an inaccessible
985 // (clause 11) or ambiguous (10.2) base class of D, a program that
986 // necessitates this conversion is ill-formed. The result of the
987 // conversion is a pointer to the base class sub-object of the
988 // derived class object. The null pointer value is converted to
989 // the null pointer value of the destination type.
990 //
Douglas Gregor39c16d42008-10-24 04:54:22 +0000991 // Note that we do not check for ambiguity or inaccessibility
992 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000993 if (getLangOptions().CPlusPlus &&
994 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor237f96c2008-11-26 23:31:11 +0000995 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000996 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000997 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000998 ToType, Context);
999 return true;
1000 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001001
Douglas Gregora119f102008-12-19 19:13:09 +00001002 return false;
1003}
1004
1005/// isObjCPointerConversion - Determines whether this is an
1006/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1007/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001008bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001009 QualType& ConvertedType,
1010 bool &IncompatibleObjC) {
1011 if (!getLangOptions().ObjC1)
1012 return false;
1013
Steve Naroff7cae42b2009-07-10 23:34:53 +00001014 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001015 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001016 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001017 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001018
Steve Naroff7cae42b2009-07-10 23:34:53 +00001019 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001020 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001021 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001022 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001023 ConvertedType = ToType;
1024 return true;
1025 }
1026 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001027 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001028 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001029 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001030 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001031 ConvertedType = ToType;
1032 return true;
1033 }
1034 // Objective C++: We're able to convert from a pointer to an
1035 // interface to a pointer to a different interface.
1036 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1037 ConvertedType = ToType;
1038 return true;
1039 }
1040
1041 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1042 // Okay: this is some kind of implicit downcast of Objective-C
1043 // interfaces, which is permitted. However, we're going to
1044 // complain about it.
1045 IncompatibleObjC = true;
1046 ConvertedType = FromType;
1047 return true;
1048 }
Mike Stump11289f42009-09-09 15:08:12 +00001049 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001050 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001051 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001052 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001053 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001054 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001055 ToPointeeType = ToBlockPtr->getPointeeType();
1056 else
Douglas Gregora119f102008-12-19 19:13:09 +00001057 return false;
1058
Douglas Gregor033f56d2008-12-23 00:53:59 +00001059 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001060 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001061 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001062 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001063 FromPointeeType = FromBlockPtr->getPointeeType();
1064 else
Douglas Gregora119f102008-12-19 19:13:09 +00001065 return false;
1066
Douglas Gregora119f102008-12-19 19:13:09 +00001067 // If we have pointers to pointers, recursively check whether this
1068 // is an Objective-C conversion.
1069 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1070 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1071 IncompatibleObjC)) {
1072 // We always complain about this conversion.
1073 IncompatibleObjC = true;
1074 ConvertedType = ToType;
1075 return true;
1076 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001077 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001078 // differences in the argument and result types are in Objective-C
1079 // pointer conversions. If so, we permit the conversion (but
1080 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001081 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001082 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001083 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001084 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001085 if (FromFunctionType && ToFunctionType) {
1086 // If the function types are exactly the same, this isn't an
1087 // Objective-C pointer conversion.
1088 if (Context.getCanonicalType(FromPointeeType)
1089 == Context.getCanonicalType(ToPointeeType))
1090 return false;
1091
1092 // Perform the quick checks that will tell us whether these
1093 // function types are obviously different.
1094 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1095 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1096 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1097 return false;
1098
1099 bool HasObjCConversion = false;
1100 if (Context.getCanonicalType(FromFunctionType->getResultType())
1101 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1102 // Okay, the types match exactly. Nothing to do.
1103 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1104 ToFunctionType->getResultType(),
1105 ConvertedType, IncompatibleObjC)) {
1106 // Okay, we have an Objective-C pointer conversion.
1107 HasObjCConversion = true;
1108 } else {
1109 // Function types are too different. Abort.
1110 return false;
1111 }
Mike Stump11289f42009-09-09 15:08:12 +00001112
Douglas Gregora119f102008-12-19 19:13:09 +00001113 // Check argument types.
1114 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1115 ArgIdx != NumArgs; ++ArgIdx) {
1116 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1117 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1118 if (Context.getCanonicalType(FromArgType)
1119 == Context.getCanonicalType(ToArgType)) {
1120 // Okay, the types match exactly. Nothing to do.
1121 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1122 ConvertedType, IncompatibleObjC)) {
1123 // Okay, we have an Objective-C pointer conversion.
1124 HasObjCConversion = true;
1125 } else {
1126 // Argument types are too different. Abort.
1127 return false;
1128 }
1129 }
1130
1131 if (HasObjCConversion) {
1132 // We had an Objective-C conversion. Allow this pointer
1133 // conversion, but complain about it.
1134 ConvertedType = ToType;
1135 IncompatibleObjC = true;
1136 return true;
1137 }
1138 }
1139
Sebastian Redl72b597d2009-01-25 19:43:20 +00001140 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001141}
1142
Douglas Gregor39c16d42008-10-24 04:54:22 +00001143/// CheckPointerConversion - Check the pointer conversion from the
1144/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001145/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001146/// conversions for which IsPointerConversion has already returned
1147/// true. It returns true and produces a diagnostic if there was an
1148/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001149bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1150 CastExpr::CastKind &Kind) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001151 QualType FromType = From->getType();
1152
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001153 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1154 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001155 QualType FromPointeeType = FromPtrType->getPointeeType(),
1156 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001157
Douglas Gregor39c16d42008-10-24 04:54:22 +00001158 if (FromPointeeType->isRecordType() &&
1159 ToPointeeType->isRecordType()) {
1160 // We must have a derived-to-base conversion. Check an
1161 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001162 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1163 From->getExprLoc(),
1164 From->getSourceRange()))
1165 return true;
1166
1167 // The conversion was successful.
1168 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001169 }
1170 }
Mike Stump11289f42009-09-09 15:08:12 +00001171 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001172 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001173 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001174 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001175 // Objective-C++ conversions are always okay.
1176 // FIXME: We should have a different class of conversions for the
1177 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001178 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001179 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001180
Steve Naroff7cae42b2009-07-10 23:34:53 +00001181 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001182 return false;
1183}
1184
Sebastian Redl72b597d2009-01-25 19:43:20 +00001185/// IsMemberPointerConversion - Determines whether the conversion of the
1186/// expression From, which has the (possibly adjusted) type FromType, can be
1187/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1188/// If so, returns true and places the converted type (that might differ from
1189/// ToType in its cv-qualifiers at some level) into ConvertedType.
1190bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Mike Stump11289f42009-09-09 15:08:12 +00001191 QualType ToType, QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001192 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001193 if (!ToTypePtr)
1194 return false;
1195
1196 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1197 if (From->isNullPointerConstant(Context)) {
1198 ConvertedType = ToType;
1199 return true;
1200 }
1201
1202 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001203 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001204 if (!FromTypePtr)
1205 return false;
1206
1207 // A pointer to member of B can be converted to a pointer to member of D,
1208 // where D is derived from B (C++ 4.11p2).
1209 QualType FromClass(FromTypePtr->getClass(), 0);
1210 QualType ToClass(ToTypePtr->getClass(), 0);
1211 // FIXME: What happens when these are dependent? Is this function even called?
1212
1213 if (IsDerivedFrom(ToClass, FromClass)) {
1214 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1215 ToClass.getTypePtr());
1216 return true;
1217 }
1218
1219 return false;
1220}
1221
1222/// CheckMemberPointerConversion - Check the member pointer conversion from the
1223/// expression From to the type ToType. This routine checks for ambiguous or
1224/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1225/// for which IsMemberPointerConversion has already returned true. It returns
1226/// true and produces a diagnostic if there was an error, or returns false
1227/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001228bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Anders Carlssond7923c62009-08-22 23:33:40 +00001229 CastExpr::CastKind &Kind) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001230 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001231 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001232 if (!FromPtrType) {
1233 // This must be a null pointer to member pointer conversion
Mike Stump11289f42009-09-09 15:08:12 +00001234 assert(From->isNullPointerConstant(Context) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001235 "Expr must be null pointer constant!");
1236 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001237 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001238 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001239
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001240 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001241 assert(ToPtrType && "No member pointer cast has a target type "
1242 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001243
Sebastian Redled8f2002009-01-28 18:33:18 +00001244 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1245 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001246
Sebastian Redled8f2002009-01-28 18:33:18 +00001247 // FIXME: What about dependent types?
1248 assert(FromClass->isRecordType() && "Pointer into non-class.");
1249 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001250
Sebastian Redled8f2002009-01-28 18:33:18 +00001251 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1252 /*DetectVirtual=*/true);
1253 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1254 assert(DerivationOkay &&
1255 "Should not have been called if derivation isn't OK.");
1256 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001257
Sebastian Redled8f2002009-01-28 18:33:18 +00001258 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1259 getUnqualifiedType())) {
1260 // Derivation is ambiguous. Redo the check to find the exact paths.
1261 Paths.clear();
1262 Paths.setRecordingPaths(true);
1263 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1264 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1265 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001266
Sebastian Redled8f2002009-01-28 18:33:18 +00001267 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1268 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1269 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1270 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001271 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001272
Douglas Gregor89ee6822009-02-28 01:32:25 +00001273 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001274 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1275 << FromClass << ToClass << QualType(VBase, 0)
1276 << From->getSourceRange();
1277 return true;
1278 }
1279
Anders Carlssond7923c62009-08-22 23:33:40 +00001280 // Must be a base to derived member conversion.
1281 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001282 return false;
1283}
1284
Douglas Gregor9a657932008-10-21 23:43:52 +00001285/// IsQualificationConversion - Determines whether the conversion from
1286/// an rvalue of type FromType to ToType is a qualification conversion
1287/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001288bool
1289Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001290 FromType = Context.getCanonicalType(FromType);
1291 ToType = Context.getCanonicalType(ToType);
1292
1293 // If FromType and ToType are the same type, this is not a
1294 // qualification conversion.
1295 if (FromType == ToType)
1296 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001297
Douglas Gregor9a657932008-10-21 23:43:52 +00001298 // (C++ 4.4p4):
1299 // A conversion can add cv-qualifiers at levels other than the first
1300 // in multi-level pointers, subject to the following rules: [...]
1301 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001302 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001303 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001304 // Within each iteration of the loop, we check the qualifiers to
1305 // determine if this still looks like a qualification
1306 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001307 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001308 // until there are no more pointers or pointers-to-members left to
1309 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001310 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001311
1312 // -- for every j > 0, if const is in cv 1,j then const is in cv
1313 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001314 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001315 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001316
Douglas Gregor9a657932008-10-21 23:43:52 +00001317 // -- if the cv 1,j and cv 2,j are different, then const is in
1318 // every cv for 0 < k < j.
1319 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001320 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001321 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001322
Douglas Gregor9a657932008-10-21 23:43:52 +00001323 // Keep track of whether all prior cv-qualifiers in the "to" type
1324 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001325 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001326 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001327 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001328
1329 // We are left with FromType and ToType being the pointee types
1330 // after unwrapping the original FromType and ToType the same number
1331 // of types. If we unwrapped any pointers, and if FromType and
1332 // ToType have the same unqualified type (since we checked
1333 // qualifiers above), then this is a qualification conversion.
1334 return UnwrappedAnyPointer &&
1335 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1336}
1337
Douglas Gregor05155d82009-08-21 23:19:43 +00001338/// \brief Given a function template or function, extract the function template
1339/// declaration (if any) and the underlying function declaration.
1340template<typename T>
1341static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1342 FunctionTemplateDecl *&FunctionTemplate) {
1343 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1344 if (FunctionTemplate)
1345 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1346 else
1347 Function = cast<T>(Orig);
1348}
1349
Douglas Gregor576e98c2009-01-30 23:27:23 +00001350/// Determines whether there is a user-defined conversion sequence
1351/// (C++ [over.ics.user]) that converts expression From to the type
1352/// ToType. If such a conversion exists, User will contain the
1353/// user-defined conversion sequence that performs such a conversion
1354/// and this routine will return true. Otherwise, this routine returns
1355/// false and User is unspecified.
1356///
1357/// \param AllowConversionFunctions true if the conversion should
1358/// consider conversion functions at all. If false, only constructors
1359/// will be considered.
1360///
1361/// \param AllowExplicit true if the conversion should consider C++0x
1362/// "explicit" conversion functions as well as non-explicit conversion
1363/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001364///
1365/// \param ForceRValue true if the expression should be treated as an rvalue
1366/// for overload resolution.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001367Sema::OverloadingResult Sema::IsUserDefinedConversion(
1368 Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001369 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001370 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001371 bool AllowConversionFunctions,
Mike Stump11289f42009-09-09 15:08:12 +00001372 bool AllowExplicit, bool ForceRValue) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001373 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001374 if (CXXRecordDecl *ToRecordDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001375 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1376 // C++ [over.match.ctor]p1:
1377 // When objects of class type are direct-initialized (8.5), or
1378 // copy-initialized from an expression of the same or a
1379 // derived class type (8.5), overload resolution selects the
1380 // constructor. [...] For copy-initialization, the candidate
1381 // functions are all the converting constructors (12.3.1) of
1382 // that class. The argument list is the expression-list within
1383 // the parentheses of the initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001384 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001385 = Context.DeclarationNames.getCXXConstructorName(
1386 Context.getCanonicalType(ToType).getUnqualifiedType());
1387 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001388 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001389 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001390 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001391 // Find the constructor (which may be a template).
1392 CXXConstructorDecl *Constructor = 0;
1393 FunctionTemplateDecl *ConstructorTmpl
1394 = dyn_cast<FunctionTemplateDecl>(*Con);
1395 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001396 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001397 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1398 else
1399 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump11289f42009-09-09 15:08:12 +00001400
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001401 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001402 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001403 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001404 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001405 1, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00001406 /*SuppressUserConversions=*/true,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001407 ForceRValue);
1408 else
1409 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1410 /*SuppressUserConversions=*/true, ForceRValue);
1411 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001412 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001413 }
1414 }
1415
Douglas Gregor576e98c2009-01-30 23:27:23 +00001416 if (!AllowConversionFunctions) {
1417 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001418 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1419 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001420 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001421 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001422 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001423 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001424 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001425 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1426 // Add all of the conversion functions as candidates.
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001427 OverloadedFunctionDecl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001428 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001429 for (OverloadedFunctionDecl::function_iterator Func
1430 = Conversions->function_begin();
1431 Func != Conversions->function_end(); ++Func) {
1432 CXXConversionDecl *Conv;
1433 FunctionTemplateDecl *ConvTemplate;
1434 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1435 if (ConvTemplate)
1436 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1437 else
1438 Conv = dyn_cast<CXXConversionDecl>(*Func);
1439
1440 if (AllowExplicit || !Conv->isExplicit()) {
1441 if (ConvTemplate)
1442 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1443 CandidateSet);
1444 else
1445 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1446 }
1447 }
1448 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001449 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001450
1451 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001452 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001453 case OR_Success:
1454 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001455 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001456 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1457 // C++ [over.ics.user]p1:
1458 // If the user-defined conversion is specified by a
1459 // constructor (12.3.1), the initial standard conversion
1460 // sequence converts the source type to the type required by
1461 // the argument of the constructor.
1462 //
1463 // FIXME: What about ellipsis conversions?
1464 QualType ThisType = Constructor->getThisType(Context);
1465 User.Before = Best->Conversions[0].Standard;
1466 User.ConversionFunction = Constructor;
1467 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001468 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001469 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001470 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001471 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001472 } else if (CXXConversionDecl *Conversion
1473 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1474 // C++ [over.ics.user]p1:
1475 //
1476 // [...] If the user-defined conversion is specified by a
1477 // conversion function (12.3.2), the initial standard
1478 // conversion sequence converts the source type to the
1479 // implicit object parameter of the conversion function.
1480 User.Before = Best->Conversions[0].Standard;
1481 User.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00001482
1483 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001484 // The second standard conversion sequence converts the
1485 // result of the user-defined conversion to the target type
1486 // for the sequence. Since an implicit conversion sequence
1487 // is an initialization, the special rules for
1488 // initialization by user-defined conversion apply when
1489 // selecting the best user-defined conversion for a
1490 // user-defined conversion sequence (see 13.3.3 and
1491 // 13.3.3.1).
1492 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001493 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001494 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001495 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001496 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001497 }
Mike Stump11289f42009-09-09 15:08:12 +00001498
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001499 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001500 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001501 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001502 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001503 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001504
1505 case OR_Ambiguous:
1506 // FIXME: See C++ [over.best.ics]p10 for the handling of
1507 // ambiguous conversion sequences.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001508 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001509 }
1510
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001511 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001512}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001513
1514bool
1515Sema::DiagnoseAmbiguousUserDefinedConversion(Expr *From, QualType ToType) {
1516 ImplicitConversionSequence ICS;
1517 OverloadCandidateSet CandidateSet;
1518 OverloadingResult OvResult =
1519 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1520 CandidateSet, true, false, false);
1521 if (OvResult != OR_Ambiguous)
1522 return false;
1523 Diag(From->getSourceRange().getBegin(),
1524 diag::err_typecheck_ambiguous_condition)
1525 << From->getType() << ToType << From->getSourceRange();
1526 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1527 return true;
1528}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001529
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001530/// CompareImplicitConversionSequences - Compare two implicit
1531/// conversion sequences to determine whether one is better than the
1532/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001533ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001534Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1535 const ImplicitConversionSequence& ICS2)
1536{
1537 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1538 // conversion sequences (as defined in 13.3.3.1)
1539 // -- a standard conversion sequence (13.3.3.1.1) is a better
1540 // conversion sequence than a user-defined conversion sequence or
1541 // an ellipsis conversion sequence, and
1542 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1543 // conversion sequence than an ellipsis conversion sequence
1544 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001545 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001546 if (ICS1.ConversionKind < ICS2.ConversionKind)
1547 return ImplicitConversionSequence::Better;
1548 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1549 return ImplicitConversionSequence::Worse;
1550
1551 // Two implicit conversion sequences of the same form are
1552 // indistinguishable conversion sequences unless one of the
1553 // following rules apply: (C++ 13.3.3.2p3):
1554 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1555 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001556 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001557 ImplicitConversionSequence::UserDefinedConversion) {
1558 // User-defined conversion sequence U1 is a better conversion
1559 // sequence than another user-defined conversion sequence U2 if
1560 // they contain the same user-defined conversion function or
1561 // constructor and if the second standard conversion sequence of
1562 // U1 is better than the second standard conversion sequence of
1563 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001564 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001565 ICS2.UserDefined.ConversionFunction)
1566 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1567 ICS2.UserDefined.After);
1568 }
1569
1570 return ImplicitConversionSequence::Indistinguishable;
1571}
1572
1573/// CompareStandardConversionSequences - Compare two standard
1574/// conversion sequences to determine whether one is better than the
1575/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001576ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001577Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1578 const StandardConversionSequence& SCS2)
1579{
1580 // Standard conversion sequence S1 is a better conversion sequence
1581 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1582
1583 // -- S1 is a proper subsequence of S2 (comparing the conversion
1584 // sequences in the canonical form defined by 13.3.3.1.1,
1585 // excluding any Lvalue Transformation; the identity conversion
1586 // sequence is considered to be a subsequence of any
1587 // non-identity conversion sequence) or, if not that,
1588 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1589 // Neither is a proper subsequence of the other. Do nothing.
1590 ;
1591 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1592 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001593 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001594 SCS1.Third == ICK_Identity))
1595 // SCS1 is a proper subsequence of SCS2.
1596 return ImplicitConversionSequence::Better;
1597 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1598 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001599 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001600 SCS2.Third == ICK_Identity))
1601 // SCS2 is a proper subsequence of SCS1.
1602 return ImplicitConversionSequence::Worse;
1603
1604 // -- the rank of S1 is better than the rank of S2 (by the rules
1605 // defined below), or, if not that,
1606 ImplicitConversionRank Rank1 = SCS1.getRank();
1607 ImplicitConversionRank Rank2 = SCS2.getRank();
1608 if (Rank1 < Rank2)
1609 return ImplicitConversionSequence::Better;
1610 else if (Rank2 < Rank1)
1611 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001612
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001613 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1614 // are indistinguishable unless one of the following rules
1615 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001616
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001617 // A conversion that is not a conversion of a pointer, or
1618 // pointer to member, to bool is better than another conversion
1619 // that is such a conversion.
1620 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1621 return SCS2.isPointerConversionToBool()
1622 ? ImplicitConversionSequence::Better
1623 : ImplicitConversionSequence::Worse;
1624
Douglas Gregor5c407d92008-10-23 00:40:37 +00001625 // C++ [over.ics.rank]p4b2:
1626 //
1627 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001628 // conversion of B* to A* is better than conversion of B* to
1629 // void*, and conversion of A* to void* is better than conversion
1630 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001631 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001632 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001633 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001634 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001635 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1636 // Exactly one of the conversion sequences is a conversion to
1637 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001638 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1639 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001640 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1641 // Neither conversion sequence converts to a void pointer; compare
1642 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001643 if (ImplicitConversionSequence::CompareKind DerivedCK
1644 = CompareDerivedToBaseConversions(SCS1, SCS2))
1645 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001646 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1647 // Both conversion sequences are conversions to void
1648 // pointers. Compare the source types to determine if there's an
1649 // inheritance relationship in their sources.
1650 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1651 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1652
1653 // Adjust the types we're converting from via the array-to-pointer
1654 // conversion, if we need to.
1655 if (SCS1.First == ICK_Array_To_Pointer)
1656 FromType1 = Context.getArrayDecayedType(FromType1);
1657 if (SCS2.First == ICK_Array_To_Pointer)
1658 FromType2 = Context.getArrayDecayedType(FromType2);
1659
Mike Stump11289f42009-09-09 15:08:12 +00001660 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001661 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001662 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001663 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001664
1665 if (IsDerivedFrom(FromPointee2, FromPointee1))
1666 return ImplicitConversionSequence::Better;
1667 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1668 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001669
1670 // Objective-C++: If one interface is more specific than the
1671 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001672 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1673 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001674 if (FromIface1 && FromIface1) {
1675 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1676 return ImplicitConversionSequence::Better;
1677 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1678 return ImplicitConversionSequence::Worse;
1679 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001680 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001681
1682 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1683 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001684 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001685 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001686 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001687
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001688 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001689 // C++0x [over.ics.rank]p3b4:
1690 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1691 // implicit object parameter of a non-static member function declared
1692 // without a ref-qualifier, and S1 binds an rvalue reference to an
1693 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001694 // FIXME: We don't know if we're dealing with the implicit object parameter,
1695 // or if the member function in this case has a ref qualifier.
1696 // (Of course, we don't have ref qualifiers yet.)
1697 if (SCS1.RRefBinding != SCS2.RRefBinding)
1698 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1699 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001700
1701 // C++ [over.ics.rank]p3b4:
1702 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1703 // which the references refer are the same type except for
1704 // top-level cv-qualifiers, and the type to which the reference
1705 // initialized by S2 refers is more cv-qualified than the type
1706 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001707 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1708 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001709 T1 = Context.getCanonicalType(T1);
1710 T2 = Context.getCanonicalType(T2);
1711 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1712 if (T2.isMoreQualifiedThan(T1))
1713 return ImplicitConversionSequence::Better;
1714 else if (T1.isMoreQualifiedThan(T2))
1715 return ImplicitConversionSequence::Worse;
1716 }
1717 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001718
1719 return ImplicitConversionSequence::Indistinguishable;
1720}
1721
1722/// CompareQualificationConversions - Compares two standard conversion
1723/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001724/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1725ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001726Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001727 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001728 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001729 // -- S1 and S2 differ only in their qualification conversion and
1730 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1731 // cv-qualification signature of type T1 is a proper subset of
1732 // the cv-qualification signature of type T2, and S1 is not the
1733 // deprecated string literal array-to-pointer conversion (4.2).
1734 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1735 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1736 return ImplicitConversionSequence::Indistinguishable;
1737
1738 // FIXME: the example in the standard doesn't use a qualification
1739 // conversion (!)
1740 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1741 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1742 T1 = Context.getCanonicalType(T1);
1743 T2 = Context.getCanonicalType(T2);
1744
1745 // If the types are the same, we won't learn anything by unwrapped
1746 // them.
1747 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1748 return ImplicitConversionSequence::Indistinguishable;
1749
Mike Stump11289f42009-09-09 15:08:12 +00001750 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001751 = ImplicitConversionSequence::Indistinguishable;
1752 while (UnwrapSimilarPointerTypes(T1, T2)) {
1753 // Within each iteration of the loop, we check the qualifiers to
1754 // determine if this still looks like a qualification
1755 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001756 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001757 // until there are no more pointers or pointers-to-members left
1758 // to unwrap. This essentially mimics what
1759 // IsQualificationConversion does, but here we're checking for a
1760 // strict subset of qualifiers.
1761 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1762 // The qualifiers are the same, so this doesn't tell us anything
1763 // about how the sequences rank.
1764 ;
1765 else if (T2.isMoreQualifiedThan(T1)) {
1766 // T1 has fewer qualifiers, so it could be the better sequence.
1767 if (Result == ImplicitConversionSequence::Worse)
1768 // Neither has qualifiers that are a subset of the other's
1769 // qualifiers.
1770 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001771
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001772 Result = ImplicitConversionSequence::Better;
1773 } else if (T1.isMoreQualifiedThan(T2)) {
1774 // T2 has fewer qualifiers, so it could be the better sequence.
1775 if (Result == ImplicitConversionSequence::Better)
1776 // Neither has qualifiers that are a subset of the other's
1777 // qualifiers.
1778 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001779
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001780 Result = ImplicitConversionSequence::Worse;
1781 } else {
1782 // Qualifiers are disjoint.
1783 return ImplicitConversionSequence::Indistinguishable;
1784 }
1785
1786 // If the types after this point are equivalent, we're done.
1787 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1788 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001789 }
1790
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001791 // Check that the winning standard conversion sequence isn't using
1792 // the deprecated string literal array to pointer conversion.
1793 switch (Result) {
1794 case ImplicitConversionSequence::Better:
1795 if (SCS1.Deprecated)
1796 Result = ImplicitConversionSequence::Indistinguishable;
1797 break;
1798
1799 case ImplicitConversionSequence::Indistinguishable:
1800 break;
1801
1802 case ImplicitConversionSequence::Worse:
1803 if (SCS2.Deprecated)
1804 Result = ImplicitConversionSequence::Indistinguishable;
1805 break;
1806 }
1807
1808 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001809}
1810
Douglas Gregor5c407d92008-10-23 00:40:37 +00001811/// CompareDerivedToBaseConversions - Compares two standard conversion
1812/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001813/// various kinds of derived-to-base conversions (C++
1814/// [over.ics.rank]p4b3). As part of these checks, we also look at
1815/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001816ImplicitConversionSequence::CompareKind
1817Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1818 const StandardConversionSequence& SCS2) {
1819 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1820 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1821 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1822 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1823
1824 // Adjust the types we're converting from via the array-to-pointer
1825 // conversion, if we need to.
1826 if (SCS1.First == ICK_Array_To_Pointer)
1827 FromType1 = Context.getArrayDecayedType(FromType1);
1828 if (SCS2.First == ICK_Array_To_Pointer)
1829 FromType2 = Context.getArrayDecayedType(FromType2);
1830
1831 // Canonicalize all of the types.
1832 FromType1 = Context.getCanonicalType(FromType1);
1833 ToType1 = Context.getCanonicalType(ToType1);
1834 FromType2 = Context.getCanonicalType(FromType2);
1835 ToType2 = Context.getCanonicalType(ToType2);
1836
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001837 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001838 //
1839 // If class B is derived directly or indirectly from class A and
1840 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001841 //
1842 // For Objective-C, we let A, B, and C also be Objective-C
1843 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001844
1845 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001846 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001847 SCS2.Second == ICK_Pointer_Conversion &&
1848 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1849 FromType1->isPointerType() && FromType2->isPointerType() &&
1850 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001851 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001852 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001853 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001854 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001855 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001856 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001857 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001858 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001859
John McCall9dd450b2009-09-21 23:43:11 +00001860 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1861 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1862 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1863 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001864
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001865 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001866 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1867 if (IsDerivedFrom(ToPointee1, ToPointee2))
1868 return ImplicitConversionSequence::Better;
1869 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1870 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001871
1872 if (ToIface1 && ToIface2) {
1873 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1874 return ImplicitConversionSequence::Better;
1875 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1876 return ImplicitConversionSequence::Worse;
1877 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001878 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001879
1880 // -- conversion of B* to A* is better than conversion of C* to A*,
1881 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1882 if (IsDerivedFrom(FromPointee2, FromPointee1))
1883 return ImplicitConversionSequence::Better;
1884 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1885 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001886
Douglas Gregor237f96c2008-11-26 23:31:11 +00001887 if (FromIface1 && FromIface2) {
1888 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1889 return ImplicitConversionSequence::Better;
1890 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1891 return ImplicitConversionSequence::Worse;
1892 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001893 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001894 }
1895
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001896 // Compare based on reference bindings.
1897 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1898 SCS1.Second == ICK_Derived_To_Base) {
1899 // -- binding of an expression of type C to a reference of type
1900 // B& is better than binding an expression of type C to a
1901 // reference of type A&,
1902 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1903 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1904 if (IsDerivedFrom(ToType1, ToType2))
1905 return ImplicitConversionSequence::Better;
1906 else if (IsDerivedFrom(ToType2, ToType1))
1907 return ImplicitConversionSequence::Worse;
1908 }
1909
Douglas Gregor2fe98832008-11-03 19:09:14 +00001910 // -- binding of an expression of type B to a reference of type
1911 // A& is better than binding an expression of type C to a
1912 // reference of type A&,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001913 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1914 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1915 if (IsDerivedFrom(FromType2, FromType1))
1916 return ImplicitConversionSequence::Better;
1917 else if (IsDerivedFrom(FromType1, FromType2))
1918 return ImplicitConversionSequence::Worse;
1919 }
1920 }
1921
1922
1923 // FIXME: conversion of A::* to B::* is better than conversion of
1924 // A::* to C::*,
1925
1926 // FIXME: conversion of B::* to C::* is better than conversion of
1927 // A::* to C::*, and
1928
Douglas Gregor2fe98832008-11-03 19:09:14 +00001929 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1930 SCS1.Second == ICK_Derived_To_Base) {
1931 // -- conversion of C to B is better than conversion of C to 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 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001939
Douglas Gregor2fe98832008-11-03 19:09:14 +00001940 // -- conversion of B to A is better than conversion of C to A.
1941 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1942 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1943 if (IsDerivedFrom(FromType2, FromType1))
1944 return ImplicitConversionSequence::Better;
1945 else if (IsDerivedFrom(FromType1, FromType2))
1946 return ImplicitConversionSequence::Worse;
1947 }
1948 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001949
Douglas Gregor5c407d92008-10-23 00:40:37 +00001950 return ImplicitConversionSequence::Indistinguishable;
1951}
1952
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001953/// TryCopyInitialization - Try to copy-initialize a value of type
1954/// ToType from the expression From. Return the implicit conversion
1955/// sequence required to pass this argument, which may be a bad
1956/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00001957/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00001958/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1959/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00001960ImplicitConversionSequence
1961Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00001962 bool SuppressUserConversions, bool ForceRValue,
1963 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001964 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001965 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00001966 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00001967 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00001968 SuppressUserConversions,
1969 /*AllowExplicit=*/false,
1970 ForceRValue,
1971 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001972 return ICS;
1973 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001974 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001975 SuppressUserConversions,
1976 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001977 ForceRValue,
1978 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001979 }
1980}
1981
Sebastian Redl42e92c42009-04-12 17:16:29 +00001982/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1983/// the expression @p From. Returns true (and emits a diagnostic) if there was
1984/// an error, returns false if the initialization succeeded. Elidable should
1985/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1986/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00001987bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00001988 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001989 if (!getLangOptions().CPlusPlus) {
1990 // In C, argument passing is the same as performing an assignment.
1991 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001992
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001993 AssignConvertType ConvTy =
1994 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00001995 if (ConvTy != Compatible &&
1996 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1997 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00001998
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001999 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2000 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002001 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002002
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002003 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002004 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002005 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002006 /*SuppressUserConversions=*/false,
2007 /*AllowExplicit=*/false,
2008 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002009
Sebastian Redl42e92c42009-04-12 17:16:29 +00002010 if (!PerformImplicitConversion(From, ToType, Flavor,
2011 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002012 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002013 if (!DiagnoseAmbiguousUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002014 return Diag(From->getSourceRange().getBegin(),
2015 diag::err_typecheck_convert_incompatible)
2016 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002017 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002018}
2019
Douglas Gregor436424c2008-11-18 23:14:02 +00002020/// TryObjectArgumentInitialization - Try to initialize the object
2021/// parameter of the given member function (@c Method) from the
2022/// expression @p From.
2023ImplicitConversionSequence
2024Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2025 QualType ClassType = Context.getTypeDeclType(Method->getParent());
John McCall8ccfcb52009-09-24 19:53:00 +00002026 QualType ImplicitParamType
2027 = Context.getCVRQualifiedType(ClassType, Method->getTypeQualifiers());
Douglas Gregor436424c2008-11-18 23:14:02 +00002028
2029 // Set up the conversion sequence as a "bad" conversion, to allow us
2030 // to exit early.
2031 ImplicitConversionSequence ICS;
2032 ICS.Standard.setAsIdentityConversion();
2033 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2034
2035 // We need to have an object of class type.
2036 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002037 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002038 FromType = PT->getPointeeType();
2039
2040 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002041
2042 // The implicit object parmeter is has the type "reference to cv X",
2043 // where X is the class of which the function is a member
2044 // (C++ [over.match.funcs]p4). However, when finding an implicit
2045 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002046 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002047 // (C++ [over.match.funcs]p5). We perform a simplified version of
2048 // reference binding here, that allows class rvalues to bind to
2049 // non-constant references.
2050
2051 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2052 // with the implicit object parameter (C++ [over.match.funcs]p5).
2053 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2054 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2055 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2056 return ICS;
2057
2058 // Check that we have either the same type or a derived type. It
2059 // affects the conversion rank.
2060 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2061 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2062 ICS.Standard.Second = ICK_Identity;
2063 else if (IsDerivedFrom(FromType, ClassType))
2064 ICS.Standard.Second = ICK_Derived_To_Base;
2065 else
2066 return ICS;
2067
2068 // Success. Mark this as a reference binding.
2069 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2070 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2071 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2072 ICS.Standard.ReferenceBinding = true;
2073 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002074 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002075 return ICS;
2076}
2077
2078/// PerformObjectArgumentInitialization - Perform initialization of
2079/// the implicit object parameter for the given Method with the given
2080/// expression.
2081bool
2082Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002083 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002084 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002085 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002086
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002087 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002088 FromRecordType = PT->getPointeeType();
2089 DestType = Method->getThisType(Context);
2090 } else {
2091 FromRecordType = From->getType();
2092 DestType = ImplicitParamRecordType;
2093 }
2094
Mike Stump11289f42009-09-09 15:08:12 +00002095 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002096 = TryObjectArgumentInitialization(From, Method);
2097 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2098 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002099 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002100 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002101
Douglas Gregor436424c2008-11-18 23:14:02 +00002102 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002103 CheckDerivedToBaseConversion(FromRecordType,
2104 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002105 From->getSourceRange().getBegin(),
2106 From->getSourceRange()))
2107 return true;
2108
Mike Stump11289f42009-09-09 15:08:12 +00002109 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002110 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002111 return false;
2112}
2113
Douglas Gregor5fb53972009-01-14 15:45:31 +00002114/// TryContextuallyConvertToBool - Attempt to contextually convert the
2115/// expression From to bool (C++0x [conv]p3).
2116ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002117 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002118 // FIXME: Are these flags correct?
2119 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002120 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002121 /*ForceRValue=*/false,
2122 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002123}
2124
2125/// PerformContextuallyConvertToBool - Perform a contextual conversion
2126/// of the expression From to bool (C++0x [conv]p3).
2127bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2128 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2129 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2130 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002131
2132 if (!DiagnoseAmbiguousUserDefinedConversion(From, Context.BoolTy))
2133 return Diag(From->getSourceRange().getBegin(),
2134 diag::err_typecheck_bool_condition)
2135 << From->getType() << From->getSourceRange();
2136 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002137}
2138
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002139/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002140/// candidate functions, using the given function call arguments. If
2141/// @p SuppressUserConversions, then don't allow user-defined
2142/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002143/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2144/// hacky way to implement the overloading rules for elidable copy
2145/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002146///
2147/// \para PartialOverloading true if we are performing "partial" overloading
2148/// based on an incomplete set of function arguments. This feature is used by
2149/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002150void
2151Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002152 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002153 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002154 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002155 bool ForceRValue,
2156 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002157 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002158 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002159 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002160 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002161 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002162 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002163 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002164
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002165 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002166 if (!isa<CXXConstructorDecl>(Method)) {
2167 // If we get here, it's because we're calling a member function
2168 // that is named without a member access expression (e.g.,
2169 // "this->f") that was either written explicitly or created
2170 // implicitly. This can happen with a qualified call to a member
2171 // function, e.g., X::f(). We use a NULL object as the implied
2172 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002173 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002174 SuppressUserConversions, ForceRValue);
2175 return;
2176 }
2177 // We treat a constructor like a non-member function, since its object
2178 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002179 }
2180
2181
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002182 // Add this candidate
2183 CandidateSet.push_back(OverloadCandidate());
2184 OverloadCandidate& Candidate = CandidateSet.back();
2185 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002186 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002187 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002188 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002189
2190 unsigned NumArgsInProto = Proto->getNumArgs();
2191
2192 // (C++ 13.3.2p2): A candidate function having fewer than m
2193 // parameters is viable only if it has an ellipsis in its parameter
2194 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002195 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2196 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002197 Candidate.Viable = false;
2198 return;
2199 }
2200
2201 // (C++ 13.3.2p2): A candidate function having more than m parameters
2202 // is viable only if the (m+1)st parameter has a default argument
2203 // (8.3.6). For the purposes of overload resolution, the
2204 // parameter list is truncated on the right, so that there are
2205 // exactly m parameters.
2206 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002207 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002208 // Not enough arguments.
2209 Candidate.Viable = false;
2210 return;
2211 }
2212
2213 // Determine the implicit conversion sequences for each of the
2214 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002215 Candidate.Conversions.resize(NumArgs);
2216 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2217 if (ArgIdx < NumArgsInProto) {
2218 // (C++ 13.3.2p3): for F to be a viable function, there shall
2219 // exist for each argument an implicit conversion sequence
2220 // (13.3.3.1) that converts that argument to the corresponding
2221 // parameter of F.
2222 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002223 Candidate.Conversions[ArgIdx]
2224 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002225 SuppressUserConversions, ForceRValue,
2226 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002227 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002228 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002229 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002230 break;
2231 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002232 } else {
2233 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2234 // argument for which there is no corresponding parameter is
2235 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002236 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002237 = ImplicitConversionSequence::EllipsisConversion;
2238 }
2239 }
2240}
2241
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002242/// \brief Add all of the function declarations in the given function set to
2243/// the overload canddiate set.
2244void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2245 Expr **Args, unsigned NumArgs,
2246 OverloadCandidateSet& CandidateSet,
2247 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002248 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002249 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002250 F != FEnd; ++F) {
2251 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
Mike Stump11289f42009-09-09 15:08:12 +00002252 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002253 SuppressUserConversions);
2254 else
Douglas Gregor89026b52009-06-30 23:57:56 +00002255 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2256 /*FIXME: explicit args */false, 0, 0,
Mike Stump11289f42009-09-09 15:08:12 +00002257 Args, NumArgs, CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002258 SuppressUserConversions);
2259 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002260}
2261
Douglas Gregor436424c2008-11-18 23:14:02 +00002262/// AddMethodCandidate - Adds the given C++ member function to the set
2263/// of candidate functions, using the given function call arguments
2264/// and the object argument (@c Object). For example, in a call
2265/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2266/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2267/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002268/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2269/// a slightly hacky way to implement the overloading rules for elidable copy
2270/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002271void
Douglas Gregor436424c2008-11-18 23:14:02 +00002272Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2273 Expr **Args, unsigned NumArgs,
2274 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002275 bool SuppressUserConversions, bool ForceRValue) {
2276 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002277 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002278 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002279 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002280 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002281 assert(!isa<CXXConstructorDecl>(Method) &&
2282 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002283
2284 // Add this candidate
2285 CandidateSet.push_back(OverloadCandidate());
2286 OverloadCandidate& Candidate = CandidateSet.back();
2287 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002288 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002289 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002290
2291 unsigned NumArgsInProto = Proto->getNumArgs();
2292
2293 // (C++ 13.3.2p2): A candidate function having fewer than m
2294 // parameters is viable only if it has an ellipsis in its parameter
2295 // list (8.3.5).
2296 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2297 Candidate.Viable = false;
2298 return;
2299 }
2300
2301 // (C++ 13.3.2p2): A candidate function having more than m parameters
2302 // is viable only if the (m+1)st parameter has a default argument
2303 // (8.3.6). For the purposes of overload resolution, the
2304 // parameter list is truncated on the right, so that there are
2305 // exactly m parameters.
2306 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2307 if (NumArgs < MinRequiredArgs) {
2308 // Not enough arguments.
2309 Candidate.Viable = false;
2310 return;
2311 }
2312
2313 Candidate.Viable = true;
2314 Candidate.Conversions.resize(NumArgs + 1);
2315
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002316 if (Method->isStatic() || !Object)
2317 // The implicit object argument is ignored.
2318 Candidate.IgnoreObjectArgument = true;
2319 else {
2320 // Determine the implicit conversion sequence for the object
2321 // parameter.
2322 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002323 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002324 == ImplicitConversionSequence::BadConversion) {
2325 Candidate.Viable = false;
2326 return;
2327 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002328 }
2329
2330 // Determine the implicit conversion sequences for each of the
2331 // arguments.
2332 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2333 if (ArgIdx < NumArgsInProto) {
2334 // (C++ 13.3.2p3): for F to be a viable function, there shall
2335 // exist for each argument an implicit conversion sequence
2336 // (13.3.3.1) that converts that argument to the corresponding
2337 // parameter of F.
2338 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002339 Candidate.Conversions[ArgIdx + 1]
2340 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002341 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002342 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002343 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002344 == ImplicitConversionSequence::BadConversion) {
2345 Candidate.Viable = false;
2346 break;
2347 }
2348 } else {
2349 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2350 // argument for which there is no corresponding parameter is
2351 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002352 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002353 = ImplicitConversionSequence::EllipsisConversion;
2354 }
2355 }
2356}
2357
Douglas Gregor97628d62009-08-21 00:16:32 +00002358/// \brief Add a C++ member function template as a candidate to the candidate
2359/// set, using template argument deduction to produce an appropriate member
2360/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002361void
Douglas Gregor97628d62009-08-21 00:16:32 +00002362Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2363 bool HasExplicitTemplateArgs,
2364 const TemplateArgument *ExplicitTemplateArgs,
2365 unsigned NumExplicitTemplateArgs,
2366 Expr *Object, Expr **Args, unsigned NumArgs,
2367 OverloadCandidateSet& CandidateSet,
2368 bool SuppressUserConversions,
2369 bool ForceRValue) {
2370 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002371 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002372 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002373 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002374 // candidate functions in the usual way.113) A given name can refer to one
2375 // or more function templates and also to a set of overloaded non-template
2376 // functions. In such a case, the candidate functions generated from each
2377 // function template are combined with the set of non-template candidate
2378 // functions.
2379 TemplateDeductionInfo Info(Context);
2380 FunctionDecl *Specialization = 0;
2381 if (TemplateDeductionResult Result
2382 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2383 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2384 Args, NumArgs, Specialization, Info)) {
2385 // FIXME: Record what happened with template argument deduction, so
2386 // that we can give the user a beautiful diagnostic.
2387 (void)Result;
2388 return;
2389 }
Mike Stump11289f42009-09-09 15:08:12 +00002390
Douglas Gregor97628d62009-08-21 00:16:32 +00002391 // Add the function template specialization produced by template argument
2392 // deduction as a candidate.
2393 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002394 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002395 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002396 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002397 CandidateSet, SuppressUserConversions, ForceRValue);
2398}
2399
Douglas Gregor05155d82009-08-21 23:19:43 +00002400/// \brief Add a C++ function template specialization as a candidate
2401/// in the candidate set, using template argument deduction to produce
2402/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002403void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002404Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor89026b52009-06-30 23:57:56 +00002405 bool HasExplicitTemplateArgs,
2406 const TemplateArgument *ExplicitTemplateArgs,
2407 unsigned NumExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002408 Expr **Args, unsigned NumArgs,
2409 OverloadCandidateSet& CandidateSet,
2410 bool SuppressUserConversions,
2411 bool ForceRValue) {
2412 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002413 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002414 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002415 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002416 // candidate functions in the usual way.113) A given name can refer to one
2417 // or more function templates and also to a set of overloaded non-template
2418 // functions. In such a case, the candidate functions generated from each
2419 // function template are combined with the set of non-template candidate
2420 // functions.
2421 TemplateDeductionInfo Info(Context);
2422 FunctionDecl *Specialization = 0;
2423 if (TemplateDeductionResult Result
Douglas Gregor89026b52009-06-30 23:57:56 +00002424 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2425 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2426 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002427 // FIXME: Record what happened with template argument deduction, so
2428 // that we can give the user a beautiful diagnostic.
2429 (void)Result;
2430 return;
2431 }
Mike Stump11289f42009-09-09 15:08:12 +00002432
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002433 // Add the function template specialization produced by template argument
2434 // deduction as a candidate.
2435 assert(Specialization && "Missing function template specialization?");
2436 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2437 SuppressUserConversions, ForceRValue);
2438}
Mike Stump11289f42009-09-09 15:08:12 +00002439
Douglas Gregora1f013e2008-11-07 22:36:19 +00002440/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002441/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002442/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002443/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002444/// (which may or may not be the same type as the type that the
2445/// conversion function produces).
2446void
2447Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2448 Expr *From, QualType ToType,
2449 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002450 assert(!Conversion->getDescribedFunctionTemplate() &&
2451 "Conversion function templates use AddTemplateConversionCandidate");
2452
Douglas Gregora1f013e2008-11-07 22:36:19 +00002453 // Add this candidate
2454 CandidateSet.push_back(OverloadCandidate());
2455 OverloadCandidate& Candidate = CandidateSet.back();
2456 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002457 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002458 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002459 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002460 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002461 = Conversion->getConversionType().getAsOpaquePtr();
2462 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2463
Douglas Gregor436424c2008-11-18 23:14:02 +00002464 // Determine the implicit conversion sequence for the implicit
2465 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002466 Candidate.Viable = true;
2467 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002468 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002469 // Conversion functions to a different type in the base class is visible in
2470 // the derived class. So, a derived to base conversion should not participate
2471 // in overload resolution.
2472 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2473 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002474 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002475 == ImplicitConversionSequence::BadConversion) {
2476 Candidate.Viable = false;
2477 return;
2478 }
2479
2480 // To determine what the conversion from the result of calling the
2481 // conversion function to the type we're eventually trying to
2482 // convert to (ToType), we need to synthesize a call to the
2483 // conversion function and attempt copy initialization from it. This
2484 // makes sure that we get the right semantics with respect to
2485 // lvalues/rvalues and the type. Fortunately, we can allocate this
2486 // call on the stack and we don't need its arguments to be
2487 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002488 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregora1f013e2008-11-07 22:36:19 +00002489 SourceLocation());
2490 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlssona2615922009-07-31 00:48:10 +00002491 CastExpr::CK_Unknown,
Douglas Gregora11693b2008-11-12 17:17:38 +00002492 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002493
2494 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002495 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2496 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002497 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002498 Conversion->getConversionType().getNonReferenceType(),
2499 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002500 ImplicitConversionSequence ICS =
2501 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002502 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002503 /*ForceRValue=*/false,
2504 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002505
Douglas Gregora1f013e2008-11-07 22:36:19 +00002506 switch (ICS.ConversionKind) {
2507 case ImplicitConversionSequence::StandardConversion:
2508 Candidate.FinalConversion = ICS.Standard;
2509 break;
2510
2511 case ImplicitConversionSequence::BadConversion:
2512 Candidate.Viable = false;
2513 break;
2514
2515 default:
Mike Stump11289f42009-09-09 15:08:12 +00002516 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002517 "Can only end up with a standard conversion sequence or failure");
2518 }
2519}
2520
Douglas Gregor05155d82009-08-21 23:19:43 +00002521/// \brief Adds a conversion function template specialization
2522/// candidate to the overload set, using template argument deduction
2523/// to deduce the template arguments of the conversion function
2524/// template from the type that we are converting to (C++
2525/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002526void
Douglas Gregor05155d82009-08-21 23:19:43 +00002527Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2528 Expr *From, QualType ToType,
2529 OverloadCandidateSet &CandidateSet) {
2530 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2531 "Only conversion function templates permitted here");
2532
2533 TemplateDeductionInfo Info(Context);
2534 CXXConversionDecl *Specialization = 0;
2535 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002536 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002537 Specialization, Info)) {
2538 // FIXME: Record what happened with template argument deduction, so
2539 // that we can give the user a beautiful diagnostic.
2540 (void)Result;
2541 return;
2542 }
Mike Stump11289f42009-09-09 15:08:12 +00002543
Douglas Gregor05155d82009-08-21 23:19:43 +00002544 // Add the conversion function template specialization produced by
2545 // template argument deduction as a candidate.
2546 assert(Specialization && "Missing function template specialization?");
2547 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2548}
2549
Douglas Gregorab7897a2008-11-19 22:57:39 +00002550/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2551/// converts the given @c Object to a function pointer via the
2552/// conversion function @c Conversion, and then attempts to call it
2553/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2554/// the type of function that we'll eventually be calling.
2555void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002556 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002557 Expr *Object, Expr **Args, unsigned NumArgs,
2558 OverloadCandidateSet& CandidateSet) {
2559 CandidateSet.push_back(OverloadCandidate());
2560 OverloadCandidate& Candidate = CandidateSet.back();
2561 Candidate.Function = 0;
2562 Candidate.Surrogate = Conversion;
2563 Candidate.Viable = true;
2564 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002565 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002566 Candidate.Conversions.resize(NumArgs + 1);
2567
2568 // Determine the implicit conversion sequence for the implicit
2569 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002570 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002571 = TryObjectArgumentInitialization(Object, Conversion);
2572 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2573 Candidate.Viable = false;
2574 return;
2575 }
2576
2577 // The first conversion is actually a user-defined conversion whose
2578 // first conversion is ObjectInit's standard conversion (which is
2579 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002580 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002581 = ImplicitConversionSequence::UserDefinedConversion;
2582 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2583 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002584 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002585 = Candidate.Conversions[0].UserDefined.Before;
2586 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2587
Mike Stump11289f42009-09-09 15:08:12 +00002588 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002589 unsigned NumArgsInProto = Proto->getNumArgs();
2590
2591 // (C++ 13.3.2p2): A candidate function having fewer than m
2592 // parameters is viable only if it has an ellipsis in its parameter
2593 // list (8.3.5).
2594 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2595 Candidate.Viable = false;
2596 return;
2597 }
2598
2599 // Function types don't have any default arguments, so just check if
2600 // we have enough arguments.
2601 if (NumArgs < NumArgsInProto) {
2602 // Not enough arguments.
2603 Candidate.Viable = false;
2604 return;
2605 }
2606
2607 // Determine the implicit conversion sequences for each of the
2608 // arguments.
2609 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2610 if (ArgIdx < NumArgsInProto) {
2611 // (C++ 13.3.2p3): for F to be a viable function, there shall
2612 // exist for each argument an implicit conversion sequence
2613 // (13.3.3.1) that converts that argument to the corresponding
2614 // parameter of F.
2615 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002616 Candidate.Conversions[ArgIdx + 1]
2617 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002618 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002619 /*ForceRValue=*/false,
2620 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002621 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002622 == ImplicitConversionSequence::BadConversion) {
2623 Candidate.Viable = false;
2624 break;
2625 }
2626 } else {
2627 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2628 // argument for which there is no corresponding parameter is
2629 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002630 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002631 = ImplicitConversionSequence::EllipsisConversion;
2632 }
2633 }
2634}
2635
Mike Stump87c57ac2009-05-16 07:39:55 +00002636// FIXME: This will eventually be removed, once we've migrated all of the
2637// operator overloading logic over to the scheme used by binary operators, which
2638// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002639void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002640 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002641 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002642 OverloadCandidateSet& CandidateSet,
2643 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002644
2645 FunctionSet Functions;
2646
2647 QualType T1 = Args[0]->getType();
2648 QualType T2;
2649 if (NumArgs > 1)
2650 T2 = Args[1]->getType();
2651
2652 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002653 if (S)
2654 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002655 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2656 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2657 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2658 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2659}
2660
2661/// \brief Add overload candidates for overloaded operators that are
2662/// member functions.
2663///
2664/// Add the overloaded operator candidates that are member functions
2665/// for the operator Op that was used in an operator expression such
2666/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2667/// CandidateSet will store the added overload candidates. (C++
2668/// [over.match.oper]).
2669void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2670 SourceLocation OpLoc,
2671 Expr **Args, unsigned NumArgs,
2672 OverloadCandidateSet& CandidateSet,
2673 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002674 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2675
2676 // C++ [over.match.oper]p3:
2677 // For a unary operator @ with an operand of a type whose
2678 // cv-unqualified version is T1, and for a binary operator @ with
2679 // a left operand of a type whose cv-unqualified version is T1 and
2680 // a right operand of a type whose cv-unqualified version is T2,
2681 // three sets of candidate functions, designated member
2682 // candidates, non-member candidates and built-in candidates, are
2683 // constructed as follows:
2684 QualType T1 = Args[0]->getType();
2685 QualType T2;
2686 if (NumArgs > 1)
2687 T2 = Args[1]->getType();
2688
2689 // -- If T1 is a class type, the set of member candidates is the
2690 // result of the qualified lookup of T1::operator@
2691 // (13.3.1.1.1); otherwise, the set of member candidates is
2692 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002693 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002694 // Complete the type if it can be completed. Otherwise, we're done.
2695 if (RequireCompleteType(OpLoc, T1, PartialDiagnostic(0)))
2696 return;
Mike Stump11289f42009-09-09 15:08:12 +00002697
2698 LookupResult Operators = LookupQualifiedName(T1Rec->getDecl(), OpName,
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002699 LookupOrdinaryName, false);
Mike Stump11289f42009-09-09 15:08:12 +00002700 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002701 OperEnd = Operators.end();
2702 Oper != OperEnd;
2703 ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00002704 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
Douglas Gregor55297ac2008-12-23 00:26:44 +00002705 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor436424c2008-11-18 23:14:02 +00002706 /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002707 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002708}
2709
Douglas Gregora11693b2008-11-12 17:17:38 +00002710/// AddBuiltinCandidate - Add a candidate for a built-in
2711/// operator. ResultTy and ParamTys are the result and parameter types
2712/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002713/// arguments being passed to the candidate. IsAssignmentOperator
2714/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002715/// operator. NumContextualBoolArguments is the number of arguments
2716/// (at the beginning of the argument list) that will be contextually
2717/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002718void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002719 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002720 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002721 bool IsAssignmentOperator,
2722 unsigned NumContextualBoolArguments) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002723 // Add this candidate
2724 CandidateSet.push_back(OverloadCandidate());
2725 OverloadCandidate& Candidate = CandidateSet.back();
2726 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002727 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002728 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002729 Candidate.BuiltinTypes.ResultTy = ResultTy;
2730 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2731 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2732
2733 // Determine the implicit conversion sequences for each of the
2734 // arguments.
2735 Candidate.Viable = true;
2736 Candidate.Conversions.resize(NumArgs);
2737 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002738 // C++ [over.match.oper]p4:
2739 // For the built-in assignment operators, conversions of the
2740 // left operand are restricted as follows:
2741 // -- no temporaries are introduced to hold the left operand, and
2742 // -- no user-defined conversions are applied to the left
2743 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002744 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002745 //
2746 // We block these conversions by turning off user-defined
2747 // conversions, since that is the only way that initialization of
2748 // a reference to a non-class type can occur from something that
2749 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002750 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002751 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002752 "Contextual conversion to bool requires bool type");
2753 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2754 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002755 Candidate.Conversions[ArgIdx]
2756 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002757 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002758 /*ForceRValue=*/false,
2759 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002760 }
Mike Stump11289f42009-09-09 15:08:12 +00002761 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002762 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002763 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002764 break;
2765 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002766 }
2767}
2768
2769/// BuiltinCandidateTypeSet - A set of types that will be used for the
2770/// candidate operator functions for built-in operators (C++
2771/// [over.built]). The types are separated into pointer types and
2772/// enumeration types.
2773class BuiltinCandidateTypeSet {
2774 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002775 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002776
2777 /// PointerTypes - The set of pointer types that will be used in the
2778 /// built-in candidates.
2779 TypeSet PointerTypes;
2780
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002781 /// MemberPointerTypes - The set of member pointer types that will be
2782 /// used in the built-in candidates.
2783 TypeSet MemberPointerTypes;
2784
Douglas Gregora11693b2008-11-12 17:17:38 +00002785 /// EnumerationTypes - The set of enumeration types that will be
2786 /// used in the built-in candidates.
2787 TypeSet EnumerationTypes;
2788
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002789 /// Sema - The semantic analysis instance where we are building the
2790 /// candidate type set.
2791 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002792
Douglas Gregora11693b2008-11-12 17:17:38 +00002793 /// Context - The AST context in which we will build the type sets.
2794 ASTContext &Context;
2795
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002796 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2797 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002798
2799public:
2800 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002801 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002802
Mike Stump11289f42009-09-09 15:08:12 +00002803 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002804 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002805
Douglas Gregor5fb53972009-01-14 15:45:31 +00002806 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2807 bool AllowExplicitConversions);
Douglas Gregora11693b2008-11-12 17:17:38 +00002808
2809 /// pointer_begin - First pointer type found;
2810 iterator pointer_begin() { return PointerTypes.begin(); }
2811
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002812 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002813 iterator pointer_end() { return PointerTypes.end(); }
2814
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002815 /// member_pointer_begin - First member pointer type found;
2816 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2817
2818 /// member_pointer_end - Past the last member pointer type found;
2819 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2820
Douglas Gregora11693b2008-11-12 17:17:38 +00002821 /// enumeration_begin - First enumeration type found;
2822 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2823
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002824 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002825 iterator enumeration_end() { return EnumerationTypes.end(); }
2826};
2827
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002828/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00002829/// the set of pointer types along with any more-qualified variants of
2830/// that type. For example, if @p Ty is "int const *", this routine
2831/// will add "int const *", "int const volatile *", "int const
2832/// restrict *", and "int const volatile restrict *" to the set of
2833/// pointer types. Returns true if the add of @p Ty itself succeeded,
2834/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00002835///
2836/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002837bool
2838BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
John McCall8ccfcb52009-09-24 19:53:00 +00002839
Douglas Gregora11693b2008-11-12 17:17:38 +00002840 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002841 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002842 return false;
2843
John McCall8ccfcb52009-09-24 19:53:00 +00002844 const PointerType *PointerTy = Ty->getAs<PointerType>();
2845 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00002846
John McCall8ccfcb52009-09-24 19:53:00 +00002847 QualType PointeeTy = PointerTy->getPointeeType();
2848 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
2849
2850 // Iterate through all strict supersets of BaseCVR.
2851 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
2852 if ((CVR | BaseCVR) != CVR) continue;
2853
2854 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
2855 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00002856 }
2857
2858 return true;
2859}
2860
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002861/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2862/// to the set of pointer types along with any more-qualified variants of
2863/// that type. For example, if @p Ty is "int const *", this routine
2864/// will add "int const *", "int const volatile *", "int const
2865/// restrict *", and "int const volatile restrict *" to the set of
2866/// pointer types. Returns true if the add of @p Ty itself succeeded,
2867/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00002868///
2869/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002870bool
2871BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2872 QualType Ty) {
2873 // Insert this type.
2874 if (!MemberPointerTypes.insert(Ty))
2875 return false;
2876
John McCall8ccfcb52009-09-24 19:53:00 +00002877 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
2878 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002879
John McCall8ccfcb52009-09-24 19:53:00 +00002880 QualType PointeeTy = PointerTy->getPointeeType();
2881 const Type *ClassTy = PointerTy->getClass();
2882
2883 // Iterate through all strict supersets of the pointee type's CVR
2884 // qualifiers.
2885 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
2886 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
2887 if ((CVR | BaseCVR) != CVR) continue;
2888
2889 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
2890 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002891 }
2892
2893 return true;
2894}
2895
Douglas Gregora11693b2008-11-12 17:17:38 +00002896/// AddTypesConvertedFrom - Add each of the types to which the type @p
2897/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002898/// primarily interested in pointer types and enumeration types. We also
2899/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002900/// AllowUserConversions is true if we should look at the conversion
2901/// functions of a class type, and AllowExplicitConversions if we
2902/// should also include the explicit conversion functions of a class
2903/// type.
Mike Stump11289f42009-09-09 15:08:12 +00002904void
Douglas Gregor5fb53972009-01-14 15:45:31 +00002905BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2906 bool AllowUserConversions,
2907 bool AllowExplicitConversions) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002908 // Only deal with canonical types.
2909 Ty = Context.getCanonicalType(Ty);
2910
2911 // Look through reference types; they aren't part of the type of an
2912 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002913 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00002914 Ty = RefTy->getPointeeType();
2915
2916 // We don't care about qualifiers on the type.
2917 Ty = Ty.getUnqualifiedType();
2918
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002919 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002920 QualType PointeeTy = PointerTy->getPointeeType();
2921
2922 // Insert our type, and its more-qualified variants, into the set
2923 // of types.
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002924 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002925 return;
2926
2927 // Add 'cv void*' to our set of types.
2928 if (!Ty->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002929 QualType QualVoid
John McCall8ccfcb52009-09-24 19:53:00 +00002930 = Context.getCVRQualifiedType(Context.VoidTy,
2931 PointeeTy.getCVRQualifiers());
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002932 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregora11693b2008-11-12 17:17:38 +00002933 }
2934
2935 // If this is a pointer to a class type, add pointers to its bases
2936 // (with the same level of cv-qualification as the original
2937 // derived class, of course).
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002938 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002939 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2940 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2941 Base != ClassDecl->bases_end(); ++Base) {
2942 QualType BaseTy = Context.getCanonicalType(Base->getType());
John McCall8ccfcb52009-09-24 19:53:00 +00002943 BaseTy = Context.getCVRQualifiedType(BaseTy.getUnqualifiedType(),
2944 PointeeTy.getCVRQualifiers());
Douglas Gregora11693b2008-11-12 17:17:38 +00002945
2946 // Add the pointer type, recursively, so that we get all of
2947 // the indirect base classes, too.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002948 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00002949 }
2950 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002951 } else if (Ty->isMemberPointerType()) {
2952 // Member pointers are far easier, since the pointee can't be converted.
2953 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2954 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00002955 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00002956 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002957 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002958 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002959 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2960 // No conversion functions in incomplete types.
2961 return;
2962 }
Mike Stump11289f42009-09-09 15:08:12 +00002963
Douglas Gregora11693b2008-11-12 17:17:38 +00002964 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2965 // FIXME: Visit conversion functions in the base classes, too.
Mike Stump11289f42009-09-09 15:08:12 +00002966 OverloadedFunctionDecl *Conversions
Douglas Gregora11693b2008-11-12 17:17:38 +00002967 = ClassDecl->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00002968 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregora11693b2008-11-12 17:17:38 +00002969 = Conversions->function_begin();
2970 Func != Conversions->function_end(); ++Func) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002971 CXXConversionDecl *Conv;
2972 FunctionTemplateDecl *ConvTemplate;
2973 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2974
Mike Stump11289f42009-09-09 15:08:12 +00002975 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00002976 // about which builtin types we can convert to.
2977 if (ConvTemplate)
2978 continue;
2979
Douglas Gregor5fb53972009-01-14 15:45:31 +00002980 if (AllowExplicitConversions || !Conv->isExplicit())
2981 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00002982 }
2983 }
2984 }
2985}
2986
Douglas Gregor84605ae2009-08-24 13:43:27 +00002987/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2988/// the volatile- and non-volatile-qualified assignment operators for the
2989/// given type to the candidate set.
2990static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2991 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00002992 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00002993 unsigned NumArgs,
2994 OverloadCandidateSet &CandidateSet) {
2995 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002996
Douglas Gregor84605ae2009-08-24 13:43:27 +00002997 // T& operator=(T&, T)
2998 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2999 ParamTypes[1] = T;
3000 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3001 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003002
Douglas Gregor84605ae2009-08-24 13:43:27 +00003003 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3004 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003005 ParamTypes[0]
3006 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003007 ParamTypes[1] = T;
3008 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003009 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003010 }
3011}
Mike Stump11289f42009-09-09 15:08:12 +00003012
Douglas Gregord08452f2008-11-19 15:42:04 +00003013/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3014/// operator overloads to the candidate set (C++ [over.built]), based
3015/// on the operator @p Op and the arguments given. For example, if the
3016/// operator is a binary '+', this routine might add "int
3017/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003018void
Mike Stump11289f42009-09-09 15:08:12 +00003019Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregord08452f2008-11-19 15:42:04 +00003020 Expr **Args, unsigned NumArgs,
3021 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003022 // The set of "promoted arithmetic types", which are the arithmetic
3023 // types are that preserved by promotion (C++ [over.built]p2). Note
3024 // that the first few of these types are the promoted integral
3025 // types; these types need to be first.
3026 // FIXME: What about complex?
3027 const unsigned FirstIntegralType = 0;
3028 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003029 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003030 LastPromotedIntegralType = 13;
3031 const unsigned FirstPromotedArithmeticType = 7,
3032 LastPromotedArithmeticType = 16;
3033 const unsigned NumArithmeticTypes = 16;
3034 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003035 Context.BoolTy, Context.CharTy, Context.WCharTy,
3036// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003037 Context.SignedCharTy, Context.ShortTy,
3038 Context.UnsignedCharTy, Context.UnsignedShortTy,
3039 Context.IntTy, Context.LongTy, Context.LongLongTy,
3040 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3041 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3042 };
3043
3044 // Find all of the types that the arguments can convert to, but only
3045 // if the operator we're looking at has built-in operator candidates
3046 // that make use of these types.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003047 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003048 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3049 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003050 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003051 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003052 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003053 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003054 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003055 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3056 true,
3057 (Op == OO_Exclaim ||
3058 Op == OO_AmpAmp ||
3059 Op == OO_PipePipe));
Douglas Gregora11693b2008-11-12 17:17:38 +00003060 }
3061
3062 bool isComparison = false;
3063 switch (Op) {
3064 case OO_None:
3065 case NUM_OVERLOADED_OPERATORS:
3066 assert(false && "Expected an overloaded operator");
3067 break;
3068
Douglas Gregord08452f2008-11-19 15:42:04 +00003069 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003070 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003071 goto UnaryStar;
3072 else
3073 goto BinaryStar;
3074 break;
3075
3076 case OO_Plus: // '+' is either unary or binary
3077 if (NumArgs == 1)
3078 goto UnaryPlus;
3079 else
3080 goto BinaryPlus;
3081 break;
3082
3083 case OO_Minus: // '-' is either unary or binary
3084 if (NumArgs == 1)
3085 goto UnaryMinus;
3086 else
3087 goto BinaryMinus;
3088 break;
3089
3090 case OO_Amp: // '&' is either unary or binary
3091 if (NumArgs == 1)
3092 goto UnaryAmp;
3093 else
3094 goto BinaryAmp;
3095
3096 case OO_PlusPlus:
3097 case OO_MinusMinus:
3098 // C++ [over.built]p3:
3099 //
3100 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3101 // is either volatile or empty, there exist candidate operator
3102 // functions of the form
3103 //
3104 // VQ T& operator++(VQ T&);
3105 // T operator++(VQ T&, int);
3106 //
3107 // C++ [over.built]p4:
3108 //
3109 // For every pair (T, VQ), where T is an arithmetic type other
3110 // than bool, and VQ is either volatile or empty, there exist
3111 // candidate operator functions of the form
3112 //
3113 // VQ T& operator--(VQ T&);
3114 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003115 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003116 Arith < NumArithmeticTypes; ++Arith) {
3117 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003118 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003119 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003120
3121 // Non-volatile version.
3122 if (NumArgs == 1)
3123 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3124 else
3125 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3126
3127 // Volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003128 ParamTypes[0]
3129 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
Douglas Gregord08452f2008-11-19 15:42:04 +00003130 if (NumArgs == 1)
3131 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3132 else
3133 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3134 }
3135
3136 // C++ [over.built]p5:
3137 //
3138 // For every pair (T, VQ), where T is a cv-qualified or
3139 // cv-unqualified object type, and VQ is either volatile or
3140 // empty, there exist candidate operator functions of the form
3141 //
3142 // T*VQ& operator++(T*VQ&);
3143 // T*VQ& operator--(T*VQ&);
3144 // T* operator++(T*VQ&, int);
3145 // T* operator--(T*VQ&, int);
3146 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3147 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3148 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003149 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003150 continue;
3151
Mike Stump11289f42009-09-09 15:08:12 +00003152 QualType ParamTypes[2] = {
3153 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003154 };
Mike Stump11289f42009-09-09 15:08:12 +00003155
Douglas Gregord08452f2008-11-19 15:42:04 +00003156 // Without volatile
3157 if (NumArgs == 1)
3158 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3159 else
3160 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3161
3162 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3163 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003164 ParamTypes[0]
3165 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003166 if (NumArgs == 1)
3167 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3168 else
3169 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3170 }
3171 }
3172 break;
3173
3174 UnaryStar:
3175 // C++ [over.built]p6:
3176 // For every cv-qualified or cv-unqualified object type T, there
3177 // exist candidate operator functions of the form
3178 //
3179 // T& operator*(T*);
3180 //
3181 // C++ [over.built]p7:
3182 // For every function type T, there exist candidate operator
3183 // functions of the form
3184 // T& operator*(T*);
3185 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3186 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3187 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003188 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003189 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003190 &ParamTy, Args, 1, CandidateSet);
3191 }
3192 break;
3193
3194 UnaryPlus:
3195 // C++ [over.built]p8:
3196 // For every type T, there exist candidate operator functions of
3197 // the form
3198 //
3199 // T* operator+(T*);
3200 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3201 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3202 QualType ParamTy = *Ptr;
3203 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3204 }
Mike Stump11289f42009-09-09 15:08:12 +00003205
Douglas Gregord08452f2008-11-19 15:42:04 +00003206 // Fall through
3207
3208 UnaryMinus:
3209 // C++ [over.built]p9:
3210 // For every promoted arithmetic type T, there exist candidate
3211 // operator functions of the form
3212 //
3213 // T operator+(T);
3214 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003215 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003216 Arith < LastPromotedArithmeticType; ++Arith) {
3217 QualType ArithTy = ArithmeticTypes[Arith];
3218 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3219 }
3220 break;
3221
3222 case OO_Tilde:
3223 // C++ [over.built]p10:
3224 // For every promoted integral type T, there exist candidate
3225 // operator functions of the form
3226 //
3227 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003228 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003229 Int < LastPromotedIntegralType; ++Int) {
3230 QualType IntTy = ArithmeticTypes[Int];
3231 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3232 }
3233 break;
3234
Douglas Gregora11693b2008-11-12 17:17:38 +00003235 case OO_New:
3236 case OO_Delete:
3237 case OO_Array_New:
3238 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003239 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003240 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003241 break;
3242
3243 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003244 UnaryAmp:
3245 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003246 // C++ [over.match.oper]p3:
3247 // -- For the operator ',', the unary operator '&', or the
3248 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003249 break;
3250
Douglas Gregor84605ae2009-08-24 13:43:27 +00003251 case OO_EqualEqual:
3252 case OO_ExclaimEqual:
3253 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003254 // For every pointer to member type T, there exist candidate operator
3255 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003256 //
3257 // bool operator==(T,T);
3258 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003259 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003260 MemPtr = CandidateTypes.member_pointer_begin(),
3261 MemPtrEnd = CandidateTypes.member_pointer_end();
3262 MemPtr != MemPtrEnd;
3263 ++MemPtr) {
3264 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3265 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3266 }
Mike Stump11289f42009-09-09 15:08:12 +00003267
Douglas Gregor84605ae2009-08-24 13:43:27 +00003268 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003269
Douglas Gregora11693b2008-11-12 17:17:38 +00003270 case OO_Less:
3271 case OO_Greater:
3272 case OO_LessEqual:
3273 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003274 // C++ [over.built]p15:
3275 //
3276 // For every pointer or enumeration type T, there exist
3277 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003278 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003279 // bool operator<(T, T);
3280 // bool operator>(T, T);
3281 // bool operator<=(T, T);
3282 // bool operator>=(T, T);
3283 // bool operator==(T, T);
3284 // bool operator!=(T, T);
3285 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3286 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3287 QualType ParamTypes[2] = { *Ptr, *Ptr };
3288 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3289 }
Mike Stump11289f42009-09-09 15:08:12 +00003290 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003291 = CandidateTypes.enumeration_begin();
3292 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3293 QualType ParamTypes[2] = { *Enum, *Enum };
3294 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3295 }
3296
3297 // Fall through.
3298 isComparison = true;
3299
Douglas Gregord08452f2008-11-19 15:42:04 +00003300 BinaryPlus:
3301 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003302 if (!isComparison) {
3303 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3304
3305 // C++ [over.built]p13:
3306 //
3307 // For every cv-qualified or cv-unqualified object type T
3308 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003309 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003310 // T* operator+(T*, ptrdiff_t);
3311 // T& operator[](T*, ptrdiff_t); [BELOW]
3312 // T* operator-(T*, ptrdiff_t);
3313 // T* operator+(ptrdiff_t, T*);
3314 // T& operator[](ptrdiff_t, T*); [BELOW]
3315 //
3316 // C++ [over.built]p14:
3317 //
3318 // For every T, where T is a pointer to object type, there
3319 // exist candidate operator functions of the form
3320 //
3321 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003322 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003323 = CandidateTypes.pointer_begin();
3324 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3325 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3326
3327 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3328 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3329
3330 if (Op == OO_Plus) {
3331 // T* operator+(ptrdiff_t, T*);
3332 ParamTypes[0] = ParamTypes[1];
3333 ParamTypes[1] = *Ptr;
3334 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3335 } else {
3336 // ptrdiff_t operator-(T, T);
3337 ParamTypes[1] = *Ptr;
3338 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3339 Args, 2, CandidateSet);
3340 }
3341 }
3342 }
3343 // Fall through
3344
Douglas Gregora11693b2008-11-12 17:17:38 +00003345 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003346 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003347 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003348 // C++ [over.built]p12:
3349 //
3350 // For every pair of promoted arithmetic types L and R, there
3351 // exist candidate operator functions of the form
3352 //
3353 // LR operator*(L, R);
3354 // LR operator/(L, R);
3355 // LR operator+(L, R);
3356 // LR operator-(L, R);
3357 // bool operator<(L, R);
3358 // bool operator>(L, R);
3359 // bool operator<=(L, R);
3360 // bool operator>=(L, R);
3361 // bool operator==(L, R);
3362 // bool operator!=(L, R);
3363 //
3364 // where LR is the result of the usual arithmetic conversions
3365 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003366 //
3367 // C++ [over.built]p24:
3368 //
3369 // For every pair of promoted arithmetic types L and R, there exist
3370 // candidate operator functions of the form
3371 //
3372 // LR operator?(bool, L, R);
3373 //
3374 // where LR is the result of the usual arithmetic conversions
3375 // between types L and R.
3376 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003377 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003378 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003379 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003380 Right < LastPromotedArithmeticType; ++Right) {
3381 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003382 QualType Result
3383 = isComparison
3384 ? Context.BoolTy
3385 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003386 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3387 }
3388 }
3389 break;
3390
3391 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003392 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003393 case OO_Caret:
3394 case OO_Pipe:
3395 case OO_LessLess:
3396 case OO_GreaterGreater:
3397 // C++ [over.built]p17:
3398 //
3399 // For every pair of promoted integral types L and R, there
3400 // exist candidate operator functions of the form
3401 //
3402 // LR operator%(L, R);
3403 // LR operator&(L, R);
3404 // LR operator^(L, R);
3405 // LR operator|(L, R);
3406 // L operator<<(L, R);
3407 // L operator>>(L, R);
3408 //
3409 // where LR is the result of the usual arithmetic conversions
3410 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003411 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003412 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003413 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003414 Right < LastPromotedIntegralType; ++Right) {
3415 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3416 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3417 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003418 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003419 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3420 }
3421 }
3422 break;
3423
3424 case OO_Equal:
3425 // C++ [over.built]p20:
3426 //
3427 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003428 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003429 // empty, there exist candidate operator functions of the form
3430 //
3431 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003432 for (BuiltinCandidateTypeSet::iterator
3433 Enum = CandidateTypes.enumeration_begin(),
3434 EnumEnd = CandidateTypes.enumeration_end();
3435 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003436 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003437 CandidateSet);
3438 for (BuiltinCandidateTypeSet::iterator
3439 MemPtr = CandidateTypes.member_pointer_begin(),
3440 MemPtrEnd = CandidateTypes.member_pointer_end();
3441 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003442 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003443 CandidateSet);
3444 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003445
3446 case OO_PlusEqual:
3447 case OO_MinusEqual:
3448 // C++ [over.built]p19:
3449 //
3450 // For every pair (T, VQ), where T is any type and VQ is either
3451 // volatile or empty, there exist candidate operator functions
3452 // of the form
3453 //
3454 // T*VQ& operator=(T*VQ&, T*);
3455 //
3456 // C++ [over.built]p21:
3457 //
3458 // For every pair (T, VQ), where T is a cv-qualified or
3459 // cv-unqualified object type and VQ is either volatile or
3460 // empty, there exist candidate operator functions of the form
3461 //
3462 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3463 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3464 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3465 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3466 QualType ParamTypes[2];
3467 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3468
3469 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003470 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003471 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3472 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003473
Douglas Gregord08452f2008-11-19 15:42:04 +00003474 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3475 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003476 ParamTypes[0]
3477 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003478 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3479 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003480 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003481 }
3482 // Fall through.
3483
3484 case OO_StarEqual:
3485 case OO_SlashEqual:
3486 // C++ [over.built]p18:
3487 //
3488 // For every triple (L, VQ, R), where L is an arithmetic type,
3489 // VQ is either volatile or empty, and R is a promoted
3490 // arithmetic type, there exist candidate operator functions of
3491 // the form
3492 //
3493 // VQ L& operator=(VQ L&, R);
3494 // VQ L& operator*=(VQ L&, R);
3495 // VQ L& operator/=(VQ L&, R);
3496 // VQ L& operator+=(VQ L&, R);
3497 // VQ L& operator-=(VQ L&, R);
3498 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003499 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003500 Right < LastPromotedArithmeticType; ++Right) {
3501 QualType ParamTypes[2];
3502 ParamTypes[1] = ArithmeticTypes[Right];
3503
3504 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003505 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003506 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3507 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003508
3509 // Add this built-in operator as a candidate (VQ is 'volatile').
John McCall8ccfcb52009-09-24 19:53:00 +00003510 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003511 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003512 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3513 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003514 }
3515 }
3516 break;
3517
3518 case OO_PercentEqual:
3519 case OO_LessLessEqual:
3520 case OO_GreaterGreaterEqual:
3521 case OO_AmpEqual:
3522 case OO_CaretEqual:
3523 case OO_PipeEqual:
3524 // C++ [over.built]p22:
3525 //
3526 // For every triple (L, VQ, R), where L is an integral type, VQ
3527 // is either volatile or empty, and R is a promoted integral
3528 // type, there exist candidate operator functions of the form
3529 //
3530 // VQ L& operator%=(VQ L&, R);
3531 // VQ L& operator<<=(VQ L&, R);
3532 // VQ L& operator>>=(VQ L&, R);
3533 // VQ L& operator&=(VQ L&, R);
3534 // VQ L& operator^=(VQ L&, R);
3535 // VQ L& operator|=(VQ L&, R);
3536 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003537 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003538 Right < LastPromotedIntegralType; ++Right) {
3539 QualType ParamTypes[2];
3540 ParamTypes[1] = ArithmeticTypes[Right];
3541
3542 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003543 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003544 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3545
3546 // Add this built-in operator as a candidate (VQ is 'volatile').
3547 ParamTypes[0] = ArithmeticTypes[Left];
John McCall8ccfcb52009-09-24 19:53:00 +00003548 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003549 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003550 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3551 }
3552 }
3553 break;
3554
Douglas Gregord08452f2008-11-19 15:42:04 +00003555 case OO_Exclaim: {
3556 // C++ [over.operator]p23:
3557 //
3558 // There also exist candidate operator functions of the form
3559 //
Mike Stump11289f42009-09-09 15:08:12 +00003560 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003561 // bool operator&&(bool, bool); [BELOW]
3562 // bool operator||(bool, bool); [BELOW]
3563 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003564 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3565 /*IsAssignmentOperator=*/false,
3566 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003567 break;
3568 }
3569
Douglas Gregora11693b2008-11-12 17:17:38 +00003570 case OO_AmpAmp:
3571 case OO_PipePipe: {
3572 // C++ [over.operator]p23:
3573 //
3574 // There also exist candidate operator functions of the form
3575 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003576 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003577 // bool operator&&(bool, bool);
3578 // bool operator||(bool, bool);
3579 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003580 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3581 /*IsAssignmentOperator=*/false,
3582 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003583 break;
3584 }
3585
3586 case OO_Subscript:
3587 // C++ [over.built]p13:
3588 //
3589 // For every cv-qualified or cv-unqualified object type T there
3590 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003591 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003592 // T* operator+(T*, ptrdiff_t); [ABOVE]
3593 // T& operator[](T*, ptrdiff_t);
3594 // T* operator-(T*, ptrdiff_t); [ABOVE]
3595 // T* operator+(ptrdiff_t, T*); [ABOVE]
3596 // T& operator[](ptrdiff_t, T*);
3597 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3598 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3599 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003600 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003601 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003602
3603 // T& operator[](T*, ptrdiff_t)
3604 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3605
3606 // T& operator[](ptrdiff_t, T*);
3607 ParamTypes[0] = ParamTypes[1];
3608 ParamTypes[1] = *Ptr;
3609 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3610 }
3611 break;
3612
3613 case OO_ArrowStar:
3614 // FIXME: No support for pointer-to-members yet.
3615 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003616
3617 case OO_Conditional:
3618 // Note that we don't consider the first argument, since it has been
3619 // contextually converted to bool long ago. The candidates below are
3620 // therefore added as binary.
3621 //
3622 // C++ [over.built]p24:
3623 // For every type T, where T is a pointer or pointer-to-member type,
3624 // there exist candidate operator functions of the form
3625 //
3626 // T operator?(bool, T, T);
3627 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003628 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3629 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3630 QualType ParamTypes[2] = { *Ptr, *Ptr };
3631 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3632 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003633 for (BuiltinCandidateTypeSet::iterator Ptr =
3634 CandidateTypes.member_pointer_begin(),
3635 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3636 QualType ParamTypes[2] = { *Ptr, *Ptr };
3637 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3638 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003639 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003640 }
3641}
3642
Douglas Gregore254f902009-02-04 00:32:51 +00003643/// \brief Add function candidates found via argument-dependent lookup
3644/// to the set of overloading candidates.
3645///
3646/// This routine performs argument-dependent name lookup based on the
3647/// given function name (which may also be an operator name) and adds
3648/// all of the overload candidates found by ADL to the overload
3649/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003650void
Douglas Gregore254f902009-02-04 00:32:51 +00003651Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3652 Expr **Args, unsigned NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003653 bool HasExplicitTemplateArgs,
3654 const TemplateArgument *ExplicitTemplateArgs,
3655 unsigned NumExplicitTemplateArgs,
3656 OverloadCandidateSet& CandidateSet,
3657 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003658 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003659
Douglas Gregorcabea402009-09-22 15:41:20 +00003660 // FIXME: Should we be trafficking in canonical function decls throughout?
3661
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003662 // Record all of the function candidates that we've already
3663 // added to the overload set, so that we don't add those same
3664 // candidates a second time.
3665 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3666 CandEnd = CandidateSet.end();
3667 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003668 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003669 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003670 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3671 Functions.insert(FunTmpl);
3672 }
Douglas Gregore254f902009-02-04 00:32:51 +00003673
Douglas Gregorcabea402009-09-22 15:41:20 +00003674 // FIXME: Pass in the explicit template arguments?
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003675 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003676
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003677 // Erase all of the candidates we already knew about.
3678 // FIXME: This is suboptimal. Is there a better way?
3679 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3680 CandEnd = CandidateSet.end();
3681 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003682 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003683 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003684 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3685 Functions.erase(FunTmpl);
3686 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003687
3688 // For each of the ADL candidates we found, add it to the overload
3689 // set.
3690 for (FunctionSet::iterator Func = Functions.begin(),
3691 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00003692 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003693 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3694 if (HasExplicitTemplateArgs)
3695 continue;
3696
3697 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3698 false, false, PartialOverloading);
3699 } else
Mike Stump11289f42009-09-09 15:08:12 +00003700 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00003701 HasExplicitTemplateArgs,
3702 ExplicitTemplateArgs,
3703 NumExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003704 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00003705 }
Douglas Gregore254f902009-02-04 00:32:51 +00003706}
3707
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003708/// isBetterOverloadCandidate - Determines whether the first overload
3709/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00003710bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003711Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00003712 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003713 // Define viable functions to be better candidates than non-viable
3714 // functions.
3715 if (!Cand2.Viable)
3716 return Cand1.Viable;
3717 else if (!Cand1.Viable)
3718 return false;
3719
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003720 // C++ [over.match.best]p1:
3721 //
3722 // -- if F is a static member function, ICS1(F) is defined such
3723 // that ICS1(F) is neither better nor worse than ICS1(G) for
3724 // any function G, and, symmetrically, ICS1(G) is neither
3725 // better nor worse than ICS1(F).
3726 unsigned StartArg = 0;
3727 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3728 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003729
Douglas Gregord3cb3562009-07-07 23:38:56 +00003730 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00003731 // A viable function F1 is defined to be a better function than another
3732 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00003733 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003734 unsigned NumArgs = Cand1.Conversions.size();
3735 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3736 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003737 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003738 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3739 Cand2.Conversions[ArgIdx])) {
3740 case ImplicitConversionSequence::Better:
3741 // Cand1 has a better conversion sequence.
3742 HasBetterConversion = true;
3743 break;
3744
3745 case ImplicitConversionSequence::Worse:
3746 // Cand1 can't be better than Cand2.
3747 return false;
3748
3749 case ImplicitConversionSequence::Indistinguishable:
3750 // Do nothing.
3751 break;
3752 }
3753 }
3754
Mike Stump11289f42009-09-09 15:08:12 +00003755 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00003756 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003757 if (HasBetterConversion)
3758 return true;
3759
Mike Stump11289f42009-09-09 15:08:12 +00003760 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00003761 // specialization, or, if not that,
3762 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3763 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3764 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003765
3766 // -- F1 and F2 are function template specializations, and the function
3767 // template for F1 is more specialized than the template for F2
3768 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00003769 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00003770 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3771 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00003772 if (FunctionTemplateDecl *BetterTemplate
3773 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3774 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00003775 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
3776 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00003777 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003778
Douglas Gregora1f013e2008-11-07 22:36:19 +00003779 // -- the context is an initialization by user-defined conversion
3780 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3781 // from the return type of F1 to the destination type (i.e.,
3782 // the type of the entity being initialized) is a better
3783 // conversion sequence than the standard conversion sequence
3784 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00003785 if (Cand1.Function && Cand2.Function &&
3786 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003787 isa<CXXConversionDecl>(Cand2.Function)) {
3788 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3789 Cand2.FinalConversion)) {
3790 case ImplicitConversionSequence::Better:
3791 // Cand1 has a better conversion sequence.
3792 return true;
3793
3794 case ImplicitConversionSequence::Worse:
3795 // Cand1 can't be better than Cand2.
3796 return false;
3797
3798 case ImplicitConversionSequence::Indistinguishable:
3799 // Do nothing
3800 break;
3801 }
3802 }
3803
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003804 return false;
3805}
3806
Mike Stump11289f42009-09-09 15:08:12 +00003807/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003808/// within an overload candidate set.
3809///
3810/// \param CandidateSet the set of candidate functions.
3811///
3812/// \param Loc the location of the function name (or operator symbol) for
3813/// which overload resolution occurs.
3814///
Mike Stump11289f42009-09-09 15:08:12 +00003815/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003816/// function, Best points to the candidate function found.
3817///
3818/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00003819Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003820Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003821 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003822 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003823 // Find the best viable function.
3824 Best = CandidateSet.end();
3825 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3826 Cand != CandidateSet.end(); ++Cand) {
3827 if (Cand->Viable) {
3828 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3829 Best = Cand;
3830 }
3831 }
3832
3833 // If we didn't find any viable functions, abort.
3834 if (Best == CandidateSet.end())
3835 return OR_No_Viable_Function;
3836
3837 // Make sure that this function is better than every other viable
3838 // function. If not, we have an ambiguity.
3839 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3840 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00003841 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003842 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00003843 !isBetterOverloadCandidate(*Best, *Cand)) {
3844 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003845 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003846 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003847 }
Mike Stump11289f42009-09-09 15:08:12 +00003848
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003849 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003850 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00003851 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003852 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003853 return OR_Deleted;
3854
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003855 // C++ [basic.def.odr]p2:
3856 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00003857 // when referred to from a potentially-evaluated expression. [Note: this
3858 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003859 // (clause 13), user-defined conversions (12.3.2), allocation function for
3860 // placement new (5.3.4), as well as non-default initialization (8.5).
3861 if (Best->Function)
3862 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003863 return OR_Success;
3864}
3865
3866/// PrintOverloadCandidates - When overload resolution fails, prints
3867/// diagnostic messages containing the candidates in the candidate
3868/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00003869void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003870Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003871 bool OnlyViable) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003872 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3873 LastCand = CandidateSet.end();
3874 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003875 if (Cand->Viable || !OnlyViable) {
3876 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003877 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003878 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003879 // Deleted or "unavailable" function.
3880 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3881 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00003882 } else if (FunctionTemplateDecl *FunTmpl
3883 = Cand->Function->getPrimaryTemplate()) {
3884 // Function template specialization
3885 // FIXME: Give a better reason!
3886 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
3887 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
3888 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00003889 } else {
3890 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00003891 bool errReported = false;
3892 if (!Cand->Viable && Cand->Conversions.size() > 0) {
3893 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
3894 const ImplicitConversionSequence &Conversion =
3895 Cand->Conversions[i];
3896 if ((Conversion.ConversionKind !=
3897 ImplicitConversionSequence::BadConversion) ||
3898 Conversion.ConversionFunctionSet.size() == 0)
3899 continue;
3900 Diag(Cand->Function->getLocation(),
3901 diag::err_ovl_candidate_not_viable) << (i+1);
3902 errReported = true;
3903 for (int j = Conversion.ConversionFunctionSet.size()-1;
3904 j >= 0; j--) {
3905 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
3906 Diag(Func->getLocation(), diag::err_ovl_candidate);
3907 }
3908 }
3909 }
3910 if (!errReported)
3911 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00003912 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00003913 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003914 // Desugar the type of the surrogate down to a function type,
3915 // retaining as many typedefs as possible while still showing
3916 // the function type (and, therefore, its parameter types).
3917 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003918 bool isLValueReference = false;
3919 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003920 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003921 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003922 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003923 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003924 isLValueReference = true;
3925 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003926 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003927 FnType = FnTypeRef->getPointeeType();
3928 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003929 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003930 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003931 FnType = FnTypePtr->getPointeeType();
3932 isPointer = true;
3933 }
3934 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00003935 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003936 // Reconstruct the pointer/reference as appropriate.
3937 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003938 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3939 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003940
Douglas Gregorab7897a2008-11-19 22:57:39 +00003941 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003942 << FnType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003943 } else {
3944 // FIXME: We need to get the identifier in here
Mike Stump87c57ac2009-05-16 07:39:55 +00003945 // FIXME: Do we want the error message to point at the operator?
3946 // (built-ins won't have a location)
Mike Stump11289f42009-09-09 15:08:12 +00003947 QualType FnType
Douglas Gregora11693b2008-11-12 17:17:38 +00003948 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3949 Cand->BuiltinTypes.ParamTypes,
3950 Cand->Conversions.size(),
3951 false, 0);
3952
Chris Lattner1e5665e2008-11-24 06:25:27 +00003953 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003954 }
3955 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003956 }
3957}
3958
Douglas Gregorcd695e52008-11-10 20:40:00 +00003959/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3960/// an overloaded function (C++ [over.over]), where @p From is an
3961/// expression with overloaded function type and @p ToType is the type
3962/// we're trying to resolve to. For example:
3963///
3964/// @code
3965/// int f(double);
3966/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00003967///
Douglas Gregorcd695e52008-11-10 20:40:00 +00003968/// int (*pfd)(double) = f; // selects f(double)
3969/// @endcode
3970///
3971/// This routine returns the resulting FunctionDecl if it could be
3972/// resolved, and NULL otherwise. When @p Complain is true, this
3973/// routine will emit diagnostics if there is an error.
3974FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003975Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003976 bool Complain) {
3977 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003978 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003979 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00003980 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003981 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00003982 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003983 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003984 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003985 FunctionType = MemTypePtr->getPointeeType();
3986 IsMember = true;
3987 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003988
3989 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00003990 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00003991 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00003992 return 0;
3993
3994 // Find the actual overloaded function declaration.
3995 OverloadedFunctionDecl *Ovl = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003996
Douglas Gregorcd695e52008-11-10 20:40:00 +00003997 // C++ [over.over]p1:
3998 // [...] [Note: any redundant set of parentheses surrounding the
3999 // overloaded function name is ignored (5.1). ]
4000 Expr *OvlExpr = From->IgnoreParens();
4001
4002 // C++ [over.over]p1:
4003 // [...] The overloaded function name can be preceded by the &
4004 // operator.
4005 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4006 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4007 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4008 }
4009
4010 // Try to dig out the overloaded function.
Douglas Gregor9b146582009-07-08 20:55:45 +00004011 FunctionTemplateDecl *FunctionTemplate = 0;
4012 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004013 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor9b146582009-07-08 20:55:45 +00004014 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
4015 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004016
Mike Stump11289f42009-09-09 15:08:12 +00004017 // If there's no overloaded function declaration or function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00004018 // we're done.
4019 if (!Ovl && !FunctionTemplate)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004020 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004021
Douglas Gregor9b146582009-07-08 20:55:45 +00004022 OverloadIterator Fun;
4023 if (Ovl)
4024 Fun = Ovl;
4025 else
4026 Fun = FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00004027
Douglas Gregorcd695e52008-11-10 20:40:00 +00004028 // Look through all of the overloaded functions, searching for one
4029 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004030 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Mike Stump11289f42009-09-09 15:08:12 +00004031
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004032 bool FoundNonTemplateFunction = false;
Douglas Gregor9b146582009-07-08 20:55:45 +00004033 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004034 // C++ [over.over]p3:
4035 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004036 // targets of type "pointer-to-function" or "reference-to-function."
4037 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004038 // type "pointer-to-member-function."
4039 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004040
Mike Stump11289f42009-09-09 15:08:12 +00004041 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor9b146582009-07-08 20:55:45 +00004042 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump11289f42009-09-09 15:08:12 +00004043 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004044 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004045 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004046 // static when converting to member pointer.
4047 if (Method->isStatic() == IsMember)
4048 continue;
4049 } else if (IsMember)
4050 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004051
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004052 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004053 // If the name is a function template, template argument deduction is
4054 // done (14.8.2.2), and if the argument deduction succeeds, the
4055 // resulting template argument list is used to generate a single
4056 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004057 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004058 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004059 FunctionDecl *Specialization = 0;
4060 TemplateDeductionInfo Info(Context);
4061 if (TemplateDeductionResult Result
4062 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
4063 /*FIXME:*/0, /*FIXME:*/0,
4064 FunctionType, Specialization, Info)) {
4065 // FIXME: make a note of the failed deduction for diagnostics.
4066 (void)Result;
4067 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004068 // FIXME: If the match isn't exact, shouldn't we just drop this as
4069 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004070 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004071 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004072 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004073 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004074 }
4075 }
Mike Stump11289f42009-09-09 15:08:12 +00004076
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004077 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4078 // Skip non-static functions when converting to pointer, and static
4079 // when converting to member pointer.
4080 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004081 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004082 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004083 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004084
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004085 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004086 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004087 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004088 FoundNonTemplateFunction = true;
4089 }
Mike Stump11289f42009-09-09 15:08:12 +00004090 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004091 }
4092
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004093 // If there were 0 or 1 matches, we're done.
4094 if (Matches.empty())
4095 return 0;
4096 else if (Matches.size() == 1)
4097 return *Matches.begin();
4098
4099 // C++ [over.over]p4:
4100 // If more than one function is selected, [...]
4101 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor05155d82009-08-21 23:19:43 +00004102 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004103 if (FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004104 // [...] any function template specializations in the set are
4105 // eliminated if the set also contains a non-template function, [...]
4106 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004107 if ((*M)->getPrimaryTemplate() == 0)
4108 RemainingMatches.push_back(*M);
4109 } else {
Douglas Gregor05155d82009-08-21 23:19:43 +00004110 // [...] and any given function template specialization F1 is
4111 // eliminated if the set contains a second function template
4112 // specialization whose function template is more specialized
4113 // than the function template of F1 according to the partial
4114 // ordering rules of 14.5.5.2.
4115
4116 // The algorithm specified above is quadratic. We instead use a
4117 // two-pass algorithm (similar to the one used to identify the
4118 // best viable function in an overload set) that identifies the
4119 // best function template (if it exists).
4120 MatchIter Best = Matches.begin();
4121 MatchIter M = Best, MEnd = Matches.end();
4122 // Find the most specialized function.
4123 for (++M; M != MEnd; ++M)
4124 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4125 (*Best)->getPrimaryTemplate(),
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004126 TPOC_Other)
Douglas Gregor05155d82009-08-21 23:19:43 +00004127 == (*M)->getPrimaryTemplate())
4128 Best = M;
4129
4130 // Determine whether this function template is more specialized
4131 // that all of the others.
4132 bool Ambiguous = false;
4133 for (M = Matches.begin(); M != MEnd; ++M) {
4134 if (M != Best &&
4135 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4136 (*Best)->getPrimaryTemplate(),
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004137 TPOC_Other)
Douglas Gregor05155d82009-08-21 23:19:43 +00004138 != (*Best)->getPrimaryTemplate()) {
4139 Ambiguous = true;
4140 break;
4141 }
4142 }
4143
4144 // If one function template was more specialized than all of the
4145 // others, return it.
4146 if (!Ambiguous)
4147 return *Best;
4148
4149 // We could not find a most-specialized function template, which
4150 // is equivalent to having a set of function templates with more
4151 // than one such template. So, we place all of the function
4152 // templates into the set of remaining matches and produce a
4153 // diagnostic below. FIXME: we could perform the quadratic
4154 // algorithm here, pruning the result set to limit the number of
4155 // candidates output later.
Douglas Gregor48bc3742009-09-14 22:02:01 +00004156 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004157 }
Mike Stump11289f42009-09-09 15:08:12 +00004158
4159 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004160 // selected function.
4161 if (RemainingMatches.size() == 1)
4162 return RemainingMatches.front();
Mike Stump11289f42009-09-09 15:08:12 +00004163
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004164 // FIXME: We should probably return the same thing that BestViableFunction
4165 // returns (even if we issue the diagnostics here).
4166 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4167 << RemainingMatches[0]->getDeclName();
4168 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4169 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004170 return 0;
4171}
4172
Douglas Gregorcabea402009-09-22 15:41:20 +00004173/// \brief Add a single candidate to the overload set.
4174static void AddOverloadedCallCandidate(Sema &S,
4175 AnyFunctionDecl Callee,
4176 bool &ArgumentDependentLookup,
4177 bool HasExplicitTemplateArgs,
4178 const TemplateArgument *ExplicitTemplateArgs,
4179 unsigned NumExplicitTemplateArgs,
4180 Expr **Args, unsigned NumArgs,
4181 OverloadCandidateSet &CandidateSet,
4182 bool PartialOverloading) {
4183 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4184 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4185 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4186 PartialOverloading);
4187
4188 if (Func->getDeclContext()->isRecord() ||
4189 Func->getDeclContext()->isFunctionOrMethod())
4190 ArgumentDependentLookup = false;
4191 return;
4192 }
4193
4194 FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4195 S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4196 ExplicitTemplateArgs,
4197 NumExplicitTemplateArgs,
4198 Args, NumArgs, CandidateSet);
4199
4200 if (FuncTemplate->getDeclContext()->isRecord())
4201 ArgumentDependentLookup = false;
4202}
4203
4204/// \brief Add the overload candidates named by callee and/or found by argument
4205/// dependent lookup to the given overload set.
4206void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4207 DeclarationName &UnqualifiedName,
4208 bool &ArgumentDependentLookup,
4209 bool HasExplicitTemplateArgs,
4210 const TemplateArgument *ExplicitTemplateArgs,
4211 unsigned NumExplicitTemplateArgs,
4212 Expr **Args, unsigned NumArgs,
4213 OverloadCandidateSet &CandidateSet,
4214 bool PartialOverloading) {
4215 // Add the functions denoted by Callee to the set of candidate
4216 // functions. While we're doing so, track whether argument-dependent
4217 // lookup still applies, per:
4218 //
4219 // C++0x [basic.lookup.argdep]p3:
4220 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4221 // and let Y be the lookup set produced by argument dependent
4222 // lookup (defined as follows). If X contains
4223 //
4224 // -- a declaration of a class member, or
4225 //
4226 // -- a block-scope function declaration that is not a
4227 // using-declaration (FIXME: check for using declaration), or
4228 //
4229 // -- a declaration that is neither a function or a function
4230 // template
4231 //
4232 // then Y is empty.
4233 if (!Callee) {
4234 // Nothing to do.
4235 } else if (OverloadedFunctionDecl *Ovl
4236 = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4237 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4238 FuncEnd = Ovl->function_end();
4239 Func != FuncEnd; ++Func)
4240 AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4241 HasExplicitTemplateArgs,
4242 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4243 Args, NumArgs, CandidateSet,
4244 PartialOverloading);
4245 } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4246 AddOverloadedCallCandidate(*this,
4247 AnyFunctionDecl::getFromNamedDecl(Callee),
4248 ArgumentDependentLookup,
4249 HasExplicitTemplateArgs,
4250 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4251 Args, NumArgs, CandidateSet,
4252 PartialOverloading);
4253 // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4254 // checking dynamically.
4255
4256 if (Callee)
4257 UnqualifiedName = Callee->getDeclName();
4258
4259 if (ArgumentDependentLookup)
4260 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4261 HasExplicitTemplateArgs,
4262 ExplicitTemplateArgs,
4263 NumExplicitTemplateArgs,
4264 CandidateSet,
4265 PartialOverloading);
4266}
4267
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004268/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004269/// (which eventually refers to the declaration Func) and the call
4270/// arguments Args/NumArgs, attempt to resolve the function call down
4271/// to a specific function. If overload resolution succeeds, returns
4272/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004273/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004274/// arguments and Fn, and returns NULL.
Douglas Gregore254f902009-02-04 00:32:51 +00004275FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004276 DeclarationName UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00004277 bool HasExplicitTemplateArgs,
4278 const TemplateArgument *ExplicitTemplateArgs,
4279 unsigned NumExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004280 SourceLocation LParenLoc,
4281 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004282 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004283 SourceLocation RParenLoc,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004284 bool &ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004285 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004286
4287 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004288 // functions.
4289 AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4290 HasExplicitTemplateArgs, ExplicitTemplateArgs,
4291 NumExplicitTemplateArgs, Args, NumArgs,
4292 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004293 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004294 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004295 case OR_Success:
4296 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004297
4298 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004299 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004300 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004301 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004302 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4303 break;
4304
4305 case OR_Ambiguous:
4306 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004307 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004308 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4309 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004310
4311 case OR_Deleted:
4312 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4313 << Best->Function->isDeleted()
4314 << UnqualifiedName
4315 << Fn->getSourceRange();
4316 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4317 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004318 }
4319
4320 // Overload resolution failed. Destroy all of the subexpressions and
4321 // return NULL.
4322 Fn->Destroy(Context);
4323 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4324 Args[Arg]->Destroy(Context);
4325 return 0;
4326}
4327
Douglas Gregor084d8552009-03-13 23:49:33 +00004328/// \brief Create a unary operation that may resolve to an overloaded
4329/// operator.
4330///
4331/// \param OpLoc The location of the operator itself (e.g., '*').
4332///
4333/// \param OpcIn The UnaryOperator::Opcode that describes this
4334/// operator.
4335///
4336/// \param Functions The set of non-member functions that will be
4337/// considered by overload resolution. The caller needs to build this
4338/// set based on the context using, e.g.,
4339/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4340/// set should not contain any member functions; those will be added
4341/// by CreateOverloadedUnaryOp().
4342///
4343/// \param input The input argument.
4344Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4345 unsigned OpcIn,
4346 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004347 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004348 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4349 Expr *Input = (Expr *)input.get();
4350
4351 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4352 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4353 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4354
4355 Expr *Args[2] = { Input, 0 };
4356 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004357
Douglas Gregor084d8552009-03-13 23:49:33 +00004358 // For post-increment and post-decrement, add the implicit '0' as
4359 // the second argument, so that we know this is a post-increment or
4360 // post-decrement.
4361 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4362 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004363 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004364 SourceLocation());
4365 NumArgs = 2;
4366 }
4367
4368 if (Input->isTypeDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00004369 OverloadedFunctionDecl *Overloads
Douglas Gregor084d8552009-03-13 23:49:33 +00004370 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004371 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004372 FuncEnd = Functions.end();
4373 Func != FuncEnd; ++Func)
4374 Overloads->addOverload(*Func);
4375
4376 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4377 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004378
Douglas Gregor084d8552009-03-13 23:49:33 +00004379 input.release();
4380 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4381 &Args[0], NumArgs,
4382 Context.DependentTy,
4383 OpLoc));
4384 }
4385
4386 // Build an empty overload set.
4387 OverloadCandidateSet CandidateSet;
4388
4389 // Add the candidates from the given function set.
4390 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4391
4392 // Add operator candidates that are member functions.
4393 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4394
4395 // Add builtin operator candidates.
4396 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4397
4398 // Perform overload resolution.
4399 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004400 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004401 case OR_Success: {
4402 // We found a built-in operator or an overloaded operator.
4403 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004404
Douglas Gregor084d8552009-03-13 23:49:33 +00004405 if (FnDecl) {
4406 // We matched an overloaded operator. Build a call to that
4407 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004408
Douglas Gregor084d8552009-03-13 23:49:33 +00004409 // Convert the arguments.
4410 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4411 if (PerformObjectArgumentInitialization(Input, Method))
4412 return ExprError();
4413 } else {
4414 // Convert the arguments.
4415 if (PerformCopyInitialization(Input,
4416 FnDecl->getParamDecl(0)->getType(),
4417 "passing"))
4418 return ExprError();
4419 }
4420
4421 // Determine the result type
4422 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004423 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor084d8552009-03-13 23:49:33 +00004424 ResultTy = ResultTy.getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004425
Douglas Gregor084d8552009-03-13 23:49:33 +00004426 // Build the actual expression node.
4427 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4428 SourceLocation());
4429 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004430
Douglas Gregor084d8552009-03-13 23:49:33 +00004431 input.release();
Mike Stump11289f42009-09-09 15:08:12 +00004432
4433 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004434 &Input, 1, ResultTy, OpLoc);
4435 return MaybeBindToTemporary(CE);
Douglas Gregor084d8552009-03-13 23:49:33 +00004436 } else {
4437 // We matched a built-in operator. Convert the arguments, then
4438 // break out so that we will build the appropriate built-in
4439 // operator node.
4440 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4441 Best->Conversions[0], "passing"))
4442 return ExprError();
4443
4444 break;
4445 }
4446 }
4447
4448 case OR_No_Viable_Function:
4449 // No viable function; fall through to handling this as a
4450 // built-in operator, which will produce an error message for us.
4451 break;
4452
4453 case OR_Ambiguous:
4454 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4455 << UnaryOperator::getOpcodeStr(Opc)
4456 << Input->getSourceRange();
4457 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4458 return ExprError();
4459
4460 case OR_Deleted:
4461 Diag(OpLoc, diag::err_ovl_deleted_oper)
4462 << Best->Function->isDeleted()
4463 << UnaryOperator::getOpcodeStr(Opc)
4464 << Input->getSourceRange();
4465 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4466 return ExprError();
4467 }
4468
4469 // Either we found no viable overloaded operator or we matched a
4470 // built-in operator. In either case, fall through to trying to
4471 // build a built-in operation.
4472 input.release();
4473 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4474}
4475
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004476/// \brief Create a binary operation that may resolve to an overloaded
4477/// operator.
4478///
4479/// \param OpLoc The location of the operator itself (e.g., '+').
4480///
4481/// \param OpcIn The BinaryOperator::Opcode that describes this
4482/// operator.
4483///
4484/// \param Functions The set of non-member functions that will be
4485/// considered by overload resolution. The caller needs to build this
4486/// set based on the context using, e.g.,
4487/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4488/// set should not contain any member functions; those will be added
4489/// by CreateOverloadedBinOp().
4490///
4491/// \param LHS Left-hand argument.
4492/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004493Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004494Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004495 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004496 FunctionSet &Functions,
4497 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004498 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004499 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004500
4501 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4502 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4503 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4504
4505 // If either side is type-dependent, create an appropriate dependent
4506 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004507 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004508 // .* cannot be overloaded.
4509 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004510 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004511 Context.DependentTy, OpLoc));
4512
Mike Stump11289f42009-09-09 15:08:12 +00004513 OverloadedFunctionDecl *Overloads
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004514 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004515 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004516 FuncEnd = Functions.end();
4517 Func != FuncEnd; ++Func)
4518 Overloads->addOverload(*Func);
4519
4520 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4521 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004522
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004523 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004524 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004525 Context.DependentTy,
4526 OpLoc));
4527 }
4528
4529 // If this is the .* operator, which is not overloadable, just
4530 // create a built-in binary operator.
4531 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004532 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004533
4534 // If this is one of the assignment operators, we only perform
4535 // overload resolution if the left-hand side is a class or
4536 // enumeration type (C++ [expr.ass]p3).
4537 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregore9899d92009-08-26 17:08:25 +00004538 !Args[0]->getType()->isOverloadableType())
4539 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004540
Douglas Gregor084d8552009-03-13 23:49:33 +00004541 // Build an empty overload set.
4542 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004543
4544 // Add the candidates from the given function set.
4545 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4546
4547 // Add operator candidates that are member functions.
4548 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4549
4550 // Add builtin operator candidates.
4551 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4552
4553 // Perform overload resolution.
4554 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004555 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004556 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004557 // We found a built-in operator or an overloaded operator.
4558 FunctionDecl *FnDecl = Best->Function;
4559
4560 if (FnDecl) {
4561 // We matched an overloaded operator. Build a call to that
4562 // operator.
4563
4564 // Convert the arguments.
4565 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004566 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4567 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004568 "passing"))
4569 return ExprError();
4570 } else {
4571 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004572 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004573 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004574 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004575 "passing"))
4576 return ExprError();
4577 }
4578
4579 // Determine the result type
4580 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004581 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004582 ResultTy = ResultTy.getNonReferenceType();
4583
4584 // Build the actual expression node.
4585 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004586 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004587 UsualUnaryConversions(FnExpr);
4588
Mike Stump11289f42009-09-09 15:08:12 +00004589 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004590 Args, 2, ResultTy, OpLoc);
4591 return MaybeBindToTemporary(CE);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004592 } else {
4593 // We matched a built-in operator. Convert the arguments, then
4594 // break out so that we will build the appropriate built-in
4595 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004596 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004597 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004598 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004599 Best->Conversions[1], "passing"))
4600 return ExprError();
4601
4602 break;
4603 }
4604 }
4605
4606 case OR_No_Viable_Function:
Sebastian Redl027de2a2009-05-21 11:50:50 +00004607 // For class as left operand for assignment or compound assigment operator
4608 // do not fall through to handling in built-in, but report that no overloaded
4609 // assignment operator found
Douglas Gregore9899d92009-08-26 17:08:25 +00004610 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004611 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4612 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004613 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl027de2a2009-05-21 11:50:50 +00004614 return ExprError();
4615 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004616 // No viable function; fall through to handling this as a
4617 // built-in operator, which will produce an error message for us.
4618 break;
4619
4620 case OR_Ambiguous:
4621 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4622 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004623 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004624 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4625 return ExprError();
4626
4627 case OR_Deleted:
4628 Diag(OpLoc, diag::err_ovl_deleted_oper)
4629 << Best->Function->isDeleted()
4630 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004631 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004632 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4633 return ExprError();
4634 }
4635
4636 // Either we found no viable overloaded operator or we matched a
4637 // built-in operator. In either case, try to build a built-in
4638 // operation.
Douglas Gregore9899d92009-08-26 17:08:25 +00004639 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004640}
4641
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004642/// BuildCallToMemberFunction - Build a call to a member
4643/// function. MemExpr is the expression that refers to the member
4644/// function (and includes the object parameter), Args/NumArgs are the
4645/// arguments to the function call (not including the object
4646/// parameter). The caller needs to validate that the member
4647/// expression refers to a member function or an overloaded member
4648/// function.
4649Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00004650Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4651 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004652 unsigned NumArgs, SourceLocation *CommaLocs,
4653 SourceLocation RParenLoc) {
4654 // Dig out the member expression. This holds both the object
4655 // argument and the member function we're referring to.
4656 MemberExpr *MemExpr = 0;
4657 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4658 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4659 else
4660 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4661 assert(MemExpr && "Building member call without member expression");
4662
4663 // Extract the object argument.
4664 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004665
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004666 CXXMethodDecl *Method = 0;
Douglas Gregor97628d62009-08-21 00:16:32 +00004667 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4668 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004669 // Add overload candidates
4670 OverloadCandidateSet CandidateSet;
Douglas Gregor97628d62009-08-21 00:16:32 +00004671 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004672
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004673 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4674 Func != FuncEnd; ++Func) {
4675 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
Mike Stump11289f42009-09-09 15:08:12 +00004676 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004677 /*SuppressUserConversions=*/false);
4678 else
Douglas Gregor84f14dd2009-09-01 00:37:14 +00004679 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4680 MemExpr->hasExplicitTemplateArgumentList(),
4681 MemExpr->getTemplateArgs(),
4682 MemExpr->getNumTemplateArgs(),
4683 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004684 CandidateSet,
4685 /*SuppressUsedConversions=*/false);
4686 }
Mike Stump11289f42009-09-09 15:08:12 +00004687
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004688 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004689 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004690 case OR_Success:
4691 Method = cast<CXXMethodDecl>(Best->Function);
4692 break;
4693
4694 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004695 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004696 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004697 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004698 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4699 // FIXME: Leaking incoming expressions!
4700 return true;
4701
4702 case OR_Ambiguous:
Mike Stump11289f42009-09-09 15:08:12 +00004703 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004704 diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004705 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004706 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4707 // FIXME: Leaking incoming expressions!
4708 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004709
4710 case OR_Deleted:
Mike Stump11289f42009-09-09 15:08:12 +00004711 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00004712 diag::err_ovl_deleted_member_call)
4713 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00004714 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004715 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4716 // FIXME: Leaking incoming expressions!
4717 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004718 }
4719
4720 FixOverloadedFunctionReference(MemExpr, Method);
4721 } else {
4722 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4723 }
4724
4725 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00004726 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004727 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00004728 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004729 Method->getResultType().getNonReferenceType(),
4730 RParenLoc));
4731
4732 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00004733 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004734 PerformObjectArgumentInitialization(ObjectArg, Method))
4735 return true;
4736 MemExpr->setBase(ObjectArg);
4737
4738 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004739 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004740 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004741 RParenLoc))
4742 return true;
4743
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004744 if (CheckFunctionCall(Method, TheCall.get()))
4745 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00004746
4747 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004748}
4749
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004750/// BuildCallToObjectOfClassType - Build a call to an object of class
4751/// type (C++ [over.call.object]), which can end up invoking an
4752/// overloaded function call operator (@c operator()) or performing a
4753/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00004754Sema::ExprResult
4755Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00004756 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004757 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004758 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004759 SourceLocation RParenLoc) {
4760 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004761 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00004762
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004763 // C++ [over.call.object]p1:
4764 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00004765 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004766 // candidate functions includes at least the function call
4767 // operators of T. The function call operators of T are obtained by
4768 // ordinary lookup of the name operator() in the context of
4769 // (E).operator().
4770 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00004771 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004772 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004773 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004774 Oper != OperEnd; ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00004775 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor55297ac2008-12-23 00:26:44 +00004776 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004777
Douglas Gregorab7897a2008-11-19 22:57:39 +00004778 // C++ [over.call.object]p2:
4779 // In addition, for each conversion function declared in T of the
4780 // form
4781 //
4782 // operator conversion-type-id () cv-qualifier;
4783 //
4784 // where cv-qualifier is the same cv-qualification as, or a
4785 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00004786 // denotes the type "pointer to function of (P1,...,Pn) returning
4787 // R", or the type "reference to pointer to function of
4788 // (P1,...,Pn) returning R", or the type "reference to function
4789 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00004790 // is also considered as a candidate function. Similarly,
4791 // surrogate call functions are added to the set of candidate
4792 // functions for each conversion function declared in an
4793 // accessible base class provided the function is not hidden
4794 // within T by another intervening declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004795
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004796 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4797 // FIXME: Look in base classes for more conversion operators!
Mike Stump11289f42009-09-09 15:08:12 +00004798 OverloadedFunctionDecl *Conversions
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004799 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00004800 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004801 Func = Conversions->function_begin(),
4802 FuncEnd = Conversions->function_end();
4803 Func != FuncEnd; ++Func) {
4804 CXXConversionDecl *Conv;
4805 FunctionTemplateDecl *ConvTemplate;
4806 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00004807
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004808 // Skip over templated conversion functions; they aren't
4809 // surrogates.
4810 if (ConvTemplate)
4811 continue;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004812
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004813 // Strip the reference type (if any) and then the pointer type (if
4814 // any) to get down to what might be a function type.
4815 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4816 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4817 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004818
John McCall9dd450b2009-09-21 23:43:11 +00004819 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004820 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4821 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004822 }
Mike Stump11289f42009-09-09 15:08:12 +00004823
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004824 // Perform overload resolution.
4825 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004826 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004827 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00004828 // Overload resolution succeeded; we'll build the appropriate call
4829 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004830 break;
4831
4832 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004833 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00004834 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004835 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00004836 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004837 break;
4838
4839 case OR_Ambiguous:
4840 Diag(Object->getSourceRange().getBegin(),
4841 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004842 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004843 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4844 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004845
4846 case OR_Deleted:
4847 Diag(Object->getSourceRange().getBegin(),
4848 diag::err_ovl_deleted_object_call)
4849 << Best->Function->isDeleted()
4850 << Object->getType() << Object->getSourceRange();
4851 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4852 break;
Mike Stump11289f42009-09-09 15:08:12 +00004853 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004854
Douglas Gregorab7897a2008-11-19 22:57:39 +00004855 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004856 // We had an error; delete all of the subexpressions and return
4857 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00004858 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004859 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00004860 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004861 return true;
4862 }
4863
Douglas Gregorab7897a2008-11-19 22:57:39 +00004864 if (Best->Function == 0) {
4865 // Since there is no function declaration, this is one of the
4866 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00004867 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00004868 = cast<CXXConversionDecl>(
4869 Best->Conversions[0].UserDefined.ConversionFunction);
4870
4871 // We selected one of the surrogate functions that converts the
4872 // object parameter to a function pointer. Perform the conversion
4873 // on the object argument, then let ActOnCallExpr finish the job.
4874 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004875 ImpCastExprToType(Object,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004876 Conv->getConversionType().getNonReferenceType(),
Anders Carlssona076d142009-07-31 01:23:52 +00004877 CastExpr::CK_Unknown,
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004878 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004879 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4880 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4881 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004882 }
4883
4884 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4885 // that calls this method, using Object for the implicit object
4886 // parameter and passing along the remaining arguments.
4887 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00004888 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004889
4890 unsigned NumArgsInProto = Proto->getNumArgs();
4891 unsigned NumArgsToCheck = NumArgs;
4892
4893 // Build the full argument list for the method call (the
4894 // implicit object parameter is placed at the beginning of the
4895 // list).
4896 Expr **MethodArgs;
4897 if (NumArgs < NumArgsInProto) {
4898 NumArgsToCheck = NumArgsInProto;
4899 MethodArgs = new Expr*[NumArgsInProto + 1];
4900 } else {
4901 MethodArgs = new Expr*[NumArgs + 1];
4902 }
4903 MethodArgs[0] = Object;
4904 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4905 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00004906
4907 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004908 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004909 UsualUnaryConversions(NewFn);
4910
4911 // Once we've built TheCall, all of the expressions are properly
4912 // owned.
4913 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004914 ExprOwningPtr<CXXOperatorCallExpr>
4915 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004916 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00004917 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004918 delete [] MethodArgs;
4919
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004920 // We may have default arguments. If so, we need to allocate more
4921 // slots in the call for them.
4922 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00004923 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004924 else if (NumArgs > NumArgsInProto)
4925 NumArgsToCheck = NumArgsInProto;
4926
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004927 bool IsError = false;
4928
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004929 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004930 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004931 TheCall->setArg(0, Object);
4932
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004933
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004934 // Check the argument types.
4935 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004936 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004937 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004938 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00004939
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004940 // Pass the argument.
4941 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004942 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004943 } else {
Anders Carlssone8271232009-08-14 18:30:22 +00004944 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004945 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004946
4947 TheCall->setArg(i + 1, Arg);
4948 }
4949
4950 // If this is a variadic call, handle args passed through "...".
4951 if (Proto->isVariadic()) {
4952 // Promote the arguments (C99 6.5.2.2p7).
4953 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4954 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004955 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004956 TheCall->setArg(i + 1, Arg);
4957 }
4958 }
4959
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004960 if (IsError) return true;
4961
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004962 if (CheckFunctionCall(Method, TheCall.get()))
4963 return true;
4964
Anders Carlsson1c83deb2009-08-16 03:53:54 +00004965 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004966}
4967
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004968/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00004969/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004970/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00004971Sema::OwningExprResult
4972Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4973 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004974 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00004975
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004976 // C++ [over.ref]p1:
4977 //
4978 // [...] An expression x->m is interpreted as (x.operator->())->m
4979 // for a class object x of type T if T::operator->() exists and if
4980 // the operator is selected as the best match function by the
4981 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004982 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4983 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004984 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00004985
Anders Carlsson78b54932009-09-10 23:18:36 +00004986 LookupResult R = LookupQualifiedName(BaseRecord->getDecl(), OpName,
4987 LookupOrdinaryName);
4988
4989 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
4990 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00004991 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004992 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004993
4994 // Perform overload resolution.
4995 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004996 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004997 case OR_Success:
4998 // Overload resolution succeeded; we'll build the call below.
4999 break;
5000
5001 case OR_No_Viable_Function:
5002 if (CandidateSet.empty())
5003 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00005004 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005005 else
5006 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00005007 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005008 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00005009 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005010
5011 case OR_Ambiguous:
5012 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005013 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005014 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005015 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005016
5017 case OR_Deleted:
5018 Diag(OpLoc, diag::err_ovl_deleted_oper)
5019 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005020 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005021 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005022 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005023 }
5024
5025 // Convert the object parameter.
5026 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005027 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005028 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005029
5030 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005031 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005032
5033 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005034 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5035 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005036 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005037 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005038 Method->getResultType().getNonReferenceType(),
5039 OpLoc);
Douglas Gregord8061562009-08-06 03:17:00 +00005040 return Owned(Base);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005041}
5042
Douglas Gregorcd695e52008-11-10 20:40:00 +00005043/// FixOverloadedFunctionReference - E is an expression that refers to
5044/// a C++ overloaded function (possibly with some parentheses and
5045/// perhaps a '&' around it). We have resolved the overloaded function
5046/// to the function declaration Fn, so patch up the expression E to
5047/// refer (possibly indirectly) to Fn.
5048void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
5049 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5050 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5051 E->setType(PE->getSubExpr()->getType());
5052 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005053 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005054 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005055 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5056 if (Method->isStatic()) {
5057 // Do nothing: static member functions aren't any different
5058 // from non-member functions.
Mike Stump11289f42009-09-09 15:08:12 +00005059 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005060 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
5061 // We have taken the address of a pointer to member
5062 // function. Perform the computation here so that we get the
5063 // appropriate pointer to member type.
5064 DRE->setDecl(Fn);
5065 DRE->setType(Fn->getType());
5066 QualType ClassType
5067 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
Mike Stump11289f42009-09-09 15:08:12 +00005068 E->setType(Context.getMemberPointerType(Fn->getType(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005069 ClassType.getTypePtr()));
5070 return;
5071 }
5072 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005073 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005074 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregorcd695e52008-11-10 20:40:00 +00005075 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor9b146582009-07-08 20:55:45 +00005076 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Mike Stump11289f42009-09-09 15:08:12 +00005077 isa<FunctionTemplateDecl>(DR->getDecl())) &&
Douglas Gregor9b146582009-07-08 20:55:45 +00005078 "Expected overloaded function or function template");
Douglas Gregorcd695e52008-11-10 20:40:00 +00005079 DR->setDecl(Fn);
5080 E->setType(Fn->getType());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005081 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5082 MemExpr->setMemberDecl(Fn);
5083 E->setType(Fn->getType());
Douglas Gregorcd695e52008-11-10 20:40:00 +00005084 } else {
5085 assert(false && "Invalid reference to overloaded function");
5086 }
5087}
5088
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005089} // end namespace clang