blob: 12eb58733b152b358db363fc4deebb89669a894a [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);
859 unsigned Quals = CanonFromPointee.getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000860
861 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor237f96c2008-11-26 23:31:11 +0000862 if (CanonToPointee.getCVRQualifiers() == Quals) {
863 // ToType is exactly what we need. Return it.
864 if (ToType.getTypePtr())
865 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.
873 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
874}
875
Mike Stump11289f42009-09-09 15:08:12 +0000876static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000877 bool InOverloadResolution,
878 ASTContext &Context) {
879 // Handle value-dependent integral null pointer constants correctly.
880 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
881 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
882 Expr->getType()->isIntegralType())
883 return !InOverloadResolution;
884
885 return Expr->isNullPointerConstant(Context);
886}
Mike Stump11289f42009-09-09 15:08:12 +0000887
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000888/// IsPointerConversion - Determines whether the conversion of the
889/// expression From, which has the (possibly adjusted) type FromType,
890/// can be converted to the type ToType via a pointer conversion (C++
891/// 4.10). If so, returns true and places the converted type (that
892/// might differ from ToType in its cv-qualifiers at some level) into
893/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000894///
Douglas Gregora29dc052008-11-27 01:19:21 +0000895/// This routine also supports conversions to and from block pointers
896/// and conversions with Objective-C's 'id', 'id<protocols...>', and
897/// pointers to interfaces. FIXME: Once we've determined the
898/// appropriate overloading rules for Objective-C, we may want to
899/// split the Objective-C checks into a different routine; however,
900/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000901/// conversions, so for now they live here. IncompatibleObjC will be
902/// set if the conversion is an allowed Objective-C conversion that
903/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000904bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000905 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000906 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000907 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000908 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000909 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
910 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000911
Mike Stump11289f42009-09-09 15:08:12 +0000912 // Conversion from a null pointer constant to any Objective-C pointer type.
913 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000914 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000915 ConvertedType = ToType;
916 return true;
917 }
918
Douglas Gregor231d1c62008-11-27 00:15:41 +0000919 // Blocks: Block pointers can be converted to void*.
920 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000921 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000922 ConvertedType = ToType;
923 return true;
924 }
925 // Blocks: A null pointer constant can be converted to a block
926 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000927 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000928 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000929 ConvertedType = ToType;
930 return true;
931 }
932
Sebastian Redl576fd422009-05-10 18:38:11 +0000933 // If the left-hand-side is nullptr_t, the right side can be a null
934 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000935 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000936 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000937 ConvertedType = ToType;
938 return true;
939 }
940
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000941 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000942 if (!ToTypePtr)
943 return false;
944
945 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000946 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000947 ConvertedType = ToType;
948 return true;
949 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000950
Douglas Gregor237f96c2008-11-26 23:31:11 +0000951 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000952 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000953 if (!FromTypePtr)
954 return false;
955
956 QualType FromPointeeType = FromTypePtr->getPointeeType();
957 QualType ToPointeeType = ToTypePtr->getPointeeType();
958
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000959 // An rvalue of type "pointer to cv T," where T is an object type,
960 // can be converted to an rvalue of type "pointer to cv void" (C++
961 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000962 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000963 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000964 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000965 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000966 return true;
967 }
968
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000969 // When we're overloading in C, we allow a special kind of pointer
970 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +0000971 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000972 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000973 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000974 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +0000975 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000976 return true;
977 }
978
Douglas Gregor5c407d92008-10-23 00:40:37 +0000979 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +0000980 //
Douglas Gregor5c407d92008-10-23 00:40:37 +0000981 // An rvalue of type "pointer to cv D," where D is a class type,
982 // can be converted to an rvalue of type "pointer to cv B," where
983 // B is a base class (clause 10) of D. If B is an inaccessible
984 // (clause 11) or ambiguous (10.2) base class of D, a program that
985 // necessitates this conversion is ill-formed. The result of the
986 // conversion is a pointer to the base class sub-object of the
987 // derived class object. The null pointer value is converted to
988 // the null pointer value of the destination type.
989 //
Douglas Gregor39c16d42008-10-24 04:54:22 +0000990 // Note that we do not check for ambiguity or inaccessibility
991 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000992 if (getLangOptions().CPlusPlus &&
993 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor237f96c2008-11-26 23:31:11 +0000994 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000995 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000996 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000997 ToType, Context);
998 return true;
999 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001000
Douglas Gregora119f102008-12-19 19:13:09 +00001001 return false;
1002}
1003
1004/// isObjCPointerConversion - Determines whether this is an
1005/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1006/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001007bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001008 QualType& ConvertedType,
1009 bool &IncompatibleObjC) {
1010 if (!getLangOptions().ObjC1)
1011 return false;
1012
Steve Naroff7cae42b2009-07-10 23:34:53 +00001013 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001014 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001015 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001016 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001017
Steve Naroff7cae42b2009-07-10 23:34:53 +00001018 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001019 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001020 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001021 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001022 ConvertedType = ToType;
1023 return true;
1024 }
1025 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001026 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001027 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001028 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001029 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001030 ConvertedType = ToType;
1031 return true;
1032 }
1033 // Objective C++: We're able to convert from a pointer to an
1034 // interface to a pointer to a different interface.
1035 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1036 ConvertedType = ToType;
1037 return true;
1038 }
1039
1040 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1041 // Okay: this is some kind of implicit downcast of Objective-C
1042 // interfaces, which is permitted. However, we're going to
1043 // complain about it.
1044 IncompatibleObjC = true;
1045 ConvertedType = FromType;
1046 return true;
1047 }
Mike Stump11289f42009-09-09 15:08:12 +00001048 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001049 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001050 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001051 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001052 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001053 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001054 ToPointeeType = ToBlockPtr->getPointeeType();
1055 else
Douglas Gregora119f102008-12-19 19:13:09 +00001056 return false;
1057
Douglas Gregor033f56d2008-12-23 00:53:59 +00001058 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001059 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001060 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001061 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001062 FromPointeeType = FromBlockPtr->getPointeeType();
1063 else
Douglas Gregora119f102008-12-19 19:13:09 +00001064 return false;
1065
Douglas Gregora119f102008-12-19 19:13:09 +00001066 // If we have pointers to pointers, recursively check whether this
1067 // is an Objective-C conversion.
1068 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1069 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1070 IncompatibleObjC)) {
1071 // We always complain about this conversion.
1072 IncompatibleObjC = true;
1073 ConvertedType = ToType;
1074 return true;
1075 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001076 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001077 // differences in the argument and result types are in Objective-C
1078 // pointer conversions. If so, we permit the conversion (but
1079 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001080 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001081 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001082 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001083 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001084 if (FromFunctionType && ToFunctionType) {
1085 // If the function types are exactly the same, this isn't an
1086 // Objective-C pointer conversion.
1087 if (Context.getCanonicalType(FromPointeeType)
1088 == Context.getCanonicalType(ToPointeeType))
1089 return false;
1090
1091 // Perform the quick checks that will tell us whether these
1092 // function types are obviously different.
1093 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1094 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1095 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1096 return false;
1097
1098 bool HasObjCConversion = false;
1099 if (Context.getCanonicalType(FromFunctionType->getResultType())
1100 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1101 // Okay, the types match exactly. Nothing to do.
1102 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1103 ToFunctionType->getResultType(),
1104 ConvertedType, IncompatibleObjC)) {
1105 // Okay, we have an Objective-C pointer conversion.
1106 HasObjCConversion = true;
1107 } else {
1108 // Function types are too different. Abort.
1109 return false;
1110 }
Mike Stump11289f42009-09-09 15:08:12 +00001111
Douglas Gregora119f102008-12-19 19:13:09 +00001112 // Check argument types.
1113 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1114 ArgIdx != NumArgs; ++ArgIdx) {
1115 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1116 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1117 if (Context.getCanonicalType(FromArgType)
1118 == Context.getCanonicalType(ToArgType)) {
1119 // Okay, the types match exactly. Nothing to do.
1120 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1121 ConvertedType, IncompatibleObjC)) {
1122 // Okay, we have an Objective-C pointer conversion.
1123 HasObjCConversion = true;
1124 } else {
1125 // Argument types are too different. Abort.
1126 return false;
1127 }
1128 }
1129
1130 if (HasObjCConversion) {
1131 // We had an Objective-C conversion. Allow this pointer
1132 // conversion, but complain about it.
1133 ConvertedType = ToType;
1134 IncompatibleObjC = true;
1135 return true;
1136 }
1137 }
1138
Sebastian Redl72b597d2009-01-25 19:43:20 +00001139 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001140}
1141
Douglas Gregor39c16d42008-10-24 04:54:22 +00001142/// CheckPointerConversion - Check the pointer conversion from the
1143/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001144/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001145/// conversions for which IsPointerConversion has already returned
1146/// true. It returns true and produces a diagnostic if there was an
1147/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001148bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1149 CastExpr::CastKind &Kind) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001150 QualType FromType = From->getType();
1151
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001152 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1153 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001154 QualType FromPointeeType = FromPtrType->getPointeeType(),
1155 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001156
Douglas Gregor39c16d42008-10-24 04:54:22 +00001157 if (FromPointeeType->isRecordType() &&
1158 ToPointeeType->isRecordType()) {
1159 // We must have a derived-to-base conversion. Check an
1160 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001161 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1162 From->getExprLoc(),
1163 From->getSourceRange()))
1164 return true;
1165
1166 // The conversion was successful.
1167 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001168 }
1169 }
Mike Stump11289f42009-09-09 15:08:12 +00001170 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001171 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001172 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001173 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001174 // Objective-C++ conversions are always okay.
1175 // FIXME: We should have a different class of conversions for the
1176 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001177 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001178 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001179
Steve Naroff7cae42b2009-07-10 23:34:53 +00001180 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001181 return false;
1182}
1183
Sebastian Redl72b597d2009-01-25 19:43:20 +00001184/// IsMemberPointerConversion - Determines whether the conversion of the
1185/// expression From, which has the (possibly adjusted) type FromType, can be
1186/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1187/// If so, returns true and places the converted type (that might differ from
1188/// ToType in its cv-qualifiers at some level) into ConvertedType.
1189bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Mike Stump11289f42009-09-09 15:08:12 +00001190 QualType ToType, QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001191 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001192 if (!ToTypePtr)
1193 return false;
1194
1195 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1196 if (From->isNullPointerConstant(Context)) {
1197 ConvertedType = ToType;
1198 return true;
1199 }
1200
1201 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001202 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001203 if (!FromTypePtr)
1204 return false;
1205
1206 // A pointer to member of B can be converted to a pointer to member of D,
1207 // where D is derived from B (C++ 4.11p2).
1208 QualType FromClass(FromTypePtr->getClass(), 0);
1209 QualType ToClass(ToTypePtr->getClass(), 0);
1210 // FIXME: What happens when these are dependent? Is this function even called?
1211
1212 if (IsDerivedFrom(ToClass, FromClass)) {
1213 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1214 ToClass.getTypePtr());
1215 return true;
1216 }
1217
1218 return false;
1219}
1220
1221/// CheckMemberPointerConversion - Check the member pointer conversion from the
1222/// expression From to the type ToType. This routine checks for ambiguous or
1223/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1224/// for which IsMemberPointerConversion has already returned true. It returns
1225/// true and produces a diagnostic if there was an error, or returns false
1226/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001227bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Anders Carlssond7923c62009-08-22 23:33:40 +00001228 CastExpr::CastKind &Kind) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001229 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001230 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001231 if (!FromPtrType) {
1232 // This must be a null pointer to member pointer conversion
Mike Stump11289f42009-09-09 15:08:12 +00001233 assert(From->isNullPointerConstant(Context) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001234 "Expr must be null pointer constant!");
1235 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001236 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001237 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001238
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001239 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001240 assert(ToPtrType && "No member pointer cast has a target type "
1241 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001242
Sebastian Redled8f2002009-01-28 18:33:18 +00001243 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1244 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001245
Sebastian Redled8f2002009-01-28 18:33:18 +00001246 // FIXME: What about dependent types?
1247 assert(FromClass->isRecordType() && "Pointer into non-class.");
1248 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001249
Sebastian Redled8f2002009-01-28 18:33:18 +00001250 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1251 /*DetectVirtual=*/true);
1252 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1253 assert(DerivationOkay &&
1254 "Should not have been called if derivation isn't OK.");
1255 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001256
Sebastian Redled8f2002009-01-28 18:33:18 +00001257 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1258 getUnqualifiedType())) {
1259 // Derivation is ambiguous. Redo the check to find the exact paths.
1260 Paths.clear();
1261 Paths.setRecordingPaths(true);
1262 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1263 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1264 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001265
Sebastian Redled8f2002009-01-28 18:33:18 +00001266 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1267 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1268 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1269 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001270 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001271
Douglas Gregor89ee6822009-02-28 01:32:25 +00001272 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001273 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1274 << FromClass << ToClass << QualType(VBase, 0)
1275 << From->getSourceRange();
1276 return true;
1277 }
1278
Anders Carlssond7923c62009-08-22 23:33:40 +00001279 // Must be a base to derived member conversion.
1280 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001281 return false;
1282}
1283
Douglas Gregor9a657932008-10-21 23:43:52 +00001284/// IsQualificationConversion - Determines whether the conversion from
1285/// an rvalue of type FromType to ToType is a qualification conversion
1286/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001287bool
1288Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001289 FromType = Context.getCanonicalType(FromType);
1290 ToType = Context.getCanonicalType(ToType);
1291
1292 // If FromType and ToType are the same type, this is not a
1293 // qualification conversion.
1294 if (FromType == ToType)
1295 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001296
Douglas Gregor9a657932008-10-21 23:43:52 +00001297 // (C++ 4.4p4):
1298 // A conversion can add cv-qualifiers at levels other than the first
1299 // in multi-level pointers, subject to the following rules: [...]
1300 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001301 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001302 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001303 // Within each iteration of the loop, we check the qualifiers to
1304 // determine if this still looks like a qualification
1305 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001306 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001307 // until there are no more pointers or pointers-to-members left to
1308 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001309 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001310
1311 // -- for every j > 0, if const is in cv 1,j then const is in cv
1312 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001313 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001314 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001315
Douglas Gregor9a657932008-10-21 23:43:52 +00001316 // -- if the cv 1,j and cv 2,j are different, then const is in
1317 // every cv for 0 < k < j.
1318 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001319 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001320 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001321
Douglas Gregor9a657932008-10-21 23:43:52 +00001322 // Keep track of whether all prior cv-qualifiers in the "to" type
1323 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001324 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001325 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001326 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001327
1328 // We are left with FromType and ToType being the pointee types
1329 // after unwrapping the original FromType and ToType the same number
1330 // of types. If we unwrapped any pointers, and if FromType and
1331 // ToType have the same unqualified type (since we checked
1332 // qualifiers above), then this is a qualification conversion.
1333 return UnwrappedAnyPointer &&
1334 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1335}
1336
Douglas Gregor05155d82009-08-21 23:19:43 +00001337/// \brief Given a function template or function, extract the function template
1338/// declaration (if any) and the underlying function declaration.
1339template<typename T>
1340static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1341 FunctionTemplateDecl *&FunctionTemplate) {
1342 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1343 if (FunctionTemplate)
1344 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1345 else
1346 Function = cast<T>(Orig);
1347}
1348
Douglas Gregor576e98c2009-01-30 23:27:23 +00001349/// Determines whether there is a user-defined conversion sequence
1350/// (C++ [over.ics.user]) that converts expression From to the type
1351/// ToType. If such a conversion exists, User will contain the
1352/// user-defined conversion sequence that performs such a conversion
1353/// and this routine will return true. Otherwise, this routine returns
1354/// false and User is unspecified.
1355///
1356/// \param AllowConversionFunctions true if the conversion should
1357/// consider conversion functions at all. If false, only constructors
1358/// will be considered.
1359///
1360/// \param AllowExplicit true if the conversion should consider C++0x
1361/// "explicit" conversion functions as well as non-explicit conversion
1362/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001363///
1364/// \param ForceRValue true if the expression should be treated as an rvalue
1365/// for overload resolution.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001366Sema::OverloadingResult Sema::IsUserDefinedConversion(
1367 Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001368 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001369 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001370 bool AllowConversionFunctions,
Mike Stump11289f42009-09-09 15:08:12 +00001371 bool AllowExplicit, bool ForceRValue) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001372 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001373 if (CXXRecordDecl *ToRecordDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001374 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1375 // C++ [over.match.ctor]p1:
1376 // When objects of class type are direct-initialized (8.5), or
1377 // copy-initialized from an expression of the same or a
1378 // derived class type (8.5), overload resolution selects the
1379 // constructor. [...] For copy-initialization, the candidate
1380 // functions are all the converting constructors (12.3.1) of
1381 // that class. The argument list is the expression-list within
1382 // the parentheses of the initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001383 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001384 = Context.DeclarationNames.getCXXConstructorName(
1385 Context.getCanonicalType(ToType).getUnqualifiedType());
1386 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001387 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001388 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001389 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001390 // Find the constructor (which may be a template).
1391 CXXConstructorDecl *Constructor = 0;
1392 FunctionTemplateDecl *ConstructorTmpl
1393 = dyn_cast<FunctionTemplateDecl>(*Con);
1394 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001395 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001396 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1397 else
1398 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump11289f42009-09-09 15:08:12 +00001399
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001400 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001401 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001402 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001403 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001404 1, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00001405 /*SuppressUserConversions=*/true,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001406 ForceRValue);
1407 else
1408 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1409 /*SuppressUserConversions=*/true, ForceRValue);
1410 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001411 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001412 }
1413 }
1414
Douglas Gregor576e98c2009-01-30 23:27:23 +00001415 if (!AllowConversionFunctions) {
1416 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001417 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1418 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001419 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001420 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001421 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001422 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001423 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001424 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1425 // Add all of the conversion functions as candidates.
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001426 OverloadedFunctionDecl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001427 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001428 for (OverloadedFunctionDecl::function_iterator Func
1429 = Conversions->function_begin();
1430 Func != Conversions->function_end(); ++Func) {
1431 CXXConversionDecl *Conv;
1432 FunctionTemplateDecl *ConvTemplate;
1433 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1434 if (ConvTemplate)
1435 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1436 else
1437 Conv = dyn_cast<CXXConversionDecl>(*Func);
1438
1439 if (AllowExplicit || !Conv->isExplicit()) {
1440 if (ConvTemplate)
1441 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1442 CandidateSet);
1443 else
1444 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1445 }
1446 }
1447 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001448 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001449
1450 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001451 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001452 case OR_Success:
1453 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001454 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001455 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1456 // C++ [over.ics.user]p1:
1457 // If the user-defined conversion is specified by a
1458 // constructor (12.3.1), the initial standard conversion
1459 // sequence converts the source type to the type required by
1460 // the argument of the constructor.
1461 //
1462 // FIXME: What about ellipsis conversions?
1463 QualType ThisType = Constructor->getThisType(Context);
1464 User.Before = Best->Conversions[0].Standard;
1465 User.ConversionFunction = Constructor;
1466 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001467 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001468 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001469 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001470 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001471 } else if (CXXConversionDecl *Conversion
1472 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1473 // C++ [over.ics.user]p1:
1474 //
1475 // [...] If the user-defined conversion is specified by a
1476 // conversion function (12.3.2), the initial standard
1477 // conversion sequence converts the source type to the
1478 // implicit object parameter of the conversion function.
1479 User.Before = Best->Conversions[0].Standard;
1480 User.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00001481
1482 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001483 // The second standard conversion sequence converts the
1484 // result of the user-defined conversion to the target type
1485 // for the sequence. Since an implicit conversion sequence
1486 // is an initialization, the special rules for
1487 // initialization by user-defined conversion apply when
1488 // selecting the best user-defined conversion for a
1489 // user-defined conversion sequence (see 13.3.3 and
1490 // 13.3.3.1).
1491 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001492 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001493 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001494 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001495 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001496 }
Mike Stump11289f42009-09-09 15:08:12 +00001497
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001498 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001499 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001500 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001501 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001502 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001503
1504 case OR_Ambiguous:
1505 // FIXME: See C++ [over.best.ics]p10 for the handling of
1506 // ambiguous conversion sequences.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001507 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001508 }
1509
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001510 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001511}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001512
1513bool
1514Sema::DiagnoseAmbiguousUserDefinedConversion(Expr *From, QualType ToType) {
1515 ImplicitConversionSequence ICS;
1516 OverloadCandidateSet CandidateSet;
1517 OverloadingResult OvResult =
1518 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1519 CandidateSet, true, false, false);
1520 if (OvResult != OR_Ambiguous)
1521 return false;
1522 Diag(From->getSourceRange().getBegin(),
1523 diag::err_typecheck_ambiguous_condition)
1524 << From->getType() << ToType << From->getSourceRange();
1525 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1526 return true;
1527}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001528
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001529/// CompareImplicitConversionSequences - Compare two implicit
1530/// conversion sequences to determine whether one is better than the
1531/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001532ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001533Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1534 const ImplicitConversionSequence& ICS2)
1535{
1536 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1537 // conversion sequences (as defined in 13.3.3.1)
1538 // -- a standard conversion sequence (13.3.3.1.1) is a better
1539 // conversion sequence than a user-defined conversion sequence or
1540 // an ellipsis conversion sequence, and
1541 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1542 // conversion sequence than an ellipsis conversion sequence
1543 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001544 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001545 if (ICS1.ConversionKind < ICS2.ConversionKind)
1546 return ImplicitConversionSequence::Better;
1547 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1548 return ImplicitConversionSequence::Worse;
1549
1550 // Two implicit conversion sequences of the same form are
1551 // indistinguishable conversion sequences unless one of the
1552 // following rules apply: (C++ 13.3.3.2p3):
1553 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1554 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001555 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001556 ImplicitConversionSequence::UserDefinedConversion) {
1557 // User-defined conversion sequence U1 is a better conversion
1558 // sequence than another user-defined conversion sequence U2 if
1559 // they contain the same user-defined conversion function or
1560 // constructor and if the second standard conversion sequence of
1561 // U1 is better than the second standard conversion sequence of
1562 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001563 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001564 ICS2.UserDefined.ConversionFunction)
1565 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1566 ICS2.UserDefined.After);
1567 }
1568
1569 return ImplicitConversionSequence::Indistinguishable;
1570}
1571
1572/// CompareStandardConversionSequences - Compare two standard
1573/// conversion sequences to determine whether one is better than the
1574/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001575ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001576Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1577 const StandardConversionSequence& SCS2)
1578{
1579 // Standard conversion sequence S1 is a better conversion sequence
1580 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1581
1582 // -- S1 is a proper subsequence of S2 (comparing the conversion
1583 // sequences in the canonical form defined by 13.3.3.1.1,
1584 // excluding any Lvalue Transformation; the identity conversion
1585 // sequence is considered to be a subsequence of any
1586 // non-identity conversion sequence) or, if not that,
1587 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1588 // Neither is a proper subsequence of the other. Do nothing.
1589 ;
1590 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1591 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001592 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001593 SCS1.Third == ICK_Identity))
1594 // SCS1 is a proper subsequence of SCS2.
1595 return ImplicitConversionSequence::Better;
1596 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1597 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001598 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001599 SCS2.Third == ICK_Identity))
1600 // SCS2 is a proper subsequence of SCS1.
1601 return ImplicitConversionSequence::Worse;
1602
1603 // -- the rank of S1 is better than the rank of S2 (by the rules
1604 // defined below), or, if not that,
1605 ImplicitConversionRank Rank1 = SCS1.getRank();
1606 ImplicitConversionRank Rank2 = SCS2.getRank();
1607 if (Rank1 < Rank2)
1608 return ImplicitConversionSequence::Better;
1609 else if (Rank2 < Rank1)
1610 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001611
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001612 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1613 // are indistinguishable unless one of the following rules
1614 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001615
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001616 // A conversion that is not a conversion of a pointer, or
1617 // pointer to member, to bool is better than another conversion
1618 // that is such a conversion.
1619 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1620 return SCS2.isPointerConversionToBool()
1621 ? ImplicitConversionSequence::Better
1622 : ImplicitConversionSequence::Worse;
1623
Douglas Gregor5c407d92008-10-23 00:40:37 +00001624 // C++ [over.ics.rank]p4b2:
1625 //
1626 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001627 // conversion of B* to A* is better than conversion of B* to
1628 // void*, and conversion of A* to void* is better than conversion
1629 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001630 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001631 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001632 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001633 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001634 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1635 // Exactly one of the conversion sequences is a conversion to
1636 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001637 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1638 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001639 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1640 // Neither conversion sequence converts to a void pointer; compare
1641 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001642 if (ImplicitConversionSequence::CompareKind DerivedCK
1643 = CompareDerivedToBaseConversions(SCS1, SCS2))
1644 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001645 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1646 // Both conversion sequences are conversions to void
1647 // pointers. Compare the source types to determine if there's an
1648 // inheritance relationship in their sources.
1649 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1650 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1651
1652 // Adjust the types we're converting from via the array-to-pointer
1653 // conversion, if we need to.
1654 if (SCS1.First == ICK_Array_To_Pointer)
1655 FromType1 = Context.getArrayDecayedType(FromType1);
1656 if (SCS2.First == ICK_Array_To_Pointer)
1657 FromType2 = Context.getArrayDecayedType(FromType2);
1658
Mike Stump11289f42009-09-09 15:08:12 +00001659 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001660 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001661 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001662 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001663
1664 if (IsDerivedFrom(FromPointee2, FromPointee1))
1665 return ImplicitConversionSequence::Better;
1666 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1667 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001668
1669 // Objective-C++: If one interface is more specific than the
1670 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001671 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1672 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001673 if (FromIface1 && FromIface1) {
1674 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1675 return ImplicitConversionSequence::Better;
1676 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1677 return ImplicitConversionSequence::Worse;
1678 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001679 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001680
1681 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1682 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001683 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001684 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001685 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001686
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001687 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001688 // C++0x [over.ics.rank]p3b4:
1689 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1690 // implicit object parameter of a non-static member function declared
1691 // without a ref-qualifier, and S1 binds an rvalue reference to an
1692 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001693 // FIXME: We don't know if we're dealing with the implicit object parameter,
1694 // or if the member function in this case has a ref qualifier.
1695 // (Of course, we don't have ref qualifiers yet.)
1696 if (SCS1.RRefBinding != SCS2.RRefBinding)
1697 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1698 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001699
1700 // C++ [over.ics.rank]p3b4:
1701 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1702 // which the references refer are the same type except for
1703 // top-level cv-qualifiers, and the type to which the reference
1704 // initialized by S2 refers is more cv-qualified than the type
1705 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001706 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1707 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001708 T1 = Context.getCanonicalType(T1);
1709 T2 = Context.getCanonicalType(T2);
1710 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1711 if (T2.isMoreQualifiedThan(T1))
1712 return ImplicitConversionSequence::Better;
1713 else if (T1.isMoreQualifiedThan(T2))
1714 return ImplicitConversionSequence::Worse;
1715 }
1716 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001717
1718 return ImplicitConversionSequence::Indistinguishable;
1719}
1720
1721/// CompareQualificationConversions - Compares two standard conversion
1722/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001723/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1724ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001725Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001726 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001727 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001728 // -- S1 and S2 differ only in their qualification conversion and
1729 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1730 // cv-qualification signature of type T1 is a proper subset of
1731 // the cv-qualification signature of type T2, and S1 is not the
1732 // deprecated string literal array-to-pointer conversion (4.2).
1733 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1734 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1735 return ImplicitConversionSequence::Indistinguishable;
1736
1737 // FIXME: the example in the standard doesn't use a qualification
1738 // conversion (!)
1739 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1740 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1741 T1 = Context.getCanonicalType(T1);
1742 T2 = Context.getCanonicalType(T2);
1743
1744 // If the types are the same, we won't learn anything by unwrapped
1745 // them.
1746 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1747 return ImplicitConversionSequence::Indistinguishable;
1748
Mike Stump11289f42009-09-09 15:08:12 +00001749 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001750 = ImplicitConversionSequence::Indistinguishable;
1751 while (UnwrapSimilarPointerTypes(T1, T2)) {
1752 // Within each iteration of the loop, we check the qualifiers to
1753 // determine if this still looks like a qualification
1754 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001755 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001756 // until there are no more pointers or pointers-to-members left
1757 // to unwrap. This essentially mimics what
1758 // IsQualificationConversion does, but here we're checking for a
1759 // strict subset of qualifiers.
1760 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1761 // The qualifiers are the same, so this doesn't tell us anything
1762 // about how the sequences rank.
1763 ;
1764 else if (T2.isMoreQualifiedThan(T1)) {
1765 // T1 has fewer qualifiers, so it could be the better sequence.
1766 if (Result == ImplicitConversionSequence::Worse)
1767 // Neither has qualifiers that are a subset of the other's
1768 // qualifiers.
1769 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001770
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001771 Result = ImplicitConversionSequence::Better;
1772 } else if (T1.isMoreQualifiedThan(T2)) {
1773 // T2 has fewer qualifiers, so it could be the better sequence.
1774 if (Result == ImplicitConversionSequence::Better)
1775 // Neither has qualifiers that are a subset of the other's
1776 // qualifiers.
1777 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001778
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001779 Result = ImplicitConversionSequence::Worse;
1780 } else {
1781 // Qualifiers are disjoint.
1782 return ImplicitConversionSequence::Indistinguishable;
1783 }
1784
1785 // If the types after this point are equivalent, we're done.
1786 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1787 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001788 }
1789
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001790 // Check that the winning standard conversion sequence isn't using
1791 // the deprecated string literal array to pointer conversion.
1792 switch (Result) {
1793 case ImplicitConversionSequence::Better:
1794 if (SCS1.Deprecated)
1795 Result = ImplicitConversionSequence::Indistinguishable;
1796 break;
1797
1798 case ImplicitConversionSequence::Indistinguishable:
1799 break;
1800
1801 case ImplicitConversionSequence::Worse:
1802 if (SCS2.Deprecated)
1803 Result = ImplicitConversionSequence::Indistinguishable;
1804 break;
1805 }
1806
1807 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001808}
1809
Douglas Gregor5c407d92008-10-23 00:40:37 +00001810/// CompareDerivedToBaseConversions - Compares two standard conversion
1811/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001812/// various kinds of derived-to-base conversions (C++
1813/// [over.ics.rank]p4b3). As part of these checks, we also look at
1814/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001815ImplicitConversionSequence::CompareKind
1816Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1817 const StandardConversionSequence& SCS2) {
1818 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1819 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1820 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1821 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1822
1823 // Adjust the types we're converting from via the array-to-pointer
1824 // conversion, if we need to.
1825 if (SCS1.First == ICK_Array_To_Pointer)
1826 FromType1 = Context.getArrayDecayedType(FromType1);
1827 if (SCS2.First == ICK_Array_To_Pointer)
1828 FromType2 = Context.getArrayDecayedType(FromType2);
1829
1830 // Canonicalize all of the types.
1831 FromType1 = Context.getCanonicalType(FromType1);
1832 ToType1 = Context.getCanonicalType(ToType1);
1833 FromType2 = Context.getCanonicalType(FromType2);
1834 ToType2 = Context.getCanonicalType(ToType2);
1835
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001836 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001837 //
1838 // If class B is derived directly or indirectly from class A and
1839 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001840 //
1841 // For Objective-C, we let A, B, and C also be Objective-C
1842 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001843
1844 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001845 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001846 SCS2.Second == ICK_Pointer_Conversion &&
1847 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1848 FromType1->isPointerType() && FromType2->isPointerType() &&
1849 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001850 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001851 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001852 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001853 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001854 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001855 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001856 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001857 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001858
John McCall9dd450b2009-09-21 23:43:11 +00001859 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1860 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1861 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1862 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001863
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001864 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001865 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1866 if (IsDerivedFrom(ToPointee1, ToPointee2))
1867 return ImplicitConversionSequence::Better;
1868 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1869 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001870
1871 if (ToIface1 && ToIface2) {
1872 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1873 return ImplicitConversionSequence::Better;
1874 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1875 return ImplicitConversionSequence::Worse;
1876 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001877 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001878
1879 // -- conversion of B* to A* is better than conversion of C* to A*,
1880 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1881 if (IsDerivedFrom(FromPointee2, FromPointee1))
1882 return ImplicitConversionSequence::Better;
1883 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1884 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001885
Douglas Gregor237f96c2008-11-26 23:31:11 +00001886 if (FromIface1 && FromIface2) {
1887 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1888 return ImplicitConversionSequence::Better;
1889 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1890 return ImplicitConversionSequence::Worse;
1891 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001892 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001893 }
1894
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001895 // Compare based on reference bindings.
1896 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1897 SCS1.Second == ICK_Derived_To_Base) {
1898 // -- binding of an expression of type C to a reference of type
1899 // B& is better than binding an expression of type C to a
1900 // reference of type A&,
1901 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1902 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1903 if (IsDerivedFrom(ToType1, ToType2))
1904 return ImplicitConversionSequence::Better;
1905 else if (IsDerivedFrom(ToType2, ToType1))
1906 return ImplicitConversionSequence::Worse;
1907 }
1908
Douglas Gregor2fe98832008-11-03 19:09:14 +00001909 // -- binding of an expression of type B to a reference of type
1910 // A& is better than binding an expression of type C to a
1911 // reference of type A&,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001912 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1913 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1914 if (IsDerivedFrom(FromType2, FromType1))
1915 return ImplicitConversionSequence::Better;
1916 else if (IsDerivedFrom(FromType1, FromType2))
1917 return ImplicitConversionSequence::Worse;
1918 }
1919 }
1920
1921
1922 // FIXME: conversion of A::* to B::* is better than conversion of
1923 // A::* to C::*,
1924
1925 // FIXME: conversion of B::* to C::* is better than conversion of
1926 // A::* to C::*, and
1927
Douglas Gregor2fe98832008-11-03 19:09:14 +00001928 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1929 SCS1.Second == ICK_Derived_To_Base) {
1930 // -- conversion of C to B is better than conversion of C to A,
1931 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1932 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1933 if (IsDerivedFrom(ToType1, ToType2))
1934 return ImplicitConversionSequence::Better;
1935 else if (IsDerivedFrom(ToType2, ToType1))
1936 return ImplicitConversionSequence::Worse;
1937 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001938
Douglas Gregor2fe98832008-11-03 19:09:14 +00001939 // -- conversion of B to A is better than conversion of C to A.
1940 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1941 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1942 if (IsDerivedFrom(FromType2, FromType1))
1943 return ImplicitConversionSequence::Better;
1944 else if (IsDerivedFrom(FromType1, FromType2))
1945 return ImplicitConversionSequence::Worse;
1946 }
1947 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001948
Douglas Gregor5c407d92008-10-23 00:40:37 +00001949 return ImplicitConversionSequence::Indistinguishable;
1950}
1951
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001952/// TryCopyInitialization - Try to copy-initialize a value of type
1953/// ToType from the expression From. Return the implicit conversion
1954/// sequence required to pass this argument, which may be a bad
1955/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00001956/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00001957/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1958/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00001959ImplicitConversionSequence
1960Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00001961 bool SuppressUserConversions, bool ForceRValue,
1962 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001963 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001964 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00001965 CheckReferenceInit(From, ToType,
Anders Carlsson271e3a42009-08-27 17:30:43 +00001966 SuppressUserConversions,
1967 /*AllowExplicit=*/false,
1968 ForceRValue,
1969 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001970 return ICS;
1971 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001972 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001973 SuppressUserConversions,
1974 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001975 ForceRValue,
1976 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001977 }
1978}
1979
Sebastian Redl42e92c42009-04-12 17:16:29 +00001980/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1981/// the expression @p From. Returns true (and emits a diagnostic) if there was
1982/// an error, returns false if the initialization succeeded. Elidable should
1983/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1984/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00001985bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00001986 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001987 if (!getLangOptions().CPlusPlus) {
1988 // In C, argument passing is the same as performing an assignment.
1989 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001990
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001991 AssignConvertType ConvTy =
1992 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00001993 if (ConvTy != Compatible &&
1994 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1995 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00001996
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001997 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1998 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001999 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002000
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002001 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002002 return CheckReferenceInit(From, ToType,
2003 /*SuppressUserConversions=*/false,
2004 /*AllowExplicit=*/false,
2005 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002006
Sebastian Redl42e92c42009-04-12 17:16:29 +00002007 if (!PerformImplicitConversion(From, ToType, Flavor,
2008 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002009 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002010 if (!DiagnoseAmbiguousUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002011 return Diag(From->getSourceRange().getBegin(),
2012 diag::err_typecheck_convert_incompatible)
2013 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002014 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002015}
2016
Douglas Gregor436424c2008-11-18 23:14:02 +00002017/// TryObjectArgumentInitialization - Try to initialize the object
2018/// parameter of the given member function (@c Method) from the
2019/// expression @p From.
2020ImplicitConversionSequence
2021Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2022 QualType ClassType = Context.getTypeDeclType(Method->getParent());
2023 unsigned MethodQuals = Method->getTypeQualifiers();
2024 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
2025
2026 // Set up the conversion sequence as a "bad" conversion, to allow us
2027 // to exit early.
2028 ImplicitConversionSequence ICS;
2029 ICS.Standard.setAsIdentityConversion();
2030 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2031
2032 // We need to have an object of class type.
2033 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002034 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002035 FromType = PT->getPointeeType();
2036
2037 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002038
2039 // The implicit object parmeter is has the type "reference to cv X",
2040 // where X is the class of which the function is a member
2041 // (C++ [over.match.funcs]p4). However, when finding an implicit
2042 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002043 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002044 // (C++ [over.match.funcs]p5). We perform a simplified version of
2045 // reference binding here, that allows class rvalues to bind to
2046 // non-constant references.
2047
2048 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2049 // with the implicit object parameter (C++ [over.match.funcs]p5).
2050 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2051 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2052 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2053 return ICS;
2054
2055 // Check that we have either the same type or a derived type. It
2056 // affects the conversion rank.
2057 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2058 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2059 ICS.Standard.Second = ICK_Identity;
2060 else if (IsDerivedFrom(FromType, ClassType))
2061 ICS.Standard.Second = ICK_Derived_To_Base;
2062 else
2063 return ICS;
2064
2065 // Success. Mark this as a reference binding.
2066 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2067 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2068 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2069 ICS.Standard.ReferenceBinding = true;
2070 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002071 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002072 return ICS;
2073}
2074
2075/// PerformObjectArgumentInitialization - Perform initialization of
2076/// the implicit object parameter for the given Method with the given
2077/// expression.
2078bool
2079Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002080 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002081 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002082 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002083
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002084 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002085 FromRecordType = PT->getPointeeType();
2086 DestType = Method->getThisType(Context);
2087 } else {
2088 FromRecordType = From->getType();
2089 DestType = ImplicitParamRecordType;
2090 }
2091
Mike Stump11289f42009-09-09 15:08:12 +00002092 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002093 = TryObjectArgumentInitialization(From, Method);
2094 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2095 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002096 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002097 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002098
Douglas Gregor436424c2008-11-18 23:14:02 +00002099 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002100 CheckDerivedToBaseConversion(FromRecordType,
2101 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002102 From->getSourceRange().getBegin(),
2103 From->getSourceRange()))
2104 return true;
2105
Mike Stump11289f42009-09-09 15:08:12 +00002106 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002107 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002108 return false;
2109}
2110
Douglas Gregor5fb53972009-01-14 15:45:31 +00002111/// TryContextuallyConvertToBool - Attempt to contextually convert the
2112/// expression From to bool (C++0x [conv]p3).
2113ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002114 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002115 // FIXME: Are these flags correct?
2116 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002117 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002118 /*ForceRValue=*/false,
2119 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002120}
2121
2122/// PerformContextuallyConvertToBool - Perform a contextual conversion
2123/// of the expression From to bool (C++0x [conv]p3).
2124bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2125 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2126 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2127 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002128
2129 if (!DiagnoseAmbiguousUserDefinedConversion(From, Context.BoolTy))
2130 return Diag(From->getSourceRange().getBegin(),
2131 diag::err_typecheck_bool_condition)
2132 << From->getType() << From->getSourceRange();
2133 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002134}
2135
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002136/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002137/// candidate functions, using the given function call arguments. If
2138/// @p SuppressUserConversions, then don't allow user-defined
2139/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002140/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2141/// hacky way to implement the overloading rules for elidable copy
2142/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002143///
2144/// \para PartialOverloading true if we are performing "partial" overloading
2145/// based on an incomplete set of function arguments. This feature is used by
2146/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002147void
2148Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002149 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002150 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002151 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002152 bool ForceRValue,
2153 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002154 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002155 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002156 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002157 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002158 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002159 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002160 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002161
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002162 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002163 if (!isa<CXXConstructorDecl>(Method)) {
2164 // If we get here, it's because we're calling a member function
2165 // that is named without a member access expression (e.g.,
2166 // "this->f") that was either written explicitly or created
2167 // implicitly. This can happen with a qualified call to a member
2168 // function, e.g., X::f(). We use a NULL object as the implied
2169 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002170 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002171 SuppressUserConversions, ForceRValue);
2172 return;
2173 }
2174 // We treat a constructor like a non-member function, since its object
2175 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002176 }
2177
2178
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002179 // Add this candidate
2180 CandidateSet.push_back(OverloadCandidate());
2181 OverloadCandidate& Candidate = CandidateSet.back();
2182 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002183 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002184 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002185 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002186
2187 unsigned NumArgsInProto = Proto->getNumArgs();
2188
2189 // (C++ 13.3.2p2): A candidate function having fewer than m
2190 // parameters is viable only if it has an ellipsis in its parameter
2191 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002192 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2193 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002194 Candidate.Viable = false;
2195 return;
2196 }
2197
2198 // (C++ 13.3.2p2): A candidate function having more than m parameters
2199 // is viable only if the (m+1)st parameter has a default argument
2200 // (8.3.6). For the purposes of overload resolution, the
2201 // parameter list is truncated on the right, so that there are
2202 // exactly m parameters.
2203 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002204 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002205 // Not enough arguments.
2206 Candidate.Viable = false;
2207 return;
2208 }
2209
2210 // Determine the implicit conversion sequences for each of the
2211 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002212 Candidate.Conversions.resize(NumArgs);
2213 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2214 if (ArgIdx < NumArgsInProto) {
2215 // (C++ 13.3.2p3): for F to be a viable function, there shall
2216 // exist for each argument an implicit conversion sequence
2217 // (13.3.3.1) that converts that argument to the corresponding
2218 // parameter of F.
2219 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002220 Candidate.Conversions[ArgIdx]
2221 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002222 SuppressUserConversions, ForceRValue,
2223 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002224 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002225 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002226 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002227 break;
2228 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002229 } else {
2230 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2231 // argument for which there is no corresponding parameter is
2232 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002233 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002234 = ImplicitConversionSequence::EllipsisConversion;
2235 }
2236 }
2237}
2238
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002239/// \brief Add all of the function declarations in the given function set to
2240/// the overload canddiate set.
2241void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2242 Expr **Args, unsigned NumArgs,
2243 OverloadCandidateSet& CandidateSet,
2244 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002245 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002246 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002247 F != FEnd; ++F) {
2248 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
Mike Stump11289f42009-09-09 15:08:12 +00002249 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002250 SuppressUserConversions);
2251 else
Douglas Gregor89026b52009-06-30 23:57:56 +00002252 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2253 /*FIXME: explicit args */false, 0, 0,
Mike Stump11289f42009-09-09 15:08:12 +00002254 Args, NumArgs, CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002255 SuppressUserConversions);
2256 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002257}
2258
Douglas Gregor436424c2008-11-18 23:14:02 +00002259/// AddMethodCandidate - Adds the given C++ member function to the set
2260/// of candidate functions, using the given function call arguments
2261/// and the object argument (@c Object). For example, in a call
2262/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2263/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2264/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002265/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2266/// a slightly hacky way to implement the overloading rules for elidable copy
2267/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002268void
Douglas Gregor436424c2008-11-18 23:14:02 +00002269Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2270 Expr **Args, unsigned NumArgs,
2271 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002272 bool SuppressUserConversions, bool ForceRValue) {
2273 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002274 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002275 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002276 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002277 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002278 assert(!isa<CXXConstructorDecl>(Method) &&
2279 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002280
2281 // Add this candidate
2282 CandidateSet.push_back(OverloadCandidate());
2283 OverloadCandidate& Candidate = CandidateSet.back();
2284 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002285 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002286 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002287
2288 unsigned NumArgsInProto = Proto->getNumArgs();
2289
2290 // (C++ 13.3.2p2): A candidate function having fewer than m
2291 // parameters is viable only if it has an ellipsis in its parameter
2292 // list (8.3.5).
2293 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2294 Candidate.Viable = false;
2295 return;
2296 }
2297
2298 // (C++ 13.3.2p2): A candidate function having more than m parameters
2299 // is viable only if the (m+1)st parameter has a default argument
2300 // (8.3.6). For the purposes of overload resolution, the
2301 // parameter list is truncated on the right, so that there are
2302 // exactly m parameters.
2303 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2304 if (NumArgs < MinRequiredArgs) {
2305 // Not enough arguments.
2306 Candidate.Viable = false;
2307 return;
2308 }
2309
2310 Candidate.Viable = true;
2311 Candidate.Conversions.resize(NumArgs + 1);
2312
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002313 if (Method->isStatic() || !Object)
2314 // The implicit object argument is ignored.
2315 Candidate.IgnoreObjectArgument = true;
2316 else {
2317 // Determine the implicit conversion sequence for the object
2318 // parameter.
2319 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002320 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002321 == ImplicitConversionSequence::BadConversion) {
2322 Candidate.Viable = false;
2323 return;
2324 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002325 }
2326
2327 // Determine the implicit conversion sequences for each of the
2328 // arguments.
2329 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2330 if (ArgIdx < NumArgsInProto) {
2331 // (C++ 13.3.2p3): for F to be a viable function, there shall
2332 // exist for each argument an implicit conversion sequence
2333 // (13.3.3.1) that converts that argument to the corresponding
2334 // parameter of F.
2335 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002336 Candidate.Conversions[ArgIdx + 1]
2337 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002338 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002339 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002340 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002341 == ImplicitConversionSequence::BadConversion) {
2342 Candidate.Viable = false;
2343 break;
2344 }
2345 } else {
2346 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2347 // argument for which there is no corresponding parameter is
2348 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002349 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002350 = ImplicitConversionSequence::EllipsisConversion;
2351 }
2352 }
2353}
2354
Douglas Gregor97628d62009-08-21 00:16:32 +00002355/// \brief Add a C++ member function template as a candidate to the candidate
2356/// set, using template argument deduction to produce an appropriate member
2357/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002358void
Douglas Gregor97628d62009-08-21 00:16:32 +00002359Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2360 bool HasExplicitTemplateArgs,
2361 const TemplateArgument *ExplicitTemplateArgs,
2362 unsigned NumExplicitTemplateArgs,
2363 Expr *Object, Expr **Args, unsigned NumArgs,
2364 OverloadCandidateSet& CandidateSet,
2365 bool SuppressUserConversions,
2366 bool ForceRValue) {
2367 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002368 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002369 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002370 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002371 // candidate functions in the usual way.113) A given name can refer to one
2372 // or more function templates and also to a set of overloaded non-template
2373 // functions. In such a case, the candidate functions generated from each
2374 // function template are combined with the set of non-template candidate
2375 // functions.
2376 TemplateDeductionInfo Info(Context);
2377 FunctionDecl *Specialization = 0;
2378 if (TemplateDeductionResult Result
2379 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2380 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2381 Args, NumArgs, Specialization, Info)) {
2382 // FIXME: Record what happened with template argument deduction, so
2383 // that we can give the user a beautiful diagnostic.
2384 (void)Result;
2385 return;
2386 }
Mike Stump11289f42009-09-09 15:08:12 +00002387
Douglas Gregor97628d62009-08-21 00:16:32 +00002388 // Add the function template specialization produced by template argument
2389 // deduction as a candidate.
2390 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002391 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002392 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002393 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002394 CandidateSet, SuppressUserConversions, ForceRValue);
2395}
2396
Douglas Gregor05155d82009-08-21 23:19:43 +00002397/// \brief Add a C++ function template specialization as a candidate
2398/// in the candidate set, using template argument deduction to produce
2399/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002400void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002401Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor89026b52009-06-30 23:57:56 +00002402 bool HasExplicitTemplateArgs,
2403 const TemplateArgument *ExplicitTemplateArgs,
2404 unsigned NumExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002405 Expr **Args, unsigned NumArgs,
2406 OverloadCandidateSet& CandidateSet,
2407 bool SuppressUserConversions,
2408 bool ForceRValue) {
2409 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002410 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002411 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002412 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002413 // candidate functions in the usual way.113) A given name can refer to one
2414 // or more function templates and also to a set of overloaded non-template
2415 // functions. In such a case, the candidate functions generated from each
2416 // function template are combined with the set of non-template candidate
2417 // functions.
2418 TemplateDeductionInfo Info(Context);
2419 FunctionDecl *Specialization = 0;
2420 if (TemplateDeductionResult Result
Douglas Gregor89026b52009-06-30 23:57:56 +00002421 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2422 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2423 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002424 // FIXME: Record what happened with template argument deduction, so
2425 // that we can give the user a beautiful diagnostic.
2426 (void)Result;
2427 return;
2428 }
Mike Stump11289f42009-09-09 15:08:12 +00002429
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002430 // Add the function template specialization produced by template argument
2431 // deduction as a candidate.
2432 assert(Specialization && "Missing function template specialization?");
2433 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2434 SuppressUserConversions, ForceRValue);
2435}
Mike Stump11289f42009-09-09 15:08:12 +00002436
Douglas Gregora1f013e2008-11-07 22:36:19 +00002437/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002438/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002439/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002440/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002441/// (which may or may not be the same type as the type that the
2442/// conversion function produces).
2443void
2444Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2445 Expr *From, QualType ToType,
2446 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002447 assert(!Conversion->getDescribedFunctionTemplate() &&
2448 "Conversion function templates use AddTemplateConversionCandidate");
2449
Douglas Gregora1f013e2008-11-07 22:36:19 +00002450 // Add this candidate
2451 CandidateSet.push_back(OverloadCandidate());
2452 OverloadCandidate& Candidate = CandidateSet.back();
2453 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002454 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002455 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002456 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002457 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002458 = Conversion->getConversionType().getAsOpaquePtr();
2459 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2460
Douglas Gregor436424c2008-11-18 23:14:02 +00002461 // Determine the implicit conversion sequence for the implicit
2462 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002463 Candidate.Viable = true;
2464 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002465 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002466 // Conversion functions to a different type in the base class is visible in
2467 // the derived class. So, a derived to base conversion should not participate
2468 // in overload resolution.
2469 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2470 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002471 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002472 == ImplicitConversionSequence::BadConversion) {
2473 Candidate.Viable = false;
2474 return;
2475 }
2476
2477 // To determine what the conversion from the result of calling the
2478 // conversion function to the type we're eventually trying to
2479 // convert to (ToType), we need to synthesize a call to the
2480 // conversion function and attempt copy initialization from it. This
2481 // makes sure that we get the right semantics with respect to
2482 // lvalues/rvalues and the type. Fortunately, we can allocate this
2483 // call on the stack and we don't need its arguments to be
2484 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002485 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregora1f013e2008-11-07 22:36:19 +00002486 SourceLocation());
2487 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlssona2615922009-07-31 00:48:10 +00002488 CastExpr::CK_Unknown,
Douglas Gregora11693b2008-11-12 17:17:38 +00002489 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002490
2491 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002492 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2493 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002494 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002495 Conversion->getConversionType().getNonReferenceType(),
2496 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002497 ImplicitConversionSequence ICS =
2498 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002499 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002500 /*ForceRValue=*/false,
2501 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002502
Douglas Gregora1f013e2008-11-07 22:36:19 +00002503 switch (ICS.ConversionKind) {
2504 case ImplicitConversionSequence::StandardConversion:
2505 Candidate.FinalConversion = ICS.Standard;
2506 break;
2507
2508 case ImplicitConversionSequence::BadConversion:
2509 Candidate.Viable = false;
2510 break;
2511
2512 default:
Mike Stump11289f42009-09-09 15:08:12 +00002513 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002514 "Can only end up with a standard conversion sequence or failure");
2515 }
2516}
2517
Douglas Gregor05155d82009-08-21 23:19:43 +00002518/// \brief Adds a conversion function template specialization
2519/// candidate to the overload set, using template argument deduction
2520/// to deduce the template arguments of the conversion function
2521/// template from the type that we are converting to (C++
2522/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002523void
Douglas Gregor05155d82009-08-21 23:19:43 +00002524Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2525 Expr *From, QualType ToType,
2526 OverloadCandidateSet &CandidateSet) {
2527 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2528 "Only conversion function templates permitted here");
2529
2530 TemplateDeductionInfo Info(Context);
2531 CXXConversionDecl *Specialization = 0;
2532 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002533 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002534 Specialization, Info)) {
2535 // FIXME: Record what happened with template argument deduction, so
2536 // that we can give the user a beautiful diagnostic.
2537 (void)Result;
2538 return;
2539 }
Mike Stump11289f42009-09-09 15:08:12 +00002540
Douglas Gregor05155d82009-08-21 23:19:43 +00002541 // Add the conversion function template specialization produced by
2542 // template argument deduction as a candidate.
2543 assert(Specialization && "Missing function template specialization?");
2544 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2545}
2546
Douglas Gregorab7897a2008-11-19 22:57:39 +00002547/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2548/// converts the given @c Object to a function pointer via the
2549/// conversion function @c Conversion, and then attempts to call it
2550/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2551/// the type of function that we'll eventually be calling.
2552void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002553 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002554 Expr *Object, Expr **Args, unsigned NumArgs,
2555 OverloadCandidateSet& CandidateSet) {
2556 CandidateSet.push_back(OverloadCandidate());
2557 OverloadCandidate& Candidate = CandidateSet.back();
2558 Candidate.Function = 0;
2559 Candidate.Surrogate = Conversion;
2560 Candidate.Viable = true;
2561 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002562 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002563 Candidate.Conversions.resize(NumArgs + 1);
2564
2565 // Determine the implicit conversion sequence for the implicit
2566 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002567 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002568 = TryObjectArgumentInitialization(Object, Conversion);
2569 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2570 Candidate.Viable = false;
2571 return;
2572 }
2573
2574 // The first conversion is actually a user-defined conversion whose
2575 // first conversion is ObjectInit's standard conversion (which is
2576 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002577 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002578 = ImplicitConversionSequence::UserDefinedConversion;
2579 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2580 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002581 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002582 = Candidate.Conversions[0].UserDefined.Before;
2583 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2584
Mike Stump11289f42009-09-09 15:08:12 +00002585 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002586 unsigned NumArgsInProto = Proto->getNumArgs();
2587
2588 // (C++ 13.3.2p2): A candidate function having fewer than m
2589 // parameters is viable only if it has an ellipsis in its parameter
2590 // list (8.3.5).
2591 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2592 Candidate.Viable = false;
2593 return;
2594 }
2595
2596 // Function types don't have any default arguments, so just check if
2597 // we have enough arguments.
2598 if (NumArgs < NumArgsInProto) {
2599 // Not enough arguments.
2600 Candidate.Viable = false;
2601 return;
2602 }
2603
2604 // Determine the implicit conversion sequences for each of the
2605 // arguments.
2606 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2607 if (ArgIdx < NumArgsInProto) {
2608 // (C++ 13.3.2p3): for F to be a viable function, there shall
2609 // exist for each argument an implicit conversion sequence
2610 // (13.3.3.1) that converts that argument to the corresponding
2611 // parameter of F.
2612 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002613 Candidate.Conversions[ArgIdx + 1]
2614 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002615 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002616 /*ForceRValue=*/false,
2617 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002618 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002619 == ImplicitConversionSequence::BadConversion) {
2620 Candidate.Viable = false;
2621 break;
2622 }
2623 } else {
2624 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2625 // argument for which there is no corresponding parameter is
2626 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002627 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002628 = ImplicitConversionSequence::EllipsisConversion;
2629 }
2630 }
2631}
2632
Mike Stump87c57ac2009-05-16 07:39:55 +00002633// FIXME: This will eventually be removed, once we've migrated all of the
2634// operator overloading logic over to the scheme used by binary operators, which
2635// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002636void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002637 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002638 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002639 OverloadCandidateSet& CandidateSet,
2640 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002641
2642 FunctionSet Functions;
2643
2644 QualType T1 = Args[0]->getType();
2645 QualType T2;
2646 if (NumArgs > 1)
2647 T2 = Args[1]->getType();
2648
2649 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002650 if (S)
2651 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002652 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2653 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2654 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2655 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2656}
2657
2658/// \brief Add overload candidates for overloaded operators that are
2659/// member functions.
2660///
2661/// Add the overloaded operator candidates that are member functions
2662/// for the operator Op that was used in an operator expression such
2663/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2664/// CandidateSet will store the added overload candidates. (C++
2665/// [over.match.oper]).
2666void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2667 SourceLocation OpLoc,
2668 Expr **Args, unsigned NumArgs,
2669 OverloadCandidateSet& CandidateSet,
2670 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002671 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2672
2673 // C++ [over.match.oper]p3:
2674 // For a unary operator @ with an operand of a type whose
2675 // cv-unqualified version is T1, and for a binary operator @ with
2676 // a left operand of a type whose cv-unqualified version is T1 and
2677 // a right operand of a type whose cv-unqualified version is T2,
2678 // three sets of candidate functions, designated member
2679 // candidates, non-member candidates and built-in candidates, are
2680 // constructed as follows:
2681 QualType T1 = Args[0]->getType();
2682 QualType T2;
2683 if (NumArgs > 1)
2684 T2 = Args[1]->getType();
2685
2686 // -- If T1 is a class type, the set of member candidates is the
2687 // result of the qualified lookup of T1::operator@
2688 // (13.3.1.1.1); otherwise, the set of member candidates is
2689 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002690 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002691 // Complete the type if it can be completed. Otherwise, we're done.
2692 if (RequireCompleteType(OpLoc, T1, PartialDiagnostic(0)))
2693 return;
Mike Stump11289f42009-09-09 15:08:12 +00002694
2695 LookupResult Operators = LookupQualifiedName(T1Rec->getDecl(), OpName,
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002696 LookupOrdinaryName, false);
Mike Stump11289f42009-09-09 15:08:12 +00002697 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002698 OperEnd = Operators.end();
2699 Oper != OperEnd;
2700 ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00002701 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
Douglas Gregor55297ac2008-12-23 00:26:44 +00002702 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor436424c2008-11-18 23:14:02 +00002703 /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002704 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002705}
2706
Douglas Gregora11693b2008-11-12 17:17:38 +00002707/// AddBuiltinCandidate - Add a candidate for a built-in
2708/// operator. ResultTy and ParamTys are the result and parameter types
2709/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002710/// arguments being passed to the candidate. IsAssignmentOperator
2711/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002712/// operator. NumContextualBoolArguments is the number of arguments
2713/// (at the beginning of the argument list) that will be contextually
2714/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002715void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002716 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002717 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002718 bool IsAssignmentOperator,
2719 unsigned NumContextualBoolArguments) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002720 // Add this candidate
2721 CandidateSet.push_back(OverloadCandidate());
2722 OverloadCandidate& Candidate = CandidateSet.back();
2723 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002724 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002725 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002726 Candidate.BuiltinTypes.ResultTy = ResultTy;
2727 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2728 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2729
2730 // Determine the implicit conversion sequences for each of the
2731 // arguments.
2732 Candidate.Viable = true;
2733 Candidate.Conversions.resize(NumArgs);
2734 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002735 // C++ [over.match.oper]p4:
2736 // For the built-in assignment operators, conversions of the
2737 // left operand are restricted as follows:
2738 // -- no temporaries are introduced to hold the left operand, and
2739 // -- no user-defined conversions are applied to the left
2740 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002741 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002742 //
2743 // We block these conversions by turning off user-defined
2744 // conversions, since that is the only way that initialization of
2745 // a reference to a non-class type can occur from something that
2746 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002747 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002748 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002749 "Contextual conversion to bool requires bool type");
2750 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2751 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002752 Candidate.Conversions[ArgIdx]
2753 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002754 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002755 /*ForceRValue=*/false,
2756 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002757 }
Mike Stump11289f42009-09-09 15:08:12 +00002758 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002759 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002760 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002761 break;
2762 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002763 }
2764}
2765
2766/// BuiltinCandidateTypeSet - A set of types that will be used for the
2767/// candidate operator functions for built-in operators (C++
2768/// [over.built]). The types are separated into pointer types and
2769/// enumeration types.
2770class BuiltinCandidateTypeSet {
2771 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002772 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002773
2774 /// PointerTypes - The set of pointer types that will be used in the
2775 /// built-in candidates.
2776 TypeSet PointerTypes;
2777
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002778 /// MemberPointerTypes - The set of member pointer types that will be
2779 /// used in the built-in candidates.
2780 TypeSet MemberPointerTypes;
2781
Douglas Gregora11693b2008-11-12 17:17:38 +00002782 /// EnumerationTypes - The set of enumeration types that will be
2783 /// used in the built-in candidates.
2784 TypeSet EnumerationTypes;
2785
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002786 /// Sema - The semantic analysis instance where we are building the
2787 /// candidate type set.
2788 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002789
Douglas Gregora11693b2008-11-12 17:17:38 +00002790 /// Context - The AST context in which we will build the type sets.
2791 ASTContext &Context;
2792
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002793 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2794 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002795
2796public:
2797 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002798 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002799
Mike Stump11289f42009-09-09 15:08:12 +00002800 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002801 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002802
Douglas Gregor5fb53972009-01-14 15:45:31 +00002803 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2804 bool AllowExplicitConversions);
Douglas Gregora11693b2008-11-12 17:17:38 +00002805
2806 /// pointer_begin - First pointer type found;
2807 iterator pointer_begin() { return PointerTypes.begin(); }
2808
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002809 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002810 iterator pointer_end() { return PointerTypes.end(); }
2811
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002812 /// member_pointer_begin - First member pointer type found;
2813 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2814
2815 /// member_pointer_end - Past the last member pointer type found;
2816 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2817
Douglas Gregora11693b2008-11-12 17:17:38 +00002818 /// enumeration_begin - First enumeration type found;
2819 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2820
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002821 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002822 iterator enumeration_end() { return EnumerationTypes.end(); }
2823};
2824
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002825/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00002826/// the set of pointer types along with any more-qualified variants of
2827/// that type. For example, if @p Ty is "int const *", this routine
2828/// will add "int const *", "int const volatile *", "int const
2829/// restrict *", and "int const volatile restrict *" to the set of
2830/// pointer types. Returns true if the add of @p Ty itself succeeded,
2831/// false otherwise.
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002832bool
2833BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002834 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002835 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002836 return false;
2837
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002838 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002839 QualType PointeeTy = PointerTy->getPointeeType();
2840 // FIXME: Optimize this so that we don't keep trying to add the same types.
2841
Mike Stump87c57ac2009-05-16 07:39:55 +00002842 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2843 // pointer conversions that don't cast away constness?
Douglas Gregora11693b2008-11-12 17:17:38 +00002844 if (!PointeeTy.isConstQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002845 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002846 (Context.getPointerType(PointeeTy.withConst()));
2847 if (!PointeeTy.isVolatileQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002848 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002849 (Context.getPointerType(PointeeTy.withVolatile()));
2850 if (!PointeeTy.isRestrictQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002851 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002852 (Context.getPointerType(PointeeTy.withRestrict()));
2853 }
2854
2855 return true;
2856}
2857
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002858/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2859/// to the set of pointer types along with any more-qualified variants of
2860/// that type. For example, if @p Ty is "int const *", this routine
2861/// will add "int const *", "int const volatile *", "int const
2862/// restrict *", and "int const volatile restrict *" to the set of
2863/// pointer types. Returns true if the add of @p Ty itself succeeded,
2864/// false otherwise.
2865bool
2866BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2867 QualType Ty) {
2868 // Insert this type.
2869 if (!MemberPointerTypes.insert(Ty))
2870 return false;
2871
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002872 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002873 QualType PointeeTy = PointerTy->getPointeeType();
2874 const Type *ClassTy = PointerTy->getClass();
2875 // FIXME: Optimize this so that we don't keep trying to add the same types.
2876
2877 if (!PointeeTy.isConstQualified())
2878 AddMemberPointerWithMoreQualifiedTypeVariants
2879 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2880 if (!PointeeTy.isVolatileQualified())
2881 AddMemberPointerWithMoreQualifiedTypeVariants
2882 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2883 if (!PointeeTy.isRestrictQualified())
2884 AddMemberPointerWithMoreQualifiedTypeVariants
2885 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2886 }
2887
2888 return true;
2889}
2890
Douglas Gregora11693b2008-11-12 17:17:38 +00002891/// AddTypesConvertedFrom - Add each of the types to which the type @p
2892/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002893/// primarily interested in pointer types and enumeration types. We also
2894/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002895/// AllowUserConversions is true if we should look at the conversion
2896/// functions of a class type, and AllowExplicitConversions if we
2897/// should also include the explicit conversion functions of a class
2898/// type.
Mike Stump11289f42009-09-09 15:08:12 +00002899void
Douglas Gregor5fb53972009-01-14 15:45:31 +00002900BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2901 bool AllowUserConversions,
2902 bool AllowExplicitConversions) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002903 // Only deal with canonical types.
2904 Ty = Context.getCanonicalType(Ty);
2905
2906 // Look through reference types; they aren't part of the type of an
2907 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002908 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00002909 Ty = RefTy->getPointeeType();
2910
2911 // We don't care about qualifiers on the type.
2912 Ty = Ty.getUnqualifiedType();
2913
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002914 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002915 QualType PointeeTy = PointerTy->getPointeeType();
2916
2917 // Insert our type, and its more-qualified variants, into the set
2918 // of types.
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002919 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002920 return;
2921
2922 // Add 'cv void*' to our set of types.
2923 if (!Ty->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002924 QualType QualVoid
Douglas Gregora11693b2008-11-12 17:17:38 +00002925 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002926 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregora11693b2008-11-12 17:17:38 +00002927 }
2928
2929 // If this is a pointer to a class type, add pointers to its bases
2930 // (with the same level of cv-qualification as the original
2931 // derived class, of course).
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002932 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002933 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2934 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2935 Base != ClassDecl->bases_end(); ++Base) {
2936 QualType BaseTy = Context.getCanonicalType(Base->getType());
2937 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2938
2939 // Add the pointer type, recursively, so that we get all of
2940 // the indirect base classes, too.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002941 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00002942 }
2943 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002944 } else if (Ty->isMemberPointerType()) {
2945 // Member pointers are far easier, since the pointee can't be converted.
2946 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2947 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00002948 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00002949 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002950 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002951 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002952 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2953 // No conversion functions in incomplete types.
2954 return;
2955 }
Mike Stump11289f42009-09-09 15:08:12 +00002956
Douglas Gregora11693b2008-11-12 17:17:38 +00002957 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2958 // FIXME: Visit conversion functions in the base classes, too.
Mike Stump11289f42009-09-09 15:08:12 +00002959 OverloadedFunctionDecl *Conversions
Douglas Gregora11693b2008-11-12 17:17:38 +00002960 = ClassDecl->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00002961 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregora11693b2008-11-12 17:17:38 +00002962 = Conversions->function_begin();
2963 Func != Conversions->function_end(); ++Func) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002964 CXXConversionDecl *Conv;
2965 FunctionTemplateDecl *ConvTemplate;
2966 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2967
Mike Stump11289f42009-09-09 15:08:12 +00002968 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00002969 // about which builtin types we can convert to.
2970 if (ConvTemplate)
2971 continue;
2972
Douglas Gregor5fb53972009-01-14 15:45:31 +00002973 if (AllowExplicitConversions || !Conv->isExplicit())
2974 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00002975 }
2976 }
2977 }
2978}
2979
Douglas Gregor84605ae2009-08-24 13:43:27 +00002980/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2981/// the volatile- and non-volatile-qualified assignment operators for the
2982/// given type to the candidate set.
2983static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2984 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00002985 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00002986 unsigned NumArgs,
2987 OverloadCandidateSet &CandidateSet) {
2988 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002989
Douglas Gregor84605ae2009-08-24 13:43:27 +00002990 // T& operator=(T&, T)
2991 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2992 ParamTypes[1] = T;
2993 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2994 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002995
Douglas Gregor84605ae2009-08-24 13:43:27 +00002996 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2997 // volatile T& operator=(volatile T&, T)
2998 ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
2999 ParamTypes[1] = T;
3000 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003001 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003002 }
3003}
Mike Stump11289f42009-09-09 15:08:12 +00003004
Douglas Gregord08452f2008-11-19 15:42:04 +00003005/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3006/// operator overloads to the candidate set (C++ [over.built]), based
3007/// on the operator @p Op and the arguments given. For example, if the
3008/// operator is a binary '+', this routine might add "int
3009/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003010void
Mike Stump11289f42009-09-09 15:08:12 +00003011Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregord08452f2008-11-19 15:42:04 +00003012 Expr **Args, unsigned NumArgs,
3013 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003014 // The set of "promoted arithmetic types", which are the arithmetic
3015 // types are that preserved by promotion (C++ [over.built]p2). Note
3016 // that the first few of these types are the promoted integral
3017 // types; these types need to be first.
3018 // FIXME: What about complex?
3019 const unsigned FirstIntegralType = 0;
3020 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003021 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003022 LastPromotedIntegralType = 13;
3023 const unsigned FirstPromotedArithmeticType = 7,
3024 LastPromotedArithmeticType = 16;
3025 const unsigned NumArithmeticTypes = 16;
3026 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003027 Context.BoolTy, Context.CharTy, Context.WCharTy,
3028// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003029 Context.SignedCharTy, Context.ShortTy,
3030 Context.UnsignedCharTy, Context.UnsignedShortTy,
3031 Context.IntTy, Context.LongTy, Context.LongLongTy,
3032 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3033 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3034 };
3035
3036 // Find all of the types that the arguments can convert to, but only
3037 // if the operator we're looking at has built-in operator candidates
3038 // that make use of these types.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003039 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003040 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3041 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003042 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003043 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003044 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003045 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003046 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003047 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3048 true,
3049 (Op == OO_Exclaim ||
3050 Op == OO_AmpAmp ||
3051 Op == OO_PipePipe));
Douglas Gregora11693b2008-11-12 17:17:38 +00003052 }
3053
3054 bool isComparison = false;
3055 switch (Op) {
3056 case OO_None:
3057 case NUM_OVERLOADED_OPERATORS:
3058 assert(false && "Expected an overloaded operator");
3059 break;
3060
Douglas Gregord08452f2008-11-19 15:42:04 +00003061 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003062 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003063 goto UnaryStar;
3064 else
3065 goto BinaryStar;
3066 break;
3067
3068 case OO_Plus: // '+' is either unary or binary
3069 if (NumArgs == 1)
3070 goto UnaryPlus;
3071 else
3072 goto BinaryPlus;
3073 break;
3074
3075 case OO_Minus: // '-' is either unary or binary
3076 if (NumArgs == 1)
3077 goto UnaryMinus;
3078 else
3079 goto BinaryMinus;
3080 break;
3081
3082 case OO_Amp: // '&' is either unary or binary
3083 if (NumArgs == 1)
3084 goto UnaryAmp;
3085 else
3086 goto BinaryAmp;
3087
3088 case OO_PlusPlus:
3089 case OO_MinusMinus:
3090 // C++ [over.built]p3:
3091 //
3092 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3093 // is either volatile or empty, there exist candidate operator
3094 // functions of the form
3095 //
3096 // VQ T& operator++(VQ T&);
3097 // T operator++(VQ T&, int);
3098 //
3099 // C++ [over.built]p4:
3100 //
3101 // For every pair (T, VQ), where T is an arithmetic type other
3102 // than bool, and VQ is either volatile or empty, there exist
3103 // candidate operator functions of the form
3104 //
3105 // VQ T& operator--(VQ T&);
3106 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003107 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003108 Arith < NumArithmeticTypes; ++Arith) {
3109 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003110 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003111 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003112
3113 // Non-volatile version.
3114 if (NumArgs == 1)
3115 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3116 else
3117 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3118
3119 // Volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003120 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregord08452f2008-11-19 15:42:04 +00003121 if (NumArgs == 1)
3122 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3123 else
3124 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3125 }
3126
3127 // C++ [over.built]p5:
3128 //
3129 // For every pair (T, VQ), where T is a cv-qualified or
3130 // cv-unqualified object type, and VQ is either volatile or
3131 // empty, there exist candidate operator functions of the form
3132 //
3133 // T*VQ& operator++(T*VQ&);
3134 // T*VQ& operator--(T*VQ&);
3135 // T* operator++(T*VQ&, int);
3136 // T* operator--(T*VQ&, int);
3137 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3138 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3139 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003140 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003141 continue;
3142
Mike Stump11289f42009-09-09 15:08:12 +00003143 QualType ParamTypes[2] = {
3144 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003145 };
Mike Stump11289f42009-09-09 15:08:12 +00003146
Douglas Gregord08452f2008-11-19 15:42:04 +00003147 // Without volatile
3148 if (NumArgs == 1)
3149 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3150 else
3151 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3152
3153 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3154 // With volatile
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003155 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregord08452f2008-11-19 15:42:04 +00003156 if (NumArgs == 1)
3157 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3158 else
3159 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3160 }
3161 }
3162 break;
3163
3164 UnaryStar:
3165 // C++ [over.built]p6:
3166 // For every cv-qualified or cv-unqualified object type T, there
3167 // exist candidate operator functions of the form
3168 //
3169 // T& operator*(T*);
3170 //
3171 // C++ [over.built]p7:
3172 // For every function type T, there exist candidate operator
3173 // functions of the form
3174 // T& operator*(T*);
3175 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3176 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3177 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003178 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003179 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003180 &ParamTy, Args, 1, CandidateSet);
3181 }
3182 break;
3183
3184 UnaryPlus:
3185 // C++ [over.built]p8:
3186 // For every type T, there exist candidate operator functions of
3187 // the form
3188 //
3189 // T* operator+(T*);
3190 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3191 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3192 QualType ParamTy = *Ptr;
3193 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3194 }
Mike Stump11289f42009-09-09 15:08:12 +00003195
Douglas Gregord08452f2008-11-19 15:42:04 +00003196 // Fall through
3197
3198 UnaryMinus:
3199 // C++ [over.built]p9:
3200 // For every promoted arithmetic type T, there exist candidate
3201 // operator functions of the form
3202 //
3203 // T operator+(T);
3204 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003205 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003206 Arith < LastPromotedArithmeticType; ++Arith) {
3207 QualType ArithTy = ArithmeticTypes[Arith];
3208 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3209 }
3210 break;
3211
3212 case OO_Tilde:
3213 // C++ [over.built]p10:
3214 // For every promoted integral type T, there exist candidate
3215 // operator functions of the form
3216 //
3217 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003218 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003219 Int < LastPromotedIntegralType; ++Int) {
3220 QualType IntTy = ArithmeticTypes[Int];
3221 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3222 }
3223 break;
3224
Douglas Gregora11693b2008-11-12 17:17:38 +00003225 case OO_New:
3226 case OO_Delete:
3227 case OO_Array_New:
3228 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003229 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003230 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003231 break;
3232
3233 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003234 UnaryAmp:
3235 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003236 // C++ [over.match.oper]p3:
3237 // -- For the operator ',', the unary operator '&', or the
3238 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003239 break;
3240
Douglas Gregor84605ae2009-08-24 13:43:27 +00003241 case OO_EqualEqual:
3242 case OO_ExclaimEqual:
3243 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003244 // For every pointer to member type T, there exist candidate operator
3245 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003246 //
3247 // bool operator==(T,T);
3248 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003249 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003250 MemPtr = CandidateTypes.member_pointer_begin(),
3251 MemPtrEnd = CandidateTypes.member_pointer_end();
3252 MemPtr != MemPtrEnd;
3253 ++MemPtr) {
3254 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3255 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3256 }
Mike Stump11289f42009-09-09 15:08:12 +00003257
Douglas Gregor84605ae2009-08-24 13:43:27 +00003258 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003259
Douglas Gregora11693b2008-11-12 17:17:38 +00003260 case OO_Less:
3261 case OO_Greater:
3262 case OO_LessEqual:
3263 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003264 // C++ [over.built]p15:
3265 //
3266 // For every pointer or enumeration type T, there exist
3267 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003268 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003269 // bool operator<(T, T);
3270 // bool operator>(T, T);
3271 // bool operator<=(T, T);
3272 // bool operator>=(T, T);
3273 // bool operator==(T, T);
3274 // bool operator!=(T, T);
3275 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3276 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3277 QualType ParamTypes[2] = { *Ptr, *Ptr };
3278 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3279 }
Mike Stump11289f42009-09-09 15:08:12 +00003280 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003281 = CandidateTypes.enumeration_begin();
3282 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3283 QualType ParamTypes[2] = { *Enum, *Enum };
3284 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3285 }
3286
3287 // Fall through.
3288 isComparison = true;
3289
Douglas Gregord08452f2008-11-19 15:42:04 +00003290 BinaryPlus:
3291 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003292 if (!isComparison) {
3293 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3294
3295 // C++ [over.built]p13:
3296 //
3297 // For every cv-qualified or cv-unqualified object type T
3298 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003299 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003300 // T* operator+(T*, ptrdiff_t);
3301 // T& operator[](T*, ptrdiff_t); [BELOW]
3302 // T* operator-(T*, ptrdiff_t);
3303 // T* operator+(ptrdiff_t, T*);
3304 // T& operator[](ptrdiff_t, T*); [BELOW]
3305 //
3306 // C++ [over.built]p14:
3307 //
3308 // For every T, where T is a pointer to object type, there
3309 // exist candidate operator functions of the form
3310 //
3311 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003312 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003313 = CandidateTypes.pointer_begin();
3314 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3315 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3316
3317 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3318 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3319
3320 if (Op == OO_Plus) {
3321 // T* operator+(ptrdiff_t, T*);
3322 ParamTypes[0] = ParamTypes[1];
3323 ParamTypes[1] = *Ptr;
3324 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3325 } else {
3326 // ptrdiff_t operator-(T, T);
3327 ParamTypes[1] = *Ptr;
3328 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3329 Args, 2, CandidateSet);
3330 }
3331 }
3332 }
3333 // Fall through
3334
Douglas Gregora11693b2008-11-12 17:17:38 +00003335 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003336 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003337 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003338 // C++ [over.built]p12:
3339 //
3340 // For every pair of promoted arithmetic types L and R, there
3341 // exist candidate operator functions of the form
3342 //
3343 // LR operator*(L, R);
3344 // LR operator/(L, R);
3345 // LR operator+(L, R);
3346 // LR operator-(L, R);
3347 // bool operator<(L, R);
3348 // bool operator>(L, R);
3349 // bool operator<=(L, R);
3350 // bool operator>=(L, R);
3351 // bool operator==(L, R);
3352 // bool operator!=(L, R);
3353 //
3354 // where LR is the result of the usual arithmetic conversions
3355 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003356 //
3357 // C++ [over.built]p24:
3358 //
3359 // For every pair of promoted arithmetic types L and R, there exist
3360 // candidate operator functions of the form
3361 //
3362 // LR operator?(bool, L, R);
3363 //
3364 // where LR is the result of the usual arithmetic conversions
3365 // between types L and R.
3366 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003367 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003368 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003369 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003370 Right < LastPromotedArithmeticType; ++Right) {
3371 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003372 QualType Result
3373 = isComparison
3374 ? Context.BoolTy
3375 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003376 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3377 }
3378 }
3379 break;
3380
3381 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003382 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003383 case OO_Caret:
3384 case OO_Pipe:
3385 case OO_LessLess:
3386 case OO_GreaterGreater:
3387 // C++ [over.built]p17:
3388 //
3389 // For every pair of promoted integral types L and R, there
3390 // exist candidate operator functions of the form
3391 //
3392 // LR operator%(L, R);
3393 // LR operator&(L, R);
3394 // LR operator^(L, R);
3395 // LR operator|(L, R);
3396 // L operator<<(L, R);
3397 // L operator>>(L, R);
3398 //
3399 // where LR is the result of the usual arithmetic conversions
3400 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003401 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003402 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003403 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003404 Right < LastPromotedIntegralType; ++Right) {
3405 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3406 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3407 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003408 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003409 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3410 }
3411 }
3412 break;
3413
3414 case OO_Equal:
3415 // C++ [over.built]p20:
3416 //
3417 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003418 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003419 // empty, there exist candidate operator functions of the form
3420 //
3421 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003422 for (BuiltinCandidateTypeSet::iterator
3423 Enum = CandidateTypes.enumeration_begin(),
3424 EnumEnd = CandidateTypes.enumeration_end();
3425 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003426 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003427 CandidateSet);
3428 for (BuiltinCandidateTypeSet::iterator
3429 MemPtr = CandidateTypes.member_pointer_begin(),
3430 MemPtrEnd = CandidateTypes.member_pointer_end();
3431 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003432 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003433 CandidateSet);
3434 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003435
3436 case OO_PlusEqual:
3437 case OO_MinusEqual:
3438 // C++ [over.built]p19:
3439 //
3440 // For every pair (T, VQ), where T is any type and VQ is either
3441 // volatile or empty, there exist candidate operator functions
3442 // of the form
3443 //
3444 // T*VQ& operator=(T*VQ&, T*);
3445 //
3446 // C++ [over.built]p21:
3447 //
3448 // For every pair (T, VQ), where T is a cv-qualified or
3449 // cv-unqualified object type and VQ is either volatile or
3450 // empty, there exist candidate operator functions of the form
3451 //
3452 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3453 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3454 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3455 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3456 QualType ParamTypes[2];
3457 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3458
3459 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003460 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003461 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3462 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003463
Douglas Gregord08452f2008-11-19 15:42:04 +00003464 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3465 // volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003466 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorc5e61072009-01-13 00:52:54 +00003467 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3468 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003469 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003470 }
3471 // Fall through.
3472
3473 case OO_StarEqual:
3474 case OO_SlashEqual:
3475 // C++ [over.built]p18:
3476 //
3477 // For every triple (L, VQ, R), where L is an arithmetic type,
3478 // VQ is either volatile or empty, and R is a promoted
3479 // arithmetic type, there exist candidate operator functions of
3480 // the form
3481 //
3482 // VQ L& operator=(VQ L&, R);
3483 // VQ L& operator*=(VQ L&, R);
3484 // VQ L& operator/=(VQ L&, R);
3485 // VQ L& operator+=(VQ L&, R);
3486 // VQ L& operator-=(VQ L&, R);
3487 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003488 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003489 Right < LastPromotedArithmeticType; ++Right) {
3490 QualType ParamTypes[2];
3491 ParamTypes[1] = ArithmeticTypes[Right];
3492
3493 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003494 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003495 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3496 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003497
3498 // Add this built-in operator as a candidate (VQ is 'volatile').
3499 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003500 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003501 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3502 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003503 }
3504 }
3505 break;
3506
3507 case OO_PercentEqual:
3508 case OO_LessLessEqual:
3509 case OO_GreaterGreaterEqual:
3510 case OO_AmpEqual:
3511 case OO_CaretEqual:
3512 case OO_PipeEqual:
3513 // C++ [over.built]p22:
3514 //
3515 // For every triple (L, VQ, R), where L is an integral type, VQ
3516 // is either volatile or empty, and R is a promoted integral
3517 // type, there exist candidate operator functions of the form
3518 //
3519 // VQ L& operator%=(VQ L&, R);
3520 // VQ L& operator<<=(VQ L&, R);
3521 // VQ L& operator>>=(VQ L&, R);
3522 // VQ L& operator&=(VQ L&, R);
3523 // VQ L& operator^=(VQ L&, R);
3524 // VQ L& operator|=(VQ L&, R);
3525 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003526 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003527 Right < LastPromotedIntegralType; ++Right) {
3528 QualType ParamTypes[2];
3529 ParamTypes[1] = ArithmeticTypes[Right];
3530
3531 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003532 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003533 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3534
3535 // Add this built-in operator as a candidate (VQ is 'volatile').
3536 ParamTypes[0] = ArithmeticTypes[Left];
3537 ParamTypes[0].addVolatile();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003538 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003539 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3540 }
3541 }
3542 break;
3543
Douglas Gregord08452f2008-11-19 15:42:04 +00003544 case OO_Exclaim: {
3545 // C++ [over.operator]p23:
3546 //
3547 // There also exist candidate operator functions of the form
3548 //
Mike Stump11289f42009-09-09 15:08:12 +00003549 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003550 // bool operator&&(bool, bool); [BELOW]
3551 // bool operator||(bool, bool); [BELOW]
3552 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003553 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3554 /*IsAssignmentOperator=*/false,
3555 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003556 break;
3557 }
3558
Douglas Gregora11693b2008-11-12 17:17:38 +00003559 case OO_AmpAmp:
3560 case OO_PipePipe: {
3561 // C++ [over.operator]p23:
3562 //
3563 // There also exist candidate operator functions of the form
3564 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003565 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003566 // bool operator&&(bool, bool);
3567 // bool operator||(bool, bool);
3568 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003569 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3570 /*IsAssignmentOperator=*/false,
3571 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003572 break;
3573 }
3574
3575 case OO_Subscript:
3576 // C++ [over.built]p13:
3577 //
3578 // For every cv-qualified or cv-unqualified object type T there
3579 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003580 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003581 // T* operator+(T*, ptrdiff_t); [ABOVE]
3582 // T& operator[](T*, ptrdiff_t);
3583 // T* operator-(T*, ptrdiff_t); [ABOVE]
3584 // T* operator+(ptrdiff_t, T*); [ABOVE]
3585 // T& operator[](ptrdiff_t, T*);
3586 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3587 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3588 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003589 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003590 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003591
3592 // T& operator[](T*, ptrdiff_t)
3593 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3594
3595 // T& operator[](ptrdiff_t, T*);
3596 ParamTypes[0] = ParamTypes[1];
3597 ParamTypes[1] = *Ptr;
3598 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3599 }
3600 break;
3601
3602 case OO_ArrowStar:
3603 // FIXME: No support for pointer-to-members yet.
3604 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003605
3606 case OO_Conditional:
3607 // Note that we don't consider the first argument, since it has been
3608 // contextually converted to bool long ago. The candidates below are
3609 // therefore added as binary.
3610 //
3611 // C++ [over.built]p24:
3612 // For every type T, where T is a pointer or pointer-to-member type,
3613 // there exist candidate operator functions of the form
3614 //
3615 // T operator?(bool, T, T);
3616 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003617 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3618 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3619 QualType ParamTypes[2] = { *Ptr, *Ptr };
3620 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3621 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003622 for (BuiltinCandidateTypeSet::iterator Ptr =
3623 CandidateTypes.member_pointer_begin(),
3624 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3625 QualType ParamTypes[2] = { *Ptr, *Ptr };
3626 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3627 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003628 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003629 }
3630}
3631
Douglas Gregore254f902009-02-04 00:32:51 +00003632/// \brief Add function candidates found via argument-dependent lookup
3633/// to the set of overloading candidates.
3634///
3635/// This routine performs argument-dependent name lookup based on the
3636/// given function name (which may also be an operator name) and adds
3637/// all of the overload candidates found by ADL to the overload
3638/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003639void
Douglas Gregore254f902009-02-04 00:32:51 +00003640Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3641 Expr **Args, unsigned NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003642 bool HasExplicitTemplateArgs,
3643 const TemplateArgument *ExplicitTemplateArgs,
3644 unsigned NumExplicitTemplateArgs,
3645 OverloadCandidateSet& CandidateSet,
3646 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003647 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003648
Douglas Gregorcabea402009-09-22 15:41:20 +00003649 // FIXME: Should we be trafficking in canonical function decls throughout?
3650
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003651 // Record all of the function candidates that we've already
3652 // added to the overload set, so that we don't add those same
3653 // candidates a second time.
3654 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3655 CandEnd = CandidateSet.end();
3656 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003657 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003658 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003659 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3660 Functions.insert(FunTmpl);
3661 }
Douglas Gregore254f902009-02-04 00:32:51 +00003662
Douglas Gregorcabea402009-09-22 15:41:20 +00003663 // FIXME: Pass in the explicit template arguments?
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003664 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003665
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003666 // Erase all of the candidates we already knew about.
3667 // FIXME: This is suboptimal. Is there a better way?
3668 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3669 CandEnd = CandidateSet.end();
3670 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003671 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003672 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003673 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3674 Functions.erase(FunTmpl);
3675 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003676
3677 // For each of the ADL candidates we found, add it to the overload
3678 // set.
3679 for (FunctionSet::iterator Func = Functions.begin(),
3680 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00003681 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003682 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3683 if (HasExplicitTemplateArgs)
3684 continue;
3685
3686 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3687 false, false, PartialOverloading);
3688 } else
Mike Stump11289f42009-09-09 15:08:12 +00003689 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00003690 HasExplicitTemplateArgs,
3691 ExplicitTemplateArgs,
3692 NumExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003693 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00003694 }
Douglas Gregore254f902009-02-04 00:32:51 +00003695}
3696
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003697/// isBetterOverloadCandidate - Determines whether the first overload
3698/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00003699bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003700Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00003701 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003702 // Define viable functions to be better candidates than non-viable
3703 // functions.
3704 if (!Cand2.Viable)
3705 return Cand1.Viable;
3706 else if (!Cand1.Viable)
3707 return false;
3708
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003709 // C++ [over.match.best]p1:
3710 //
3711 // -- if F is a static member function, ICS1(F) is defined such
3712 // that ICS1(F) is neither better nor worse than ICS1(G) for
3713 // any function G, and, symmetrically, ICS1(G) is neither
3714 // better nor worse than ICS1(F).
3715 unsigned StartArg = 0;
3716 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3717 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003718
Douglas Gregord3cb3562009-07-07 23:38:56 +00003719 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00003720 // A viable function F1 is defined to be a better function than another
3721 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00003722 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003723 unsigned NumArgs = Cand1.Conversions.size();
3724 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3725 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003726 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003727 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3728 Cand2.Conversions[ArgIdx])) {
3729 case ImplicitConversionSequence::Better:
3730 // Cand1 has a better conversion sequence.
3731 HasBetterConversion = true;
3732 break;
3733
3734 case ImplicitConversionSequence::Worse:
3735 // Cand1 can't be better than Cand2.
3736 return false;
3737
3738 case ImplicitConversionSequence::Indistinguishable:
3739 // Do nothing.
3740 break;
3741 }
3742 }
3743
Mike Stump11289f42009-09-09 15:08:12 +00003744 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00003745 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003746 if (HasBetterConversion)
3747 return true;
3748
Mike Stump11289f42009-09-09 15:08:12 +00003749 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00003750 // specialization, or, if not that,
3751 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3752 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3753 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003754
3755 // -- F1 and F2 are function template specializations, and the function
3756 // template for F1 is more specialized than the template for F2
3757 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00003758 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00003759 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3760 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00003761 if (FunctionTemplateDecl *BetterTemplate
3762 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3763 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00003764 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
3765 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00003766 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003767
Douglas Gregora1f013e2008-11-07 22:36:19 +00003768 // -- the context is an initialization by user-defined conversion
3769 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3770 // from the return type of F1 to the destination type (i.e.,
3771 // the type of the entity being initialized) is a better
3772 // conversion sequence than the standard conversion sequence
3773 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00003774 if (Cand1.Function && Cand2.Function &&
3775 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003776 isa<CXXConversionDecl>(Cand2.Function)) {
3777 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3778 Cand2.FinalConversion)) {
3779 case ImplicitConversionSequence::Better:
3780 // Cand1 has a better conversion sequence.
3781 return true;
3782
3783 case ImplicitConversionSequence::Worse:
3784 // Cand1 can't be better than Cand2.
3785 return false;
3786
3787 case ImplicitConversionSequence::Indistinguishable:
3788 // Do nothing
3789 break;
3790 }
3791 }
3792
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003793 return false;
3794}
3795
Mike Stump11289f42009-09-09 15:08:12 +00003796/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003797/// within an overload candidate set.
3798///
3799/// \param CandidateSet the set of candidate functions.
3800///
3801/// \param Loc the location of the function name (or operator symbol) for
3802/// which overload resolution occurs.
3803///
Mike Stump11289f42009-09-09 15:08:12 +00003804/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003805/// function, Best points to the candidate function found.
3806///
3807/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00003808Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003809Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003810 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003811 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003812 // Find the best viable function.
3813 Best = CandidateSet.end();
3814 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3815 Cand != CandidateSet.end(); ++Cand) {
3816 if (Cand->Viable) {
3817 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3818 Best = Cand;
3819 }
3820 }
3821
3822 // If we didn't find any viable functions, abort.
3823 if (Best == CandidateSet.end())
3824 return OR_No_Viable_Function;
3825
3826 // Make sure that this function is better than every other viable
3827 // function. If not, we have an ambiguity.
3828 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3829 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00003830 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003831 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00003832 !isBetterOverloadCandidate(*Best, *Cand)) {
3833 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003834 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003835 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003836 }
Mike Stump11289f42009-09-09 15:08:12 +00003837
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003838 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003839 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00003840 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003841 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003842 return OR_Deleted;
3843
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003844 // C++ [basic.def.odr]p2:
3845 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00003846 // when referred to from a potentially-evaluated expression. [Note: this
3847 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003848 // (clause 13), user-defined conversions (12.3.2), allocation function for
3849 // placement new (5.3.4), as well as non-default initialization (8.5).
3850 if (Best->Function)
3851 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003852 return OR_Success;
3853}
3854
3855/// PrintOverloadCandidates - When overload resolution fails, prints
3856/// diagnostic messages containing the candidates in the candidate
3857/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00003858void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003859Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003860 bool OnlyViable) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003861 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3862 LastCand = CandidateSet.end();
3863 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003864 if (Cand->Viable || !OnlyViable) {
3865 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003866 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003867 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003868 // Deleted or "unavailable" function.
3869 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3870 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00003871 } else if (FunctionTemplateDecl *FunTmpl
3872 = Cand->Function->getPrimaryTemplate()) {
3873 // Function template specialization
3874 // FIXME: Give a better reason!
3875 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
3876 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
3877 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00003878 } else {
3879 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00003880 bool errReported = false;
3881 if (!Cand->Viable && Cand->Conversions.size() > 0) {
3882 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
3883 const ImplicitConversionSequence &Conversion =
3884 Cand->Conversions[i];
3885 if ((Conversion.ConversionKind !=
3886 ImplicitConversionSequence::BadConversion) ||
3887 Conversion.ConversionFunctionSet.size() == 0)
3888 continue;
3889 Diag(Cand->Function->getLocation(),
3890 diag::err_ovl_candidate_not_viable) << (i+1);
3891 errReported = true;
3892 for (int j = Conversion.ConversionFunctionSet.size()-1;
3893 j >= 0; j--) {
3894 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
3895 Diag(Func->getLocation(), diag::err_ovl_candidate);
3896 }
3897 }
3898 }
3899 if (!errReported)
3900 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00003901 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00003902 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003903 // Desugar the type of the surrogate down to a function type,
3904 // retaining as many typedefs as possible while still showing
3905 // the function type (and, therefore, its parameter types).
3906 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003907 bool isLValueReference = false;
3908 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003909 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003910 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003911 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003912 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003913 isLValueReference = true;
3914 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003915 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003916 FnType = FnTypeRef->getPointeeType();
3917 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003918 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003919 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003920 FnType = FnTypePtr->getPointeeType();
3921 isPointer = true;
3922 }
3923 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00003924 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003925 // Reconstruct the pointer/reference as appropriate.
3926 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003927 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3928 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003929
Douglas Gregorab7897a2008-11-19 22:57:39 +00003930 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003931 << FnType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003932 } else {
3933 // FIXME: We need to get the identifier in here
Mike Stump87c57ac2009-05-16 07:39:55 +00003934 // FIXME: Do we want the error message to point at the operator?
3935 // (built-ins won't have a location)
Mike Stump11289f42009-09-09 15:08:12 +00003936 QualType FnType
Douglas Gregora11693b2008-11-12 17:17:38 +00003937 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3938 Cand->BuiltinTypes.ParamTypes,
3939 Cand->Conversions.size(),
3940 false, 0);
3941
Chris Lattner1e5665e2008-11-24 06:25:27 +00003942 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003943 }
3944 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003945 }
3946}
3947
Douglas Gregorcd695e52008-11-10 20:40:00 +00003948/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3949/// an overloaded function (C++ [over.over]), where @p From is an
3950/// expression with overloaded function type and @p ToType is the type
3951/// we're trying to resolve to. For example:
3952///
3953/// @code
3954/// int f(double);
3955/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00003956///
Douglas Gregorcd695e52008-11-10 20:40:00 +00003957/// int (*pfd)(double) = f; // selects f(double)
3958/// @endcode
3959///
3960/// This routine returns the resulting FunctionDecl if it could be
3961/// resolved, and NULL otherwise. When @p Complain is true, this
3962/// routine will emit diagnostics if there is an error.
3963FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003964Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003965 bool Complain) {
3966 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003967 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003968 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00003969 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003970 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00003971 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003972 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003973 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003974 FunctionType = MemTypePtr->getPointeeType();
3975 IsMember = true;
3976 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003977
3978 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00003979 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00003980 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00003981 return 0;
3982
3983 // Find the actual overloaded function declaration.
3984 OverloadedFunctionDecl *Ovl = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003985
Douglas Gregorcd695e52008-11-10 20:40:00 +00003986 // C++ [over.over]p1:
3987 // [...] [Note: any redundant set of parentheses surrounding the
3988 // overloaded function name is ignored (5.1). ]
3989 Expr *OvlExpr = From->IgnoreParens();
3990
3991 // C++ [over.over]p1:
3992 // [...] The overloaded function name can be preceded by the &
3993 // operator.
3994 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3995 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3996 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3997 }
3998
3999 // Try to dig out the overloaded function.
Douglas Gregor9b146582009-07-08 20:55:45 +00004000 FunctionTemplateDecl *FunctionTemplate = 0;
4001 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004002 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor9b146582009-07-08 20:55:45 +00004003 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
4004 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004005
Mike Stump11289f42009-09-09 15:08:12 +00004006 // If there's no overloaded function declaration or function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00004007 // we're done.
4008 if (!Ovl && !FunctionTemplate)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004009 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004010
Douglas Gregor9b146582009-07-08 20:55:45 +00004011 OverloadIterator Fun;
4012 if (Ovl)
4013 Fun = Ovl;
4014 else
4015 Fun = FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00004016
Douglas Gregorcd695e52008-11-10 20:40:00 +00004017 // Look through all of the overloaded functions, searching for one
4018 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004019 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Mike Stump11289f42009-09-09 15:08:12 +00004020
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004021 bool FoundNonTemplateFunction = false;
Douglas Gregor9b146582009-07-08 20:55:45 +00004022 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004023 // C++ [over.over]p3:
4024 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004025 // targets of type "pointer-to-function" or "reference-to-function."
4026 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004027 // type "pointer-to-member-function."
4028 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004029
Mike Stump11289f42009-09-09 15:08:12 +00004030 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor9b146582009-07-08 20:55:45 +00004031 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump11289f42009-09-09 15:08:12 +00004032 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004033 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004034 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004035 // static when converting to member pointer.
4036 if (Method->isStatic() == IsMember)
4037 continue;
4038 } else if (IsMember)
4039 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004040
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004041 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004042 // If the name is a function template, template argument deduction is
4043 // done (14.8.2.2), and if the argument deduction succeeds, the
4044 // resulting template argument list is used to generate a single
4045 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004046 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00004047 FunctionDecl *Specialization = 0;
4048 TemplateDeductionInfo Info(Context);
4049 if (TemplateDeductionResult Result
4050 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
4051 /*FIXME:*/0, /*FIXME:*/0,
4052 FunctionType, Specialization, Info)) {
4053 // FIXME: make a note of the failed deduction for diagnostics.
4054 (void)Result;
4055 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004056 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004057 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004058 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004059 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004060 }
4061 }
Mike Stump11289f42009-09-09 15:08:12 +00004062
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004063 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4064 // Skip non-static functions when converting to pointer, and static
4065 // when converting to member pointer.
4066 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004067 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004068 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004069 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004070
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004071 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004072 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004073 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004074 FoundNonTemplateFunction = true;
4075 }
Mike Stump11289f42009-09-09 15:08:12 +00004076 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004077 }
4078
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004079 // If there were 0 or 1 matches, we're done.
4080 if (Matches.empty())
4081 return 0;
4082 else if (Matches.size() == 1)
4083 return *Matches.begin();
4084
4085 // C++ [over.over]p4:
4086 // If more than one function is selected, [...]
4087 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor05155d82009-08-21 23:19:43 +00004088 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004089 if (FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004090 // [...] any function template specializations in the set are
4091 // eliminated if the set also contains a non-template function, [...]
4092 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004093 if ((*M)->getPrimaryTemplate() == 0)
4094 RemainingMatches.push_back(*M);
4095 } else {
Douglas Gregor05155d82009-08-21 23:19:43 +00004096 // [...] and any given function template specialization F1 is
4097 // eliminated if the set contains a second function template
4098 // specialization whose function template is more specialized
4099 // than the function template of F1 according to the partial
4100 // ordering rules of 14.5.5.2.
4101
4102 // The algorithm specified above is quadratic. We instead use a
4103 // two-pass algorithm (similar to the one used to identify the
4104 // best viable function in an overload set) that identifies the
4105 // best function template (if it exists).
4106 MatchIter Best = Matches.begin();
4107 MatchIter M = Best, MEnd = Matches.end();
4108 // Find the most specialized function.
4109 for (++M; M != MEnd; ++M)
4110 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4111 (*Best)->getPrimaryTemplate(),
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004112 TPOC_Other)
Douglas Gregor05155d82009-08-21 23:19:43 +00004113 == (*M)->getPrimaryTemplate())
4114 Best = M;
4115
4116 // Determine whether this function template is more specialized
4117 // that all of the others.
4118 bool Ambiguous = false;
4119 for (M = Matches.begin(); M != MEnd; ++M) {
4120 if (M != Best &&
4121 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4122 (*Best)->getPrimaryTemplate(),
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004123 TPOC_Other)
Douglas Gregor05155d82009-08-21 23:19:43 +00004124 != (*Best)->getPrimaryTemplate()) {
4125 Ambiguous = true;
4126 break;
4127 }
4128 }
4129
4130 // If one function template was more specialized than all of the
4131 // others, return it.
4132 if (!Ambiguous)
4133 return *Best;
4134
4135 // We could not find a most-specialized function template, which
4136 // is equivalent to having a set of function templates with more
4137 // than one such template. So, we place all of the function
4138 // templates into the set of remaining matches and produce a
4139 // diagnostic below. FIXME: we could perform the quadratic
4140 // algorithm here, pruning the result set to limit the number of
4141 // candidates output later.
Douglas Gregor48bc3742009-09-14 22:02:01 +00004142 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004143 }
Mike Stump11289f42009-09-09 15:08:12 +00004144
4145 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004146 // selected function.
4147 if (RemainingMatches.size() == 1)
4148 return RemainingMatches.front();
Mike Stump11289f42009-09-09 15:08:12 +00004149
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004150 // FIXME: We should probably return the same thing that BestViableFunction
4151 // returns (even if we issue the diagnostics here).
4152 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4153 << RemainingMatches[0]->getDeclName();
4154 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4155 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004156 return 0;
4157}
4158
Douglas Gregorcabea402009-09-22 15:41:20 +00004159/// \brief Add a single candidate to the overload set.
4160static void AddOverloadedCallCandidate(Sema &S,
4161 AnyFunctionDecl Callee,
4162 bool &ArgumentDependentLookup,
4163 bool HasExplicitTemplateArgs,
4164 const TemplateArgument *ExplicitTemplateArgs,
4165 unsigned NumExplicitTemplateArgs,
4166 Expr **Args, unsigned NumArgs,
4167 OverloadCandidateSet &CandidateSet,
4168 bool PartialOverloading) {
4169 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4170 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4171 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4172 PartialOverloading);
4173
4174 if (Func->getDeclContext()->isRecord() ||
4175 Func->getDeclContext()->isFunctionOrMethod())
4176 ArgumentDependentLookup = false;
4177 return;
4178 }
4179
4180 FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4181 S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4182 ExplicitTemplateArgs,
4183 NumExplicitTemplateArgs,
4184 Args, NumArgs, CandidateSet);
4185
4186 if (FuncTemplate->getDeclContext()->isRecord())
4187 ArgumentDependentLookup = false;
4188}
4189
4190/// \brief Add the overload candidates named by callee and/or found by argument
4191/// dependent lookup to the given overload set.
4192void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4193 DeclarationName &UnqualifiedName,
4194 bool &ArgumentDependentLookup,
4195 bool HasExplicitTemplateArgs,
4196 const TemplateArgument *ExplicitTemplateArgs,
4197 unsigned NumExplicitTemplateArgs,
4198 Expr **Args, unsigned NumArgs,
4199 OverloadCandidateSet &CandidateSet,
4200 bool PartialOverloading) {
4201 // Add the functions denoted by Callee to the set of candidate
4202 // functions. While we're doing so, track whether argument-dependent
4203 // lookup still applies, per:
4204 //
4205 // C++0x [basic.lookup.argdep]p3:
4206 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4207 // and let Y be the lookup set produced by argument dependent
4208 // lookup (defined as follows). If X contains
4209 //
4210 // -- a declaration of a class member, or
4211 //
4212 // -- a block-scope function declaration that is not a
4213 // using-declaration (FIXME: check for using declaration), or
4214 //
4215 // -- a declaration that is neither a function or a function
4216 // template
4217 //
4218 // then Y is empty.
4219 if (!Callee) {
4220 // Nothing to do.
4221 } else if (OverloadedFunctionDecl *Ovl
4222 = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4223 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4224 FuncEnd = Ovl->function_end();
4225 Func != FuncEnd; ++Func)
4226 AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4227 HasExplicitTemplateArgs,
4228 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4229 Args, NumArgs, CandidateSet,
4230 PartialOverloading);
4231 } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4232 AddOverloadedCallCandidate(*this,
4233 AnyFunctionDecl::getFromNamedDecl(Callee),
4234 ArgumentDependentLookup,
4235 HasExplicitTemplateArgs,
4236 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4237 Args, NumArgs, CandidateSet,
4238 PartialOverloading);
4239 // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4240 // checking dynamically.
4241
4242 if (Callee)
4243 UnqualifiedName = Callee->getDeclName();
4244
4245 if (ArgumentDependentLookup)
4246 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4247 HasExplicitTemplateArgs,
4248 ExplicitTemplateArgs,
4249 NumExplicitTemplateArgs,
4250 CandidateSet,
4251 PartialOverloading);
4252}
4253
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004254/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004255/// (which eventually refers to the declaration Func) and the call
4256/// arguments Args/NumArgs, attempt to resolve the function call down
4257/// to a specific function. If overload resolution succeeds, returns
4258/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004259/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004260/// arguments and Fn, and returns NULL.
Douglas Gregore254f902009-02-04 00:32:51 +00004261FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004262 DeclarationName UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00004263 bool HasExplicitTemplateArgs,
4264 const TemplateArgument *ExplicitTemplateArgs,
4265 unsigned NumExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004266 SourceLocation LParenLoc,
4267 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004268 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004269 SourceLocation RParenLoc,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004270 bool &ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004271 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004272
4273 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004274 // functions.
4275 AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4276 HasExplicitTemplateArgs, ExplicitTemplateArgs,
4277 NumExplicitTemplateArgs, Args, NumArgs,
4278 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004279 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004280 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004281 case OR_Success:
4282 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004283
4284 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004285 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004286 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004287 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004288 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4289 break;
4290
4291 case OR_Ambiguous:
4292 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004293 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004294 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4295 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004296
4297 case OR_Deleted:
4298 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4299 << Best->Function->isDeleted()
4300 << UnqualifiedName
4301 << Fn->getSourceRange();
4302 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4303 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004304 }
4305
4306 // Overload resolution failed. Destroy all of the subexpressions and
4307 // return NULL.
4308 Fn->Destroy(Context);
4309 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4310 Args[Arg]->Destroy(Context);
4311 return 0;
4312}
4313
Douglas Gregor084d8552009-03-13 23:49:33 +00004314/// \brief Create a unary operation that may resolve to an overloaded
4315/// operator.
4316///
4317/// \param OpLoc The location of the operator itself (e.g., '*').
4318///
4319/// \param OpcIn The UnaryOperator::Opcode that describes this
4320/// operator.
4321///
4322/// \param Functions The set of non-member functions that will be
4323/// considered by overload resolution. The caller needs to build this
4324/// set based on the context using, e.g.,
4325/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4326/// set should not contain any member functions; those will be added
4327/// by CreateOverloadedUnaryOp().
4328///
4329/// \param input The input argument.
4330Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4331 unsigned OpcIn,
4332 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004333 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004334 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4335 Expr *Input = (Expr *)input.get();
4336
4337 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4338 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4339 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4340
4341 Expr *Args[2] = { Input, 0 };
4342 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004343
Douglas Gregor084d8552009-03-13 23:49:33 +00004344 // For post-increment and post-decrement, add the implicit '0' as
4345 // the second argument, so that we know this is a post-increment or
4346 // post-decrement.
4347 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4348 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004349 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004350 SourceLocation());
4351 NumArgs = 2;
4352 }
4353
4354 if (Input->isTypeDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00004355 OverloadedFunctionDecl *Overloads
Douglas Gregor084d8552009-03-13 23:49:33 +00004356 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004357 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004358 FuncEnd = Functions.end();
4359 Func != FuncEnd; ++Func)
4360 Overloads->addOverload(*Func);
4361
4362 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4363 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004364
Douglas Gregor084d8552009-03-13 23:49:33 +00004365 input.release();
4366 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4367 &Args[0], NumArgs,
4368 Context.DependentTy,
4369 OpLoc));
4370 }
4371
4372 // Build an empty overload set.
4373 OverloadCandidateSet CandidateSet;
4374
4375 // Add the candidates from the given function set.
4376 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4377
4378 // Add operator candidates that are member functions.
4379 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4380
4381 // Add builtin operator candidates.
4382 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4383
4384 // Perform overload resolution.
4385 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004386 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004387 case OR_Success: {
4388 // We found a built-in operator or an overloaded operator.
4389 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004390
Douglas Gregor084d8552009-03-13 23:49:33 +00004391 if (FnDecl) {
4392 // We matched an overloaded operator. Build a call to that
4393 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004394
Douglas Gregor084d8552009-03-13 23:49:33 +00004395 // Convert the arguments.
4396 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4397 if (PerformObjectArgumentInitialization(Input, Method))
4398 return ExprError();
4399 } else {
4400 // Convert the arguments.
4401 if (PerformCopyInitialization(Input,
4402 FnDecl->getParamDecl(0)->getType(),
4403 "passing"))
4404 return ExprError();
4405 }
4406
4407 // Determine the result type
4408 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004409 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor084d8552009-03-13 23:49:33 +00004410 ResultTy = ResultTy.getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004411
Douglas Gregor084d8552009-03-13 23:49:33 +00004412 // Build the actual expression node.
4413 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4414 SourceLocation());
4415 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004416
Douglas Gregor084d8552009-03-13 23:49:33 +00004417 input.release();
Mike Stump11289f42009-09-09 15:08:12 +00004418
4419 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004420 &Input, 1, ResultTy, OpLoc);
4421 return MaybeBindToTemporary(CE);
Douglas Gregor084d8552009-03-13 23:49:33 +00004422 } else {
4423 // We matched a built-in operator. Convert the arguments, then
4424 // break out so that we will build the appropriate built-in
4425 // operator node.
4426 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4427 Best->Conversions[0], "passing"))
4428 return ExprError();
4429
4430 break;
4431 }
4432 }
4433
4434 case OR_No_Viable_Function:
4435 // No viable function; fall through to handling this as a
4436 // built-in operator, which will produce an error message for us.
4437 break;
4438
4439 case OR_Ambiguous:
4440 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4441 << UnaryOperator::getOpcodeStr(Opc)
4442 << Input->getSourceRange();
4443 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4444 return ExprError();
4445
4446 case OR_Deleted:
4447 Diag(OpLoc, diag::err_ovl_deleted_oper)
4448 << Best->Function->isDeleted()
4449 << UnaryOperator::getOpcodeStr(Opc)
4450 << Input->getSourceRange();
4451 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4452 return ExprError();
4453 }
4454
4455 // Either we found no viable overloaded operator or we matched a
4456 // built-in operator. In either case, fall through to trying to
4457 // build a built-in operation.
4458 input.release();
4459 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4460}
4461
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004462/// \brief Create a binary operation that may resolve to an overloaded
4463/// operator.
4464///
4465/// \param OpLoc The location of the operator itself (e.g., '+').
4466///
4467/// \param OpcIn The BinaryOperator::Opcode that describes this
4468/// operator.
4469///
4470/// \param Functions The set of non-member functions that will be
4471/// considered by overload resolution. The caller needs to build this
4472/// set based on the context using, e.g.,
4473/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4474/// set should not contain any member functions; those will be added
4475/// by CreateOverloadedBinOp().
4476///
4477/// \param LHS Left-hand argument.
4478/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004479Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004480Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004481 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004482 FunctionSet &Functions,
4483 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004484 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004485 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004486
4487 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4488 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4489 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4490
4491 // If either side is type-dependent, create an appropriate dependent
4492 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004493 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004494 // .* cannot be overloaded.
4495 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004496 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004497 Context.DependentTy, OpLoc));
4498
Mike Stump11289f42009-09-09 15:08:12 +00004499 OverloadedFunctionDecl *Overloads
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004500 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004501 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004502 FuncEnd = Functions.end();
4503 Func != FuncEnd; ++Func)
4504 Overloads->addOverload(*Func);
4505
4506 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4507 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004508
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004509 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004510 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004511 Context.DependentTy,
4512 OpLoc));
4513 }
4514
4515 // If this is the .* operator, which is not overloadable, just
4516 // create a built-in binary operator.
4517 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004518 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004519
4520 // If this is one of the assignment operators, we only perform
4521 // overload resolution if the left-hand side is a class or
4522 // enumeration type (C++ [expr.ass]p3).
4523 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregore9899d92009-08-26 17:08:25 +00004524 !Args[0]->getType()->isOverloadableType())
4525 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004526
Douglas Gregor084d8552009-03-13 23:49:33 +00004527 // Build an empty overload set.
4528 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004529
4530 // Add the candidates from the given function set.
4531 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4532
4533 // Add operator candidates that are member functions.
4534 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4535
4536 // Add builtin operator candidates.
4537 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4538
4539 // Perform overload resolution.
4540 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004541 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004542 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004543 // We found a built-in operator or an overloaded operator.
4544 FunctionDecl *FnDecl = Best->Function;
4545
4546 if (FnDecl) {
4547 // We matched an overloaded operator. Build a call to that
4548 // operator.
4549
4550 // Convert the arguments.
4551 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004552 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4553 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004554 "passing"))
4555 return ExprError();
4556 } else {
4557 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004558 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004559 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004560 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004561 "passing"))
4562 return ExprError();
4563 }
4564
4565 // Determine the result type
4566 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004567 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004568 ResultTy = ResultTy.getNonReferenceType();
4569
4570 // Build the actual expression node.
4571 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004572 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004573 UsualUnaryConversions(FnExpr);
4574
Mike Stump11289f42009-09-09 15:08:12 +00004575 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004576 Args, 2, ResultTy, OpLoc);
4577 return MaybeBindToTemporary(CE);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004578 } else {
4579 // We matched a built-in operator. Convert the arguments, then
4580 // break out so that we will build the appropriate built-in
4581 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004582 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004583 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004584 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004585 Best->Conversions[1], "passing"))
4586 return ExprError();
4587
4588 break;
4589 }
4590 }
4591
4592 case OR_No_Viable_Function:
Sebastian Redl027de2a2009-05-21 11:50:50 +00004593 // For class as left operand for assignment or compound assigment operator
4594 // do not fall through to handling in built-in, but report that no overloaded
4595 // assignment operator found
Douglas Gregore9899d92009-08-26 17:08:25 +00004596 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004597 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4598 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004599 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl027de2a2009-05-21 11:50:50 +00004600 return ExprError();
4601 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004602 // No viable function; fall through to handling this as a
4603 // built-in operator, which will produce an error message for us.
4604 break;
4605
4606 case OR_Ambiguous:
4607 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4608 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004609 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004610 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4611 return ExprError();
4612
4613 case OR_Deleted:
4614 Diag(OpLoc, diag::err_ovl_deleted_oper)
4615 << Best->Function->isDeleted()
4616 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004617 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004618 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4619 return ExprError();
4620 }
4621
4622 // Either we found no viable overloaded operator or we matched a
4623 // built-in operator. In either case, try to build a built-in
4624 // operation.
Douglas Gregore9899d92009-08-26 17:08:25 +00004625 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004626}
4627
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004628/// BuildCallToMemberFunction - Build a call to a member
4629/// function. MemExpr is the expression that refers to the member
4630/// function (and includes the object parameter), Args/NumArgs are the
4631/// arguments to the function call (not including the object
4632/// parameter). The caller needs to validate that the member
4633/// expression refers to a member function or an overloaded member
4634/// function.
4635Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00004636Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4637 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004638 unsigned NumArgs, SourceLocation *CommaLocs,
4639 SourceLocation RParenLoc) {
4640 // Dig out the member expression. This holds both the object
4641 // argument and the member function we're referring to.
4642 MemberExpr *MemExpr = 0;
4643 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4644 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4645 else
4646 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4647 assert(MemExpr && "Building member call without member expression");
4648
4649 // Extract the object argument.
4650 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004651
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004652 CXXMethodDecl *Method = 0;
Douglas Gregor97628d62009-08-21 00:16:32 +00004653 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4654 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004655 // Add overload candidates
4656 OverloadCandidateSet CandidateSet;
Douglas Gregor97628d62009-08-21 00:16:32 +00004657 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004658
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004659 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4660 Func != FuncEnd; ++Func) {
4661 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
Mike Stump11289f42009-09-09 15:08:12 +00004662 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004663 /*SuppressUserConversions=*/false);
4664 else
Douglas Gregor84f14dd2009-09-01 00:37:14 +00004665 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4666 MemExpr->hasExplicitTemplateArgumentList(),
4667 MemExpr->getTemplateArgs(),
4668 MemExpr->getNumTemplateArgs(),
4669 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004670 CandidateSet,
4671 /*SuppressUsedConversions=*/false);
4672 }
Mike Stump11289f42009-09-09 15:08:12 +00004673
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004674 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004675 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004676 case OR_Success:
4677 Method = cast<CXXMethodDecl>(Best->Function);
4678 break;
4679
4680 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004681 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004682 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004683 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004684 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4685 // FIXME: Leaking incoming expressions!
4686 return true;
4687
4688 case OR_Ambiguous:
Mike Stump11289f42009-09-09 15:08:12 +00004689 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004690 diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004691 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004692 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4693 // FIXME: Leaking incoming expressions!
4694 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004695
4696 case OR_Deleted:
Mike Stump11289f42009-09-09 15:08:12 +00004697 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00004698 diag::err_ovl_deleted_member_call)
4699 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00004700 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004701 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4702 // FIXME: Leaking incoming expressions!
4703 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004704 }
4705
4706 FixOverloadedFunctionReference(MemExpr, Method);
4707 } else {
4708 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4709 }
4710
4711 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00004712 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004713 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00004714 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004715 Method->getResultType().getNonReferenceType(),
4716 RParenLoc));
4717
4718 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00004719 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004720 PerformObjectArgumentInitialization(ObjectArg, Method))
4721 return true;
4722 MemExpr->setBase(ObjectArg);
4723
4724 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004725 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004726 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004727 RParenLoc))
4728 return true;
4729
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004730 if (CheckFunctionCall(Method, TheCall.get()))
4731 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00004732
4733 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004734}
4735
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004736/// BuildCallToObjectOfClassType - Build a call to an object of class
4737/// type (C++ [over.call.object]), which can end up invoking an
4738/// overloaded function call operator (@c operator()) or performing a
4739/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00004740Sema::ExprResult
4741Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00004742 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004743 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004744 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004745 SourceLocation RParenLoc) {
4746 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004747 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00004748
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004749 // C++ [over.call.object]p1:
4750 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00004751 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004752 // candidate functions includes at least the function call
4753 // operators of T. The function call operators of T are obtained by
4754 // ordinary lookup of the name operator() in the context of
4755 // (E).operator().
4756 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00004757 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004758 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004759 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004760 Oper != OperEnd; ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00004761 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor55297ac2008-12-23 00:26:44 +00004762 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004763
Douglas Gregorab7897a2008-11-19 22:57:39 +00004764 // C++ [over.call.object]p2:
4765 // In addition, for each conversion function declared in T of the
4766 // form
4767 //
4768 // operator conversion-type-id () cv-qualifier;
4769 //
4770 // where cv-qualifier is the same cv-qualification as, or a
4771 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00004772 // denotes the type "pointer to function of (P1,...,Pn) returning
4773 // R", or the type "reference to pointer to function of
4774 // (P1,...,Pn) returning R", or the type "reference to function
4775 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00004776 // is also considered as a candidate function. Similarly,
4777 // surrogate call functions are added to the set of candidate
4778 // functions for each conversion function declared in an
4779 // accessible base class provided the function is not hidden
4780 // within T by another intervening declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004781
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004782 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4783 // FIXME: Look in base classes for more conversion operators!
Mike Stump11289f42009-09-09 15:08:12 +00004784 OverloadedFunctionDecl *Conversions
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004785 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00004786 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004787 Func = Conversions->function_begin(),
4788 FuncEnd = Conversions->function_end();
4789 Func != FuncEnd; ++Func) {
4790 CXXConversionDecl *Conv;
4791 FunctionTemplateDecl *ConvTemplate;
4792 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00004793
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004794 // Skip over templated conversion functions; they aren't
4795 // surrogates.
4796 if (ConvTemplate)
4797 continue;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004798
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004799 // Strip the reference type (if any) and then the pointer type (if
4800 // any) to get down to what might be a function type.
4801 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4802 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4803 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004804
John McCall9dd450b2009-09-21 23:43:11 +00004805 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004806 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4807 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004808 }
Mike Stump11289f42009-09-09 15:08:12 +00004809
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004810 // Perform overload resolution.
4811 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004812 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004813 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00004814 // Overload resolution succeeded; we'll build the appropriate call
4815 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004816 break;
4817
4818 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004819 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00004820 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004821 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00004822 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004823 break;
4824
4825 case OR_Ambiguous:
4826 Diag(Object->getSourceRange().getBegin(),
4827 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004828 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004829 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4830 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004831
4832 case OR_Deleted:
4833 Diag(Object->getSourceRange().getBegin(),
4834 diag::err_ovl_deleted_object_call)
4835 << Best->Function->isDeleted()
4836 << Object->getType() << Object->getSourceRange();
4837 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4838 break;
Mike Stump11289f42009-09-09 15:08:12 +00004839 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004840
Douglas Gregorab7897a2008-11-19 22:57:39 +00004841 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004842 // We had an error; delete all of the subexpressions and return
4843 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00004844 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004845 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00004846 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004847 return true;
4848 }
4849
Douglas Gregorab7897a2008-11-19 22:57:39 +00004850 if (Best->Function == 0) {
4851 // Since there is no function declaration, this is one of the
4852 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00004853 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00004854 = cast<CXXConversionDecl>(
4855 Best->Conversions[0].UserDefined.ConversionFunction);
4856
4857 // We selected one of the surrogate functions that converts the
4858 // object parameter to a function pointer. Perform the conversion
4859 // on the object argument, then let ActOnCallExpr finish the job.
4860 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004861 ImpCastExprToType(Object,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004862 Conv->getConversionType().getNonReferenceType(),
Anders Carlssona076d142009-07-31 01:23:52 +00004863 CastExpr::CK_Unknown,
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004864 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004865 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4866 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4867 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004868 }
4869
4870 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4871 // that calls this method, using Object for the implicit object
4872 // parameter and passing along the remaining arguments.
4873 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00004874 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004875
4876 unsigned NumArgsInProto = Proto->getNumArgs();
4877 unsigned NumArgsToCheck = NumArgs;
4878
4879 // Build the full argument list for the method call (the
4880 // implicit object parameter is placed at the beginning of the
4881 // list).
4882 Expr **MethodArgs;
4883 if (NumArgs < NumArgsInProto) {
4884 NumArgsToCheck = NumArgsInProto;
4885 MethodArgs = new Expr*[NumArgsInProto + 1];
4886 } else {
4887 MethodArgs = new Expr*[NumArgs + 1];
4888 }
4889 MethodArgs[0] = Object;
4890 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4891 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00004892
4893 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004894 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004895 UsualUnaryConversions(NewFn);
4896
4897 // Once we've built TheCall, all of the expressions are properly
4898 // owned.
4899 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004900 ExprOwningPtr<CXXOperatorCallExpr>
4901 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004902 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00004903 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004904 delete [] MethodArgs;
4905
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004906 // We may have default arguments. If so, we need to allocate more
4907 // slots in the call for them.
4908 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00004909 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004910 else if (NumArgs > NumArgsInProto)
4911 NumArgsToCheck = NumArgsInProto;
4912
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004913 bool IsError = false;
4914
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004915 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004916 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004917 TheCall->setArg(0, Object);
4918
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004919
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004920 // Check the argument types.
4921 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004922 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004923 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004924 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00004925
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004926 // Pass the argument.
4927 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004928 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004929 } else {
Anders Carlssone8271232009-08-14 18:30:22 +00004930 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004931 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004932
4933 TheCall->setArg(i + 1, Arg);
4934 }
4935
4936 // If this is a variadic call, handle args passed through "...".
4937 if (Proto->isVariadic()) {
4938 // Promote the arguments (C99 6.5.2.2p7).
4939 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4940 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004941 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004942 TheCall->setArg(i + 1, Arg);
4943 }
4944 }
4945
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004946 if (IsError) return true;
4947
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004948 if (CheckFunctionCall(Method, TheCall.get()))
4949 return true;
4950
Anders Carlsson1c83deb2009-08-16 03:53:54 +00004951 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004952}
4953
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004954/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00004955/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004956/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00004957Sema::OwningExprResult
4958Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4959 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004960 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00004961
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004962 // C++ [over.ref]p1:
4963 //
4964 // [...] An expression x->m is interpreted as (x.operator->())->m
4965 // for a class object x of type T if T::operator->() exists and if
4966 // the operator is selected as the best match function by the
4967 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004968 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4969 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004970 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00004971
Anders Carlsson78b54932009-09-10 23:18:36 +00004972 LookupResult R = LookupQualifiedName(BaseRecord->getDecl(), OpName,
4973 LookupOrdinaryName);
4974
4975 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
4976 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00004977 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004978 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004979
4980 // Perform overload resolution.
4981 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004982 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004983 case OR_Success:
4984 // Overload resolution succeeded; we'll build the call below.
4985 break;
4986
4987 case OR_No_Viable_Function:
4988 if (CandidateSet.empty())
4989 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00004990 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004991 else
4992 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00004993 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004994 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00004995 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004996
4997 case OR_Ambiguous:
4998 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00004999 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005000 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005001 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005002
5003 case OR_Deleted:
5004 Diag(OpLoc, diag::err_ovl_deleted_oper)
5005 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005006 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005007 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005008 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005009 }
5010
5011 // Convert the object parameter.
5012 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005013 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005014 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005015
5016 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005017 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005018
5019 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005020 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5021 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005022 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005023 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005024 Method->getResultType().getNonReferenceType(),
5025 OpLoc);
Douglas Gregord8061562009-08-06 03:17:00 +00005026 return Owned(Base);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005027}
5028
Douglas Gregorcd695e52008-11-10 20:40:00 +00005029/// FixOverloadedFunctionReference - E is an expression that refers to
5030/// a C++ overloaded function (possibly with some parentheses and
5031/// perhaps a '&' around it). We have resolved the overloaded function
5032/// to the function declaration Fn, so patch up the expression E to
5033/// refer (possibly indirectly) to Fn.
5034void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
5035 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5036 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5037 E->setType(PE->getSubExpr()->getType());
5038 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005039 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005040 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005041 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5042 if (Method->isStatic()) {
5043 // Do nothing: static member functions aren't any different
5044 // from non-member functions.
Mike Stump11289f42009-09-09 15:08:12 +00005045 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005046 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
5047 // We have taken the address of a pointer to member
5048 // function. Perform the computation here so that we get the
5049 // appropriate pointer to member type.
5050 DRE->setDecl(Fn);
5051 DRE->setType(Fn->getType());
5052 QualType ClassType
5053 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
Mike Stump11289f42009-09-09 15:08:12 +00005054 E->setType(Context.getMemberPointerType(Fn->getType(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005055 ClassType.getTypePtr()));
5056 return;
5057 }
5058 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005059 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005060 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregorcd695e52008-11-10 20:40:00 +00005061 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor9b146582009-07-08 20:55:45 +00005062 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Mike Stump11289f42009-09-09 15:08:12 +00005063 isa<FunctionTemplateDecl>(DR->getDecl())) &&
Douglas Gregor9b146582009-07-08 20:55:45 +00005064 "Expected overloaded function or function template");
Douglas Gregorcd695e52008-11-10 20:40:00 +00005065 DR->setDecl(Fn);
5066 E->setType(Fn->getType());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005067 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5068 MemExpr->setMemberDecl(Fn);
5069 E->setType(Fn->getType());
Douglas Gregorcd695e52008-11-10 20:40:00 +00005070 } else {
5071 assert(false && "Invalid reference to overloaded function");
5072 }
5073}
5074
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005075} // end namespace clang