blob: dde58882a9a3bdf409cdc93f8ca2259eb8eb3d42 [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;
Anders Carlsson228eea32009-08-28 15:33:32 +0000413 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000414 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000415 else if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +0000416 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000417 !SuppressUserConversions, AllowExplicit,
418 ForceRValue)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000419 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000420 // C++ [over.ics.user]p4:
421 // A conversion of an expression of class type to the same class
422 // type is given Exact Match rank, and a conversion of an
423 // expression of class type to a base class of that type is
424 // given Conversion rank, in spite of the fact that a copy
425 // constructor (i.e., a user-defined conversion function) is
426 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000427 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000428 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000429 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000430 = Context.getCanonicalType(From->getType().getUnqualifiedType());
431 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
432 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000433 // Turn this into a "standard" conversion sequence, so that it
434 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000435 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
436 ICS.Standard.setAsIdentityConversion();
437 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
438 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000439 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000440 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000441 ICS.Standard.Second = ICK_Derived_To_Base;
442 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000443 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000444
445 // C++ [over.best.ics]p4:
446 // However, when considering the argument of a user-defined
447 // conversion function that is a candidate by 13.3.1.3 when
448 // invoked for the copying of the temporary in the second step
449 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
450 // 13.3.1.6 in all cases, only standard conversion sequences and
451 // ellipsis conversion sequences are allowed.
452 if (SuppressUserConversions &&
453 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
454 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000455 } else
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000456 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000457
458 return ICS;
459}
460
461/// IsStandardConversion - Determines whether there is a standard
462/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
463/// expression From to the type ToType. Standard conversion sequences
464/// only consider non-class types; for conversions that involve class
465/// types, use TryImplicitConversion. If a conversion exists, SCS will
466/// contain the standard conversion sequence required to perform this
467/// conversion and this routine will return true. Otherwise, this
468/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000469bool
470Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000471 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000472 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000473 QualType FromType = From->getType();
474
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000475 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000476 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000477 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000478 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000479 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000480 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000481
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000482 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000483 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000484 if (FromType->isRecordType() || ToType->isRecordType()) {
485 if (getLangOptions().CPlusPlus)
486 return false;
487
Mike Stump11289f42009-09-09 15:08:12 +0000488 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000489 }
490
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491 // The first conversion can be an lvalue-to-rvalue conversion,
492 // array-to-pointer conversion, or function-to-pointer conversion
493 // (C++ 4p1).
494
Mike Stump11289f42009-09-09 15:08:12 +0000495 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496 // An lvalue (3.10) of a non-function, non-array type T can be
497 // converted to an rvalue.
498 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000499 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000500 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000501 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000502 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000503
504 // If T is a non-class type, the type of the rvalue is the
505 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000506 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
507 // just strip the qualifiers because they don't matter.
508
509 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000510 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000511 } else if (FromType->isArrayType()) {
512 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000513 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000514
515 // An lvalue or rvalue of type "array of N T" or "array of unknown
516 // bound of T" can be converted to an rvalue of type "pointer to
517 // T" (C++ 4.2p1).
518 FromType = Context.getArrayDecayedType(FromType);
519
520 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
521 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000522 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000523
524 // For the purpose of ranking in overload resolution
525 // (13.3.3.1.1), this conversion is considered an
526 // array-to-pointer conversion followed by a qualification
527 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000528 SCS.Second = ICK_Identity;
529 SCS.Third = ICK_Qualification;
530 SCS.ToTypePtr = ToType.getAsOpaquePtr();
531 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000532 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000533 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
534 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000535 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000536
537 // An lvalue of function type T can be converted to an rvalue of
538 // type "pointer to T." The result is a pointer to the
539 // function. (C++ 4.3p1).
540 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000541 } else if (FunctionDecl *Fn
Douglas Gregorcd695e52008-11-10 20:40:00 +0000542 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000543 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000544 SCS.First = ICK_Function_To_Pointer;
545
546 // We were able to resolve the address of the overloaded function,
547 // so we can convert to the type of that function.
548 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000549 if (ToType->isLValueReferenceType())
550 FromType = Context.getLValueReferenceType(FromType);
551 else if (ToType->isRValueReferenceType())
552 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000553 else if (ToType->isMemberPointerType()) {
554 // Resolve address only succeeds if both sides are member pointers,
555 // but it doesn't have to be the same class. See DR 247.
556 // Note that this means that the type of &Derived::fn can be
557 // Ret (Base::*)(Args) if the fn overload actually found is from the
558 // base class, even if it was brought into the derived class via a
559 // using declaration. The standard isn't clear on this issue at all.
560 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
561 FromType = Context.getMemberPointerType(FromType,
562 Context.getTypeDeclType(M->getParent()).getTypePtr());
563 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000564 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000565 } else {
566 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000567 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000568 }
569
570 // The second conversion can be an integral promotion, floating
571 // point promotion, integral conversion, floating point conversion,
572 // floating-integral conversion, pointer conversion,
573 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000574 // For overloading in C, this can also be a "compatible-type"
575 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000576 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000577 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000578 // The unqualified versions of the types are the same: there's no
579 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000580 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000581 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000582 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000583 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000584 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000585 } else if (IsFloatingPointPromotion(FromType, ToType)) {
586 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000587 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000588 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000589 } else if (IsComplexPromotion(FromType, ToType)) {
590 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000591 SCS.Second = ICK_Complex_Promotion;
592 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000593 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000594 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000595 // Integral conversions (C++ 4.7).
596 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000597 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000598 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000599 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
600 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000601 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000602 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000603 } else if (FromType->isComplexType() && ToType->isComplexType()) {
604 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000605 SCS.Second = ICK_Complex_Conversion;
606 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000607 } else if ((FromType->isFloatingType() &&
608 ToType->isIntegralType() && (!ToType->isBooleanType() &&
609 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000610 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000611 ToType->isFloatingType())) {
612 // Floating-integral conversions (C++ 4.9).
613 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000614 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000615 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000616 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
617 (ToType->isComplexType() && FromType->isArithmeticType())) {
618 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000619 SCS.Second = ICK_Complex_Real;
620 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000621 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
622 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000623 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000624 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000625 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stump12b8ce12009-08-04 21:02:39 +0000626 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
627 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000628 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000629 } else if (ToType->isBooleanType() &&
630 (FromType->isArithmeticType() ||
631 FromType->isEnumeralType() ||
632 FromType->isPointerType() ||
633 FromType->isBlockPointerType() ||
634 FromType->isMemberPointerType() ||
635 FromType->isNullPtrType())) {
636 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000637 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000638 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000639 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000640 Context.typesAreCompatible(ToType, FromType)) {
641 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000642 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000643 } else {
644 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000645 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000646 }
647
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000648 QualType CanonFrom;
649 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000650 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000651 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000652 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000653 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000654 CanonFrom = Context.getCanonicalType(FromType);
655 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000656 } else {
657 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000658 SCS.Third = ICK_Identity;
659
Mike Stump11289f42009-09-09 15:08:12 +0000660 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000661 // [...] Any difference in top-level cv-qualification is
662 // subsumed by the initialization itself and does not constitute
663 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000664 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000665 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000666 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000667 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
668 FromType = ToType;
669 CanonFrom = CanonTo;
670 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000671 }
672
673 // If we have not converted the argument type to the parameter type,
674 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000675 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000676 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000677
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000678 SCS.ToTypePtr = FromType.getAsOpaquePtr();
679 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000680}
681
682/// IsIntegralPromotion - Determines whether the conversion from the
683/// expression From (whose potentially-adjusted type is FromType) to
684/// ToType is an integral promotion (C++ 4.5). If so, returns true and
685/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000686bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000687 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlee547972008-11-04 15:59:10 +0000688 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000689 if (!To) {
690 return false;
691 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000692
693 // An rvalue of type char, signed char, unsigned char, short int, or
694 // unsigned short int can be converted to an rvalue of type int if
695 // int can represent all the values of the source type; otherwise,
696 // the source rvalue can be converted to an rvalue of type unsigned
697 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000698 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000699 if (// We can promote any signed, promotable integer type to an int
700 (FromType->isSignedIntegerType() ||
701 // We can promote any unsigned integer type whose size is
702 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000703 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000704 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000705 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000706 }
707
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000708 return To->getKind() == BuiltinType::UInt;
709 }
710
711 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
712 // can be converted to an rvalue of the first of the following types
713 // that can represent all the values of its underlying type: int,
714 // unsigned int, long, or unsigned long (C++ 4.5p2).
715 if ((FromType->isEnumeralType() || FromType->isWideCharType())
716 && ToType->isIntegerType()) {
717 // Determine whether the type we're converting from is signed or
718 // unsigned.
719 bool FromIsSigned;
720 uint64_t FromSize = Context.getTypeSize(FromType);
721 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
722 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
723 FromIsSigned = UnderlyingType->isSignedIntegerType();
724 } else {
725 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
726 FromIsSigned = true;
727 }
728
729 // The types we'll try to promote to, in the appropriate
730 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000731 QualType PromoteTypes[6] = {
732 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000733 Context.LongTy, Context.UnsignedLongTy ,
734 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000735 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000736 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000737 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
738 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000739 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000740 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
741 // We found the type that we can promote to. If this is the
742 // type we wanted, we have a promotion. Otherwise, no
743 // promotion.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000744 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000745 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
746 }
747 }
748 }
749
750 // An rvalue for an integral bit-field (9.6) can be converted to an
751 // rvalue of type int if int can represent all the values of the
752 // bit-field; otherwise, it can be converted to unsigned int if
753 // unsigned int can represent all the values of the bit-field. If
754 // the bit-field is larger yet, no integral promotion applies to
755 // it. If the bit-field has an enumerated type, it is treated as any
756 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000757 // FIXME: We should delay checking of bit-fields until we actually perform the
758 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000759 using llvm::APSInt;
760 if (From)
761 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000762 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000763 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
764 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
765 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
766 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000767
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000768 // Are we promoting to an int from a bitfield that fits in an int?
769 if (BitWidth < ToSize ||
770 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
771 return To->getKind() == BuiltinType::Int;
772 }
Mike Stump11289f42009-09-09 15:08:12 +0000773
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000774 // Are we promoting to an unsigned int from an unsigned bitfield
775 // that fits into an unsigned int?
776 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
777 return To->getKind() == BuiltinType::UInt;
778 }
Mike Stump11289f42009-09-09 15:08:12 +0000779
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000780 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000781 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000782 }
Mike Stump11289f42009-09-09 15:08:12 +0000783
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000784 // An rvalue of type bool can be converted to an rvalue of type int,
785 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000786 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000787 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000788 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000789
790 return false;
791}
792
793/// IsFloatingPointPromotion - Determines whether the conversion from
794/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
795/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000796bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000797 /// An rvalue of type float can be converted to an rvalue of type
798 /// double. (C++ 4.6p1).
799 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000800 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000801 if (FromBuiltin->getKind() == BuiltinType::Float &&
802 ToBuiltin->getKind() == BuiltinType::Double)
803 return true;
804
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000805 // C99 6.3.1.5p1:
806 // When a float is promoted to double or long double, or a
807 // double is promoted to long double [...].
808 if (!getLangOptions().CPlusPlus &&
809 (FromBuiltin->getKind() == BuiltinType::Float ||
810 FromBuiltin->getKind() == BuiltinType::Double) &&
811 (ToBuiltin->getKind() == BuiltinType::LongDouble))
812 return true;
813 }
814
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000815 return false;
816}
817
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000818/// \brief Determine if a conversion is a complex promotion.
819///
820/// A complex promotion is defined as a complex -> complex conversion
821/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000822/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000823bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
824 const ComplexType *FromComplex = FromType->getAsComplexType();
825 if (!FromComplex)
826 return false;
827
828 const ComplexType *ToComplex = ToType->getAsComplexType();
829 if (!ToComplex)
830 return false;
831
832 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000833 ToComplex->getElementType()) ||
834 IsIntegralPromotion(0, FromComplex->getElementType(),
835 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000836}
837
Douglas Gregor237f96c2008-11-26 23:31:11 +0000838/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
839/// the pointer type FromPtr to a pointer to type ToPointee, with the
840/// same type qualifiers as FromPtr has on its pointee type. ToType,
841/// if non-empty, will be a pointer to ToType that may or may not have
842/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000843static QualType
844BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000845 QualType ToPointee, QualType ToType,
846 ASTContext &Context) {
847 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
848 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
849 unsigned Quals = CanonFromPointee.getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000850
851 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor237f96c2008-11-26 23:31:11 +0000852 if (CanonToPointee.getCVRQualifiers() == Quals) {
853 // ToType is exactly what we need. Return it.
854 if (ToType.getTypePtr())
855 return ToType;
856
857 // Build a pointer to ToPointee. It has the right qualifiers
858 // already.
859 return Context.getPointerType(ToPointee);
860 }
861
862 // Just build a canonical type that has the right qualifiers.
863 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
864}
865
Mike Stump11289f42009-09-09 15:08:12 +0000866static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000867 bool InOverloadResolution,
868 ASTContext &Context) {
869 // Handle value-dependent integral null pointer constants correctly.
870 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
871 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
872 Expr->getType()->isIntegralType())
873 return !InOverloadResolution;
874
875 return Expr->isNullPointerConstant(Context);
876}
Mike Stump11289f42009-09-09 15:08:12 +0000877
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000878/// IsPointerConversion - Determines whether the conversion of the
879/// expression From, which has the (possibly adjusted) type FromType,
880/// can be converted to the type ToType via a pointer conversion (C++
881/// 4.10). If so, returns true and places the converted type (that
882/// might differ from ToType in its cv-qualifiers at some level) into
883/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000884///
Douglas Gregora29dc052008-11-27 01:19:21 +0000885/// This routine also supports conversions to and from block pointers
886/// and conversions with Objective-C's 'id', 'id<protocols...>', and
887/// pointers to interfaces. FIXME: Once we've determined the
888/// appropriate overloading rules for Objective-C, we may want to
889/// split the Objective-C checks into a different routine; however,
890/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000891/// conversions, so for now they live here. IncompatibleObjC will be
892/// set if the conversion is an allowed Objective-C conversion that
893/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000894bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000895 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000896 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000897 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000898 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000899 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
900 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000901
Mike Stump11289f42009-09-09 15:08:12 +0000902 // Conversion from a null pointer constant to any Objective-C pointer type.
903 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000904 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000905 ConvertedType = ToType;
906 return true;
907 }
908
Douglas Gregor231d1c62008-11-27 00:15:41 +0000909 // Blocks: Block pointers can be converted to void*.
910 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000911 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000912 ConvertedType = ToType;
913 return true;
914 }
915 // Blocks: A null pointer constant can be converted to a block
916 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000917 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000918 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000919 ConvertedType = ToType;
920 return true;
921 }
922
Sebastian Redl576fd422009-05-10 18:38:11 +0000923 // If the left-hand-side is nullptr_t, the right side can be a null
924 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000925 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000926 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000927 ConvertedType = ToType;
928 return true;
929 }
930
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000931 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000932 if (!ToTypePtr)
933 return false;
934
935 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000936 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000937 ConvertedType = ToType;
938 return true;
939 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000940
Douglas Gregor237f96c2008-11-26 23:31:11 +0000941 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000942 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000943 if (!FromTypePtr)
944 return false;
945
946 QualType FromPointeeType = FromTypePtr->getPointeeType();
947 QualType ToPointeeType = ToTypePtr->getPointeeType();
948
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000949 // An rvalue of type "pointer to cv T," where T is an object type,
950 // can be converted to an rvalue of type "pointer to cv void" (C++
951 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000952 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000953 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000954 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000955 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000956 return true;
957 }
958
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000959 // When we're overloading in C, we allow a special kind of pointer
960 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +0000961 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000962 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000963 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000964 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +0000965 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000966 return true;
967 }
968
Douglas Gregor5c407d92008-10-23 00:40:37 +0000969 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +0000970 //
Douglas Gregor5c407d92008-10-23 00:40:37 +0000971 // An rvalue of type "pointer to cv D," where D is a class type,
972 // can be converted to an rvalue of type "pointer to cv B," where
973 // B is a base class (clause 10) of D. If B is an inaccessible
974 // (clause 11) or ambiguous (10.2) base class of D, a program that
975 // necessitates this conversion is ill-formed. The result of the
976 // conversion is a pointer to the base class sub-object of the
977 // derived class object. The null pointer value is converted to
978 // the null pointer value of the destination type.
979 //
Douglas Gregor39c16d42008-10-24 04:54:22 +0000980 // Note that we do not check for ambiguity or inaccessibility
981 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000982 if (getLangOptions().CPlusPlus &&
983 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor237f96c2008-11-26 23:31:11 +0000984 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000985 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000986 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000987 ToType, Context);
988 return true;
989 }
Douglas Gregor5c407d92008-10-23 00:40:37 +0000990
Douglas Gregora119f102008-12-19 19:13:09 +0000991 return false;
992}
993
994/// isObjCPointerConversion - Determines whether this is an
995/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
996/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +0000997bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +0000998 QualType& ConvertedType,
999 bool &IncompatibleObjC) {
1000 if (!getLangOptions().ObjC1)
1001 return false;
1002
Steve Naroff7cae42b2009-07-10 23:34:53 +00001003 // First, we handle all conversions on ObjC object pointer types.
1004 const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
Mike Stump11289f42009-09-09 15:08:12 +00001005 const ObjCObjectPointerType *FromObjCPtr =
Steve Naroff7cae42b2009-07-10 23:34:53 +00001006 FromType->getAsObjCObjectPointerType();
Douglas Gregora119f102008-12-19 19:13:09 +00001007
Steve Naroff7cae42b2009-07-10 23:34:53 +00001008 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001009 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001010 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001011 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001012 ConvertedType = ToType;
1013 return true;
1014 }
1015 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001016 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001017 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001018 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001019 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001020 ConvertedType = ToType;
1021 return true;
1022 }
1023 // Objective C++: We're able to convert from a pointer to an
1024 // interface to a pointer to a different interface.
1025 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1026 ConvertedType = ToType;
1027 return true;
1028 }
1029
1030 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1031 // Okay: this is some kind of implicit downcast of Objective-C
1032 // interfaces, which is permitted. However, we're going to
1033 // complain about it.
1034 IncompatibleObjC = true;
1035 ConvertedType = FromType;
1036 return true;
1037 }
Mike Stump11289f42009-09-09 15:08:12 +00001038 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001039 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001040 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001041 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001042 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001043 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001044 ToPointeeType = ToBlockPtr->getPointeeType();
1045 else
Douglas Gregora119f102008-12-19 19:13:09 +00001046 return false;
1047
Douglas Gregor033f56d2008-12-23 00:53:59 +00001048 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001049 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001050 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001051 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001052 FromPointeeType = FromBlockPtr->getPointeeType();
1053 else
Douglas Gregora119f102008-12-19 19:13:09 +00001054 return false;
1055
Douglas Gregora119f102008-12-19 19:13:09 +00001056 // If we have pointers to pointers, recursively check whether this
1057 // is an Objective-C conversion.
1058 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1059 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1060 IncompatibleObjC)) {
1061 // We always complain about this conversion.
1062 IncompatibleObjC = true;
1063 ConvertedType = ToType;
1064 return true;
1065 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001066 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001067 // differences in the argument and result types are in Objective-C
1068 // pointer conversions. If so, we permit the conversion (but
1069 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001070 const FunctionProtoType *FromFunctionType
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001071 = FromPointeeType->getAsFunctionProtoType();
1072 const FunctionProtoType *ToFunctionType
1073 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregora119f102008-12-19 19:13:09 +00001074 if (FromFunctionType && ToFunctionType) {
1075 // If the function types are exactly the same, this isn't an
1076 // Objective-C pointer conversion.
1077 if (Context.getCanonicalType(FromPointeeType)
1078 == Context.getCanonicalType(ToPointeeType))
1079 return false;
1080
1081 // Perform the quick checks that will tell us whether these
1082 // function types are obviously different.
1083 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1084 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1085 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1086 return false;
1087
1088 bool HasObjCConversion = false;
1089 if (Context.getCanonicalType(FromFunctionType->getResultType())
1090 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1091 // Okay, the types match exactly. Nothing to do.
1092 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1093 ToFunctionType->getResultType(),
1094 ConvertedType, IncompatibleObjC)) {
1095 // Okay, we have an Objective-C pointer conversion.
1096 HasObjCConversion = true;
1097 } else {
1098 // Function types are too different. Abort.
1099 return false;
1100 }
Mike Stump11289f42009-09-09 15:08:12 +00001101
Douglas Gregora119f102008-12-19 19:13:09 +00001102 // Check argument types.
1103 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1104 ArgIdx != NumArgs; ++ArgIdx) {
1105 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1106 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1107 if (Context.getCanonicalType(FromArgType)
1108 == Context.getCanonicalType(ToArgType)) {
1109 // Okay, the types match exactly. Nothing to do.
1110 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1111 ConvertedType, IncompatibleObjC)) {
1112 // Okay, we have an Objective-C pointer conversion.
1113 HasObjCConversion = true;
1114 } else {
1115 // Argument types are too different. Abort.
1116 return false;
1117 }
1118 }
1119
1120 if (HasObjCConversion) {
1121 // We had an Objective-C conversion. Allow this pointer
1122 // conversion, but complain about it.
1123 ConvertedType = ToType;
1124 IncompatibleObjC = true;
1125 return true;
1126 }
1127 }
1128
Sebastian Redl72b597d2009-01-25 19:43:20 +00001129 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001130}
1131
Douglas Gregor39c16d42008-10-24 04:54:22 +00001132/// CheckPointerConversion - Check the pointer conversion from the
1133/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001134/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001135/// conversions for which IsPointerConversion has already returned
1136/// true. It returns true and produces a diagnostic if there was an
1137/// error, or returns false otherwise.
1138bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1139 QualType FromType = From->getType();
1140
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001141 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1142 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001143 QualType FromPointeeType = FromPtrType->getPointeeType(),
1144 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001145
Douglas Gregor39c16d42008-10-24 04:54:22 +00001146 if (FromPointeeType->isRecordType() &&
1147 ToPointeeType->isRecordType()) {
1148 // We must have a derived-to-base conversion. Check an
1149 // ambiguous or inaccessible conversion.
Douglas Gregorcea4e7432008-10-24 16:17:19 +00001150 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1151 From->getExprLoc(),
1152 From->getSourceRange());
Douglas Gregor39c16d42008-10-24 04:54:22 +00001153 }
1154 }
Mike Stump11289f42009-09-09 15:08:12 +00001155 if (const ObjCObjectPointerType *FromPtrType =
Steve Naroff7cae42b2009-07-10 23:34:53 +00001156 FromType->getAsObjCObjectPointerType())
Mike Stump11289f42009-09-09 15:08:12 +00001157 if (const ObjCObjectPointerType *ToPtrType =
Steve Naroff7cae42b2009-07-10 23:34:53 +00001158 ToType->getAsObjCObjectPointerType()) {
1159 // Objective-C++ conversions are always okay.
1160 // FIXME: We should have a different class of conversions for the
1161 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001162 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001163 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001164
Steve Naroff7cae42b2009-07-10 23:34:53 +00001165 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001166 return false;
1167}
1168
Sebastian Redl72b597d2009-01-25 19:43:20 +00001169/// IsMemberPointerConversion - Determines whether the conversion of the
1170/// expression From, which has the (possibly adjusted) type FromType, can be
1171/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1172/// If so, returns true and places the converted type (that might differ from
1173/// ToType in its cv-qualifiers at some level) into ConvertedType.
1174bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Mike Stump11289f42009-09-09 15:08:12 +00001175 QualType ToType, QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001176 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001177 if (!ToTypePtr)
1178 return false;
1179
1180 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1181 if (From->isNullPointerConstant(Context)) {
1182 ConvertedType = ToType;
1183 return true;
1184 }
1185
1186 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001187 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001188 if (!FromTypePtr)
1189 return false;
1190
1191 // A pointer to member of B can be converted to a pointer to member of D,
1192 // where D is derived from B (C++ 4.11p2).
1193 QualType FromClass(FromTypePtr->getClass(), 0);
1194 QualType ToClass(ToTypePtr->getClass(), 0);
1195 // FIXME: What happens when these are dependent? Is this function even called?
1196
1197 if (IsDerivedFrom(ToClass, FromClass)) {
1198 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1199 ToClass.getTypePtr());
1200 return true;
1201 }
1202
1203 return false;
1204}
1205
1206/// CheckMemberPointerConversion - Check the member pointer conversion from the
1207/// expression From to the type ToType. This routine checks for ambiguous or
1208/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1209/// for which IsMemberPointerConversion has already returned true. It returns
1210/// true and produces a diagnostic if there was an error, or returns false
1211/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001212bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Anders Carlssond7923c62009-08-22 23:33:40 +00001213 CastExpr::CastKind &Kind) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001214 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001215 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001216 if (!FromPtrType) {
1217 // This must be a null pointer to member pointer conversion
Mike Stump11289f42009-09-09 15:08:12 +00001218 assert(From->isNullPointerConstant(Context) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001219 "Expr must be null pointer constant!");
1220 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001221 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001222 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001223
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001224 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001225 assert(ToPtrType && "No member pointer cast has a target type "
1226 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001227
Sebastian Redled8f2002009-01-28 18:33:18 +00001228 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1229 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001230
Sebastian Redled8f2002009-01-28 18:33:18 +00001231 // FIXME: What about dependent types?
1232 assert(FromClass->isRecordType() && "Pointer into non-class.");
1233 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001234
Sebastian Redled8f2002009-01-28 18:33:18 +00001235 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1236 /*DetectVirtual=*/true);
1237 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1238 assert(DerivationOkay &&
1239 "Should not have been called if derivation isn't OK.");
1240 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001241
Sebastian Redled8f2002009-01-28 18:33:18 +00001242 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1243 getUnqualifiedType())) {
1244 // Derivation is ambiguous. Redo the check to find the exact paths.
1245 Paths.clear();
1246 Paths.setRecordingPaths(true);
1247 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1248 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1249 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001250
Sebastian Redled8f2002009-01-28 18:33:18 +00001251 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1252 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1253 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1254 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001255 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001256
Douglas Gregor89ee6822009-02-28 01:32:25 +00001257 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001258 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1259 << FromClass << ToClass << QualType(VBase, 0)
1260 << From->getSourceRange();
1261 return true;
1262 }
1263
Anders Carlssond7923c62009-08-22 23:33:40 +00001264 // Must be a base to derived member conversion.
1265 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001266 return false;
1267}
1268
Douglas Gregor9a657932008-10-21 23:43:52 +00001269/// IsQualificationConversion - Determines whether the conversion from
1270/// an rvalue of type FromType to ToType is a qualification conversion
1271/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001272bool
1273Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001274 FromType = Context.getCanonicalType(FromType);
1275 ToType = Context.getCanonicalType(ToType);
1276
1277 // If FromType and ToType are the same type, this is not a
1278 // qualification conversion.
1279 if (FromType == ToType)
1280 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001281
Douglas Gregor9a657932008-10-21 23:43:52 +00001282 // (C++ 4.4p4):
1283 // A conversion can add cv-qualifiers at levels other than the first
1284 // in multi-level pointers, subject to the following rules: [...]
1285 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001286 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001287 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001288 // Within each iteration of the loop, we check the qualifiers to
1289 // determine if this still looks like a qualification
1290 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001291 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001292 // until there are no more pointers or pointers-to-members left to
1293 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001294 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001295
1296 // -- for every j > 0, if const is in cv 1,j then const is in cv
1297 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001298 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001299 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001300
Douglas Gregor9a657932008-10-21 23:43:52 +00001301 // -- if the cv 1,j and cv 2,j are different, then const is in
1302 // every cv for 0 < k < j.
1303 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001304 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001305 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001306
Douglas Gregor9a657932008-10-21 23:43:52 +00001307 // Keep track of whether all prior cv-qualifiers in the "to" type
1308 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001309 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001310 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001311 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001312
1313 // We are left with FromType and ToType being the pointee types
1314 // after unwrapping the original FromType and ToType the same number
1315 // of types. If we unwrapped any pointers, and if FromType and
1316 // ToType have the same unqualified type (since we checked
1317 // qualifiers above), then this is a qualification conversion.
1318 return UnwrappedAnyPointer &&
1319 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1320}
1321
Douglas Gregor05155d82009-08-21 23:19:43 +00001322/// \brief Given a function template or function, extract the function template
1323/// declaration (if any) and the underlying function declaration.
1324template<typename T>
1325static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1326 FunctionTemplateDecl *&FunctionTemplate) {
1327 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1328 if (FunctionTemplate)
1329 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1330 else
1331 Function = cast<T>(Orig);
1332}
1333
Douglas Gregor576e98c2009-01-30 23:27:23 +00001334/// Determines whether there is a user-defined conversion sequence
1335/// (C++ [over.ics.user]) that converts expression From to the type
1336/// ToType. If such a conversion exists, User will contain the
1337/// user-defined conversion sequence that performs such a conversion
1338/// and this routine will return true. Otherwise, this routine returns
1339/// false and User is unspecified.
1340///
1341/// \param AllowConversionFunctions true if the conversion should
1342/// consider conversion functions at all. If false, only constructors
1343/// will be considered.
1344///
1345/// \param AllowExplicit true if the conversion should consider C++0x
1346/// "explicit" conversion functions as well as non-explicit conversion
1347/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001348///
1349/// \param ForceRValue true if the expression should be treated as an rvalue
1350/// for overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00001351bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001352 UserDefinedConversionSequence& User,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001353 bool AllowConversionFunctions,
Mike Stump11289f42009-09-09 15:08:12 +00001354 bool AllowExplicit, bool ForceRValue) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001355 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001356 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001357 if (CXXRecordDecl *ToRecordDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001358 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1359 // C++ [over.match.ctor]p1:
1360 // When objects of class type are direct-initialized (8.5), or
1361 // copy-initialized from an expression of the same or a
1362 // derived class type (8.5), overload resolution selects the
1363 // constructor. [...] For copy-initialization, the candidate
1364 // functions are all the converting constructors (12.3.1) of
1365 // that class. The argument list is the expression-list within
1366 // the parentheses of the initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001367 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001368 = Context.DeclarationNames.getCXXConstructorName(
1369 Context.getCanonicalType(ToType).getUnqualifiedType());
1370 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001371 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001372 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001373 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001374 // Find the constructor (which may be a template).
1375 CXXConstructorDecl *Constructor = 0;
1376 FunctionTemplateDecl *ConstructorTmpl
1377 = dyn_cast<FunctionTemplateDecl>(*Con);
1378 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001379 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001380 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1381 else
1382 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump11289f42009-09-09 15:08:12 +00001383
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001384 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001385 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001386 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001387 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001388 1, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00001389 /*SuppressUserConversions=*/true,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001390 ForceRValue);
1391 else
1392 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1393 /*SuppressUserConversions=*/true, ForceRValue);
1394 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001395 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001396 }
1397 }
1398
Douglas Gregor576e98c2009-01-30 23:27:23 +00001399 if (!AllowConversionFunctions) {
1400 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001401 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1402 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001403 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001404 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001405 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001406 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001407 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001408 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1409 // Add all of the conversion functions as candidates.
1410 // FIXME: Look for conversions in base classes!
1411 OverloadedFunctionDecl *Conversions
1412 = FromRecordDecl->getConversionFunctions();
1413 for (OverloadedFunctionDecl::function_iterator Func
1414 = Conversions->function_begin();
1415 Func != Conversions->function_end(); ++Func) {
1416 CXXConversionDecl *Conv;
1417 FunctionTemplateDecl *ConvTemplate;
1418 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1419 if (ConvTemplate)
1420 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1421 else
1422 Conv = dyn_cast<CXXConversionDecl>(*Func);
1423
1424 if (AllowExplicit || !Conv->isExplicit()) {
1425 if (ConvTemplate)
1426 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1427 CandidateSet);
1428 else
1429 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1430 }
1431 }
1432 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001433 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001434
1435 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001436 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001437 case OR_Success:
1438 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001439 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001440 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1441 // C++ [over.ics.user]p1:
1442 // If the user-defined conversion is specified by a
1443 // constructor (12.3.1), the initial standard conversion
1444 // sequence converts the source type to the type required by
1445 // the argument of the constructor.
1446 //
1447 // FIXME: What about ellipsis conversions?
1448 QualType ThisType = Constructor->getThisType(Context);
1449 User.Before = Best->Conversions[0].Standard;
1450 User.ConversionFunction = Constructor;
1451 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001452 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001453 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001454 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1455 return true;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001456 } else if (CXXConversionDecl *Conversion
1457 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1458 // C++ [over.ics.user]p1:
1459 //
1460 // [...] If the user-defined conversion is specified by a
1461 // conversion function (12.3.2), the initial standard
1462 // conversion sequence converts the source type to the
1463 // implicit object parameter of the conversion function.
1464 User.Before = Best->Conversions[0].Standard;
1465 User.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00001466
1467 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001468 // The second standard conversion sequence converts the
1469 // result of the user-defined conversion to the target type
1470 // for the sequence. Since an implicit conversion sequence
1471 // is an initialization, the special rules for
1472 // initialization by user-defined conversion apply when
1473 // selecting the best user-defined conversion for a
1474 // user-defined conversion sequence (see 13.3.3 and
1475 // 13.3.3.1).
1476 User.After = Best->FinalConversion;
1477 return true;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001478 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001479 assert(false && "Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001480 return false;
1481 }
Mike Stump11289f42009-09-09 15:08:12 +00001482
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001483 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001484 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001485 // No conversion here! We're done.
1486 return false;
1487
1488 case OR_Ambiguous:
1489 // FIXME: See C++ [over.best.ics]p10 for the handling of
1490 // ambiguous conversion sequences.
1491 return false;
1492 }
1493
1494 return false;
1495}
1496
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001497/// CompareImplicitConversionSequences - Compare two implicit
1498/// conversion sequences to determine whether one is better than the
1499/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001500ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001501Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1502 const ImplicitConversionSequence& ICS2)
1503{
1504 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1505 // conversion sequences (as defined in 13.3.3.1)
1506 // -- a standard conversion sequence (13.3.3.1.1) is a better
1507 // conversion sequence than a user-defined conversion sequence or
1508 // an ellipsis conversion sequence, and
1509 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1510 // conversion sequence than an ellipsis conversion sequence
1511 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001512 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001513 if (ICS1.ConversionKind < ICS2.ConversionKind)
1514 return ImplicitConversionSequence::Better;
1515 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1516 return ImplicitConversionSequence::Worse;
1517
1518 // Two implicit conversion sequences of the same form are
1519 // indistinguishable conversion sequences unless one of the
1520 // following rules apply: (C++ 13.3.3.2p3):
1521 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1522 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001523 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001524 ImplicitConversionSequence::UserDefinedConversion) {
1525 // User-defined conversion sequence U1 is a better conversion
1526 // sequence than another user-defined conversion sequence U2 if
1527 // they contain the same user-defined conversion function or
1528 // constructor and if the second standard conversion sequence of
1529 // U1 is better than the second standard conversion sequence of
1530 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001531 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001532 ICS2.UserDefined.ConversionFunction)
1533 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1534 ICS2.UserDefined.After);
1535 }
1536
1537 return ImplicitConversionSequence::Indistinguishable;
1538}
1539
1540/// CompareStandardConversionSequences - Compare two standard
1541/// conversion sequences to determine whether one is better than the
1542/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001543ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001544Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1545 const StandardConversionSequence& SCS2)
1546{
1547 // Standard conversion sequence S1 is a better conversion sequence
1548 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1549
1550 // -- S1 is a proper subsequence of S2 (comparing the conversion
1551 // sequences in the canonical form defined by 13.3.3.1.1,
1552 // excluding any Lvalue Transformation; the identity conversion
1553 // sequence is considered to be a subsequence of any
1554 // non-identity conversion sequence) or, if not that,
1555 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1556 // Neither is a proper subsequence of the other. Do nothing.
1557 ;
1558 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1559 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001560 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001561 SCS1.Third == ICK_Identity))
1562 // SCS1 is a proper subsequence of SCS2.
1563 return ImplicitConversionSequence::Better;
1564 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1565 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001566 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001567 SCS2.Third == ICK_Identity))
1568 // SCS2 is a proper subsequence of SCS1.
1569 return ImplicitConversionSequence::Worse;
1570
1571 // -- the rank of S1 is better than the rank of S2 (by the rules
1572 // defined below), or, if not that,
1573 ImplicitConversionRank Rank1 = SCS1.getRank();
1574 ImplicitConversionRank Rank2 = SCS2.getRank();
1575 if (Rank1 < Rank2)
1576 return ImplicitConversionSequence::Better;
1577 else if (Rank2 < Rank1)
1578 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001579
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001580 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1581 // are indistinguishable unless one of the following rules
1582 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001583
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001584 // A conversion that is not a conversion of a pointer, or
1585 // pointer to member, to bool is better than another conversion
1586 // that is such a conversion.
1587 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1588 return SCS2.isPointerConversionToBool()
1589 ? ImplicitConversionSequence::Better
1590 : ImplicitConversionSequence::Worse;
1591
Douglas Gregor5c407d92008-10-23 00:40:37 +00001592 // C++ [over.ics.rank]p4b2:
1593 //
1594 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001595 // conversion of B* to A* is better than conversion of B* to
1596 // void*, and conversion of A* to void* is better than conversion
1597 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001598 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001599 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001600 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001601 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001602 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1603 // Exactly one of the conversion sequences is a conversion to
1604 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001605 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1606 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001607 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1608 // Neither conversion sequence converts to a void pointer; compare
1609 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001610 if (ImplicitConversionSequence::CompareKind DerivedCK
1611 = CompareDerivedToBaseConversions(SCS1, SCS2))
1612 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001613 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1614 // Both conversion sequences are conversions to void
1615 // pointers. Compare the source types to determine if there's an
1616 // inheritance relationship in their sources.
1617 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1618 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1619
1620 // Adjust the types we're converting from via the array-to-pointer
1621 // conversion, if we need to.
1622 if (SCS1.First == ICK_Array_To_Pointer)
1623 FromType1 = Context.getArrayDecayedType(FromType1);
1624 if (SCS2.First == ICK_Array_To_Pointer)
1625 FromType2 = Context.getArrayDecayedType(FromType2);
1626
Mike Stump11289f42009-09-09 15:08:12 +00001627 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001628 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001629 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001630 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001631
1632 if (IsDerivedFrom(FromPointee2, FromPointee1))
1633 return ImplicitConversionSequence::Better;
1634 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1635 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001636
1637 // Objective-C++: If one interface is more specific than the
1638 // other, it is the better one.
1639 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1640 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1641 if (FromIface1 && FromIface1) {
1642 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1643 return ImplicitConversionSequence::Better;
1644 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1645 return ImplicitConversionSequence::Worse;
1646 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001647 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001648
1649 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1650 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001651 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001652 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001653 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001654
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001655 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001656 // C++0x [over.ics.rank]p3b4:
1657 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1658 // implicit object parameter of a non-static member function declared
1659 // without a ref-qualifier, and S1 binds an rvalue reference to an
1660 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001661 // FIXME: We don't know if we're dealing with the implicit object parameter,
1662 // or if the member function in this case has a ref qualifier.
1663 // (Of course, we don't have ref qualifiers yet.)
1664 if (SCS1.RRefBinding != SCS2.RRefBinding)
1665 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1666 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001667
1668 // C++ [over.ics.rank]p3b4:
1669 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1670 // which the references refer are the same type except for
1671 // top-level cv-qualifiers, and the type to which the reference
1672 // initialized by S2 refers is more cv-qualified than the type
1673 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001674 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1675 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001676 T1 = Context.getCanonicalType(T1);
1677 T2 = Context.getCanonicalType(T2);
1678 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1679 if (T2.isMoreQualifiedThan(T1))
1680 return ImplicitConversionSequence::Better;
1681 else if (T1.isMoreQualifiedThan(T2))
1682 return ImplicitConversionSequence::Worse;
1683 }
1684 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001685
1686 return ImplicitConversionSequence::Indistinguishable;
1687}
1688
1689/// CompareQualificationConversions - Compares two standard conversion
1690/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001691/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1692ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001693Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001694 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001695 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001696 // -- S1 and S2 differ only in their qualification conversion and
1697 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1698 // cv-qualification signature of type T1 is a proper subset of
1699 // the cv-qualification signature of type T2, and S1 is not the
1700 // deprecated string literal array-to-pointer conversion (4.2).
1701 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1702 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1703 return ImplicitConversionSequence::Indistinguishable;
1704
1705 // FIXME: the example in the standard doesn't use a qualification
1706 // conversion (!)
1707 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1708 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1709 T1 = Context.getCanonicalType(T1);
1710 T2 = Context.getCanonicalType(T2);
1711
1712 // If the types are the same, we won't learn anything by unwrapped
1713 // them.
1714 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1715 return ImplicitConversionSequence::Indistinguishable;
1716
Mike Stump11289f42009-09-09 15:08:12 +00001717 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001718 = ImplicitConversionSequence::Indistinguishable;
1719 while (UnwrapSimilarPointerTypes(T1, T2)) {
1720 // Within each iteration of the loop, we check the qualifiers to
1721 // determine if this still looks like a qualification
1722 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001723 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001724 // until there are no more pointers or pointers-to-members left
1725 // to unwrap. This essentially mimics what
1726 // IsQualificationConversion does, but here we're checking for a
1727 // strict subset of qualifiers.
1728 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1729 // The qualifiers are the same, so this doesn't tell us anything
1730 // about how the sequences rank.
1731 ;
1732 else if (T2.isMoreQualifiedThan(T1)) {
1733 // T1 has fewer qualifiers, so it could be the better sequence.
1734 if (Result == ImplicitConversionSequence::Worse)
1735 // Neither has qualifiers that are a subset of the other's
1736 // qualifiers.
1737 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001738
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001739 Result = ImplicitConversionSequence::Better;
1740 } else if (T1.isMoreQualifiedThan(T2)) {
1741 // T2 has fewer qualifiers, so it could be the better sequence.
1742 if (Result == ImplicitConversionSequence::Better)
1743 // Neither has qualifiers that are a subset of the other's
1744 // qualifiers.
1745 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001746
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001747 Result = ImplicitConversionSequence::Worse;
1748 } else {
1749 // Qualifiers are disjoint.
1750 return ImplicitConversionSequence::Indistinguishable;
1751 }
1752
1753 // If the types after this point are equivalent, we're done.
1754 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1755 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001756 }
1757
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001758 // Check that the winning standard conversion sequence isn't using
1759 // the deprecated string literal array to pointer conversion.
1760 switch (Result) {
1761 case ImplicitConversionSequence::Better:
1762 if (SCS1.Deprecated)
1763 Result = ImplicitConversionSequence::Indistinguishable;
1764 break;
1765
1766 case ImplicitConversionSequence::Indistinguishable:
1767 break;
1768
1769 case ImplicitConversionSequence::Worse:
1770 if (SCS2.Deprecated)
1771 Result = ImplicitConversionSequence::Indistinguishable;
1772 break;
1773 }
1774
1775 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001776}
1777
Douglas Gregor5c407d92008-10-23 00:40:37 +00001778/// CompareDerivedToBaseConversions - Compares two standard conversion
1779/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001780/// various kinds of derived-to-base conversions (C++
1781/// [over.ics.rank]p4b3). As part of these checks, we also look at
1782/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001783ImplicitConversionSequence::CompareKind
1784Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1785 const StandardConversionSequence& SCS2) {
1786 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1787 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1788 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1789 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1790
1791 // Adjust the types we're converting from via the array-to-pointer
1792 // conversion, if we need to.
1793 if (SCS1.First == ICK_Array_To_Pointer)
1794 FromType1 = Context.getArrayDecayedType(FromType1);
1795 if (SCS2.First == ICK_Array_To_Pointer)
1796 FromType2 = Context.getArrayDecayedType(FromType2);
1797
1798 // Canonicalize all of the types.
1799 FromType1 = Context.getCanonicalType(FromType1);
1800 ToType1 = Context.getCanonicalType(ToType1);
1801 FromType2 = Context.getCanonicalType(FromType2);
1802 ToType2 = Context.getCanonicalType(ToType2);
1803
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001804 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001805 //
1806 // If class B is derived directly or indirectly from class A and
1807 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001808 //
1809 // For Objective-C, we let A, B, and C also be Objective-C
1810 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001811
1812 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001813 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001814 SCS2.Second == ICK_Pointer_Conversion &&
1815 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1816 FromType1->isPointerType() && FromType2->isPointerType() &&
1817 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001818 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001819 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001820 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001821 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001822 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001823 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001824 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001825 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001826
1827 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1828 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1829 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1830 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1831
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001832 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001833 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1834 if (IsDerivedFrom(ToPointee1, ToPointee2))
1835 return ImplicitConversionSequence::Better;
1836 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1837 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001838
1839 if (ToIface1 && ToIface2) {
1840 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1841 return ImplicitConversionSequence::Better;
1842 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1843 return ImplicitConversionSequence::Worse;
1844 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001845 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001846
1847 // -- conversion of B* to A* is better than conversion of C* to A*,
1848 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1849 if (IsDerivedFrom(FromPointee2, FromPointee1))
1850 return ImplicitConversionSequence::Better;
1851 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1852 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001853
Douglas Gregor237f96c2008-11-26 23:31:11 +00001854 if (FromIface1 && FromIface2) {
1855 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1856 return ImplicitConversionSequence::Better;
1857 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1858 return ImplicitConversionSequence::Worse;
1859 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001860 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001861 }
1862
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001863 // Compare based on reference bindings.
1864 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1865 SCS1.Second == ICK_Derived_To_Base) {
1866 // -- binding of an expression of type C to a reference of type
1867 // B& is better than binding an expression of type C to a
1868 // reference of type A&,
1869 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1870 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1871 if (IsDerivedFrom(ToType1, ToType2))
1872 return ImplicitConversionSequence::Better;
1873 else if (IsDerivedFrom(ToType2, ToType1))
1874 return ImplicitConversionSequence::Worse;
1875 }
1876
Douglas Gregor2fe98832008-11-03 19:09:14 +00001877 // -- binding of an expression of type B to a reference of type
1878 // A& is better than binding an expression of type C to a
1879 // reference of type A&,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001880 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1881 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1882 if (IsDerivedFrom(FromType2, FromType1))
1883 return ImplicitConversionSequence::Better;
1884 else if (IsDerivedFrom(FromType1, FromType2))
1885 return ImplicitConversionSequence::Worse;
1886 }
1887 }
1888
1889
1890 // FIXME: conversion of A::* to B::* is better than conversion of
1891 // A::* to C::*,
1892
1893 // FIXME: conversion of B::* to C::* is better than conversion of
1894 // A::* to C::*, and
1895
Douglas Gregor2fe98832008-11-03 19:09:14 +00001896 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1897 SCS1.Second == ICK_Derived_To_Base) {
1898 // -- conversion of C to B is better than conversion of C to A,
1899 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1900 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1901 if (IsDerivedFrom(ToType1, ToType2))
1902 return ImplicitConversionSequence::Better;
1903 else if (IsDerivedFrom(ToType2, ToType1))
1904 return ImplicitConversionSequence::Worse;
1905 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001906
Douglas Gregor2fe98832008-11-03 19:09:14 +00001907 // -- conversion of B to A is better than conversion of C to A.
1908 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1909 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1910 if (IsDerivedFrom(FromType2, FromType1))
1911 return ImplicitConversionSequence::Better;
1912 else if (IsDerivedFrom(FromType1, FromType2))
1913 return ImplicitConversionSequence::Worse;
1914 }
1915 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001916
Douglas Gregor5c407d92008-10-23 00:40:37 +00001917 return ImplicitConversionSequence::Indistinguishable;
1918}
1919
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001920/// TryCopyInitialization - Try to copy-initialize a value of type
1921/// ToType from the expression From. Return the implicit conversion
1922/// sequence required to pass this argument, which may be a bad
1923/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00001924/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00001925/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1926/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00001927ImplicitConversionSequence
1928Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00001929 bool SuppressUserConversions, bool ForceRValue,
1930 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001931 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001932 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00001933 CheckReferenceInit(From, ToType,
Anders Carlsson271e3a42009-08-27 17:30:43 +00001934 SuppressUserConversions,
1935 /*AllowExplicit=*/false,
1936 ForceRValue,
1937 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001938 return ICS;
1939 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001940 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001941 SuppressUserConversions,
1942 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001943 ForceRValue,
1944 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001945 }
1946}
1947
Sebastian Redl42e92c42009-04-12 17:16:29 +00001948/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1949/// the expression @p From. Returns true (and emits a diagnostic) if there was
1950/// an error, returns false if the initialization succeeded. Elidable should
1951/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1952/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00001953bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00001954 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001955 if (!getLangOptions().CPlusPlus) {
1956 // In C, argument passing is the same as performing an assignment.
1957 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001958
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001959 AssignConvertType ConvTy =
1960 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00001961 if (ConvTy != Compatible &&
1962 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1963 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00001964
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001965 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1966 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001967 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00001968
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001969 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00001970 return CheckReferenceInit(From, ToType,
1971 /*SuppressUserConversions=*/false,
1972 /*AllowExplicit=*/false,
1973 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001974
Sebastian Redl42e92c42009-04-12 17:16:29 +00001975 if (!PerformImplicitConversion(From, ToType, Flavor,
1976 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001977 return false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00001978
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001979 return Diag(From->getSourceRange().getBegin(),
1980 diag::err_typecheck_convert_incompatible)
1981 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001982}
1983
Douglas Gregor436424c2008-11-18 23:14:02 +00001984/// TryObjectArgumentInitialization - Try to initialize the object
1985/// parameter of the given member function (@c Method) from the
1986/// expression @p From.
1987ImplicitConversionSequence
1988Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1989 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1990 unsigned MethodQuals = Method->getTypeQualifiers();
1991 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1992
1993 // Set up the conversion sequence as a "bad" conversion, to allow us
1994 // to exit early.
1995 ImplicitConversionSequence ICS;
1996 ICS.Standard.setAsIdentityConversion();
1997 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1998
1999 // We need to have an object of class type.
2000 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002001 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002002 FromType = PT->getPointeeType();
2003
2004 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002005
2006 // The implicit object parmeter is has the type "reference to cv X",
2007 // where X is the class of which the function is a member
2008 // (C++ [over.match.funcs]p4). However, when finding an implicit
2009 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002010 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002011 // (C++ [over.match.funcs]p5). We perform a simplified version of
2012 // reference binding here, that allows class rvalues to bind to
2013 // non-constant references.
2014
2015 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2016 // with the implicit object parameter (C++ [over.match.funcs]p5).
2017 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2018 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2019 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2020 return ICS;
2021
2022 // Check that we have either the same type or a derived type. It
2023 // affects the conversion rank.
2024 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2025 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2026 ICS.Standard.Second = ICK_Identity;
2027 else if (IsDerivedFrom(FromType, ClassType))
2028 ICS.Standard.Second = ICK_Derived_To_Base;
2029 else
2030 return ICS;
2031
2032 // Success. Mark this as a reference binding.
2033 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2034 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2035 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2036 ICS.Standard.ReferenceBinding = true;
2037 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002038 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002039 return ICS;
2040}
2041
2042/// PerformObjectArgumentInitialization - Perform initialization of
2043/// the implicit object parameter for the given Method with the given
2044/// expression.
2045bool
2046Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002047 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002048 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002049 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002050
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002051 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002052 FromRecordType = PT->getPointeeType();
2053 DestType = Method->getThisType(Context);
2054 } else {
2055 FromRecordType = From->getType();
2056 DestType = ImplicitParamRecordType;
2057 }
2058
Mike Stump11289f42009-09-09 15:08:12 +00002059 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002060 = TryObjectArgumentInitialization(From, Method);
2061 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2062 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002063 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002064 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002065
Douglas Gregor436424c2008-11-18 23:14:02 +00002066 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002067 CheckDerivedToBaseConversion(FromRecordType,
2068 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002069 From->getSourceRange().getBegin(),
2070 From->getSourceRange()))
2071 return true;
2072
Mike Stump11289f42009-09-09 15:08:12 +00002073 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002074 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002075 return false;
2076}
2077
Douglas Gregor5fb53972009-01-14 15:45:31 +00002078/// TryContextuallyConvertToBool - Attempt to contextually convert the
2079/// expression From to bool (C++0x [conv]p3).
2080ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002081 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002082 // FIXME: Are these flags correct?
2083 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002084 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002085 /*ForceRValue=*/false,
2086 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002087}
2088
2089/// PerformContextuallyConvertToBool - Perform a contextual conversion
2090/// of the expression From to bool (C++0x [conv]p3).
2091bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2092 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2093 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2094 return false;
2095
Mike Stump11289f42009-09-09 15:08:12 +00002096 return Diag(From->getSourceRange().getBegin(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002097 diag::err_typecheck_bool_condition)
2098 << From->getType() << From->getSourceRange();
2099}
2100
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002101/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002102/// candidate functions, using the given function call arguments. If
2103/// @p SuppressUserConversions, then don't allow user-defined
2104/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002105/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2106/// hacky way to implement the overloading rules for elidable copy
2107/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002108void
2109Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002110 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002111 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002112 bool SuppressUserConversions,
Mike Stump11289f42009-09-09 15:08:12 +00002113 bool ForceRValue) {
2114 const FunctionProtoType* Proto
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002115 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002116 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002117 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002118 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002119 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002120 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002121
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002122 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002123 if (!isa<CXXConstructorDecl>(Method)) {
2124 // If we get here, it's because we're calling a member function
2125 // that is named without a member access expression (e.g.,
2126 // "this->f") that was either written explicitly or created
2127 // implicitly. This can happen with a qualified call to a member
2128 // function, e.g., X::f(). We use a NULL object as the implied
2129 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002130 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002131 SuppressUserConversions, ForceRValue);
2132 return;
2133 }
2134 // We treat a constructor like a non-member function, since its object
2135 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002136 }
2137
2138
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002139 // Add this candidate
2140 CandidateSet.push_back(OverloadCandidate());
2141 OverloadCandidate& Candidate = CandidateSet.back();
2142 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002143 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002144 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002145 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002146
2147 unsigned NumArgsInProto = Proto->getNumArgs();
2148
2149 // (C++ 13.3.2p2): A candidate function having fewer than m
2150 // parameters is viable only if it has an ellipsis in its parameter
2151 // list (8.3.5).
2152 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2153 Candidate.Viable = false;
2154 return;
2155 }
2156
2157 // (C++ 13.3.2p2): A candidate function having more than m parameters
2158 // is viable only if the (m+1)st parameter has a default argument
2159 // (8.3.6). For the purposes of overload resolution, the
2160 // parameter list is truncated on the right, so that there are
2161 // exactly m parameters.
2162 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2163 if (NumArgs < MinRequiredArgs) {
2164 // Not enough arguments.
2165 Candidate.Viable = false;
2166 return;
2167 }
2168
2169 // Determine the implicit conversion sequences for each of the
2170 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002171 Candidate.Conversions.resize(NumArgs);
2172 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2173 if (ArgIdx < NumArgsInProto) {
2174 // (C++ 13.3.2p3): for F to be a viable function, there shall
2175 // exist for each argument an implicit conversion sequence
2176 // (13.3.3.1) that converts that argument to the corresponding
2177 // parameter of F.
2178 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002179 Candidate.Conversions[ArgIdx]
2180 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002181 SuppressUserConversions, ForceRValue,
2182 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002183 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002184 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002185 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002186 break;
2187 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002188 } else {
2189 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2190 // argument for which there is no corresponding parameter is
2191 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002192 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002193 = ImplicitConversionSequence::EllipsisConversion;
2194 }
2195 }
2196}
2197
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002198/// \brief Add all of the function declarations in the given function set to
2199/// the overload canddiate set.
2200void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2201 Expr **Args, unsigned NumArgs,
2202 OverloadCandidateSet& CandidateSet,
2203 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002204 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002205 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002206 F != FEnd; ++F) {
2207 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
Mike Stump11289f42009-09-09 15:08:12 +00002208 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002209 SuppressUserConversions);
2210 else
Douglas Gregor89026b52009-06-30 23:57:56 +00002211 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2212 /*FIXME: explicit args */false, 0, 0,
Mike Stump11289f42009-09-09 15:08:12 +00002213 Args, NumArgs, CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002214 SuppressUserConversions);
2215 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002216}
2217
Douglas Gregor436424c2008-11-18 23:14:02 +00002218/// AddMethodCandidate - Adds the given C++ member function to the set
2219/// of candidate functions, using the given function call arguments
2220/// and the object argument (@c Object). For example, in a call
2221/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2222/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2223/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002224/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2225/// a slightly hacky way to implement the overloading rules for elidable copy
2226/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002227void
Douglas Gregor436424c2008-11-18 23:14:02 +00002228Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2229 Expr **Args, unsigned NumArgs,
2230 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002231 bool SuppressUserConversions, bool ForceRValue) {
2232 const FunctionProtoType* Proto
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002233 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002234 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002235 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002236 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002237 assert(!isa<CXXConstructorDecl>(Method) &&
2238 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002239
2240 // Add this candidate
2241 CandidateSet.push_back(OverloadCandidate());
2242 OverloadCandidate& Candidate = CandidateSet.back();
2243 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002244 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002245 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002246
2247 unsigned NumArgsInProto = Proto->getNumArgs();
2248
2249 // (C++ 13.3.2p2): A candidate function having fewer than m
2250 // parameters is viable only if it has an ellipsis in its parameter
2251 // list (8.3.5).
2252 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2253 Candidate.Viable = false;
2254 return;
2255 }
2256
2257 // (C++ 13.3.2p2): A candidate function having more than m parameters
2258 // is viable only if the (m+1)st parameter has a default argument
2259 // (8.3.6). For the purposes of overload resolution, the
2260 // parameter list is truncated on the right, so that there are
2261 // exactly m parameters.
2262 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2263 if (NumArgs < MinRequiredArgs) {
2264 // Not enough arguments.
2265 Candidate.Viable = false;
2266 return;
2267 }
2268
2269 Candidate.Viable = true;
2270 Candidate.Conversions.resize(NumArgs + 1);
2271
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002272 if (Method->isStatic() || !Object)
2273 // The implicit object argument is ignored.
2274 Candidate.IgnoreObjectArgument = true;
2275 else {
2276 // Determine the implicit conversion sequence for the object
2277 // parameter.
2278 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002279 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002280 == ImplicitConversionSequence::BadConversion) {
2281 Candidate.Viable = false;
2282 return;
2283 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002284 }
2285
2286 // Determine the implicit conversion sequences for each of the
2287 // arguments.
2288 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2289 if (ArgIdx < NumArgsInProto) {
2290 // (C++ 13.3.2p3): for F to be a viable function, there shall
2291 // exist for each argument an implicit conversion sequence
2292 // (13.3.3.1) that converts that argument to the corresponding
2293 // parameter of F.
2294 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002295 Candidate.Conversions[ArgIdx + 1]
2296 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002297 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002298 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002299 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002300 == ImplicitConversionSequence::BadConversion) {
2301 Candidate.Viable = false;
2302 break;
2303 }
2304 } else {
2305 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2306 // argument for which there is no corresponding parameter is
2307 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002308 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002309 = ImplicitConversionSequence::EllipsisConversion;
2310 }
2311 }
2312}
2313
Douglas Gregor97628d62009-08-21 00:16:32 +00002314/// \brief Add a C++ member function template as a candidate to the candidate
2315/// set, using template argument deduction to produce an appropriate member
2316/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002317void
Douglas Gregor97628d62009-08-21 00:16:32 +00002318Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2319 bool HasExplicitTemplateArgs,
2320 const TemplateArgument *ExplicitTemplateArgs,
2321 unsigned NumExplicitTemplateArgs,
2322 Expr *Object, Expr **Args, unsigned NumArgs,
2323 OverloadCandidateSet& CandidateSet,
2324 bool SuppressUserConversions,
2325 bool ForceRValue) {
2326 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002327 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002328 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002329 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002330 // candidate functions in the usual way.113) A given name can refer to one
2331 // or more function templates and also to a set of overloaded non-template
2332 // functions. In such a case, the candidate functions generated from each
2333 // function template are combined with the set of non-template candidate
2334 // functions.
2335 TemplateDeductionInfo Info(Context);
2336 FunctionDecl *Specialization = 0;
2337 if (TemplateDeductionResult Result
2338 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2339 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2340 Args, NumArgs, Specialization, Info)) {
2341 // FIXME: Record what happened with template argument deduction, so
2342 // that we can give the user a beautiful diagnostic.
2343 (void)Result;
2344 return;
2345 }
Mike Stump11289f42009-09-09 15:08:12 +00002346
Douglas Gregor97628d62009-08-21 00:16:32 +00002347 // Add the function template specialization produced by template argument
2348 // deduction as a candidate.
2349 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002350 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002351 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002352 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002353 CandidateSet, SuppressUserConversions, ForceRValue);
2354}
2355
Douglas Gregor05155d82009-08-21 23:19:43 +00002356/// \brief Add a C++ function template specialization as a candidate
2357/// in the candidate set, using template argument deduction to produce
2358/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002359void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002360Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor89026b52009-06-30 23:57:56 +00002361 bool HasExplicitTemplateArgs,
2362 const TemplateArgument *ExplicitTemplateArgs,
2363 unsigned NumExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002364 Expr **Args, unsigned NumArgs,
2365 OverloadCandidateSet& CandidateSet,
2366 bool SuppressUserConversions,
2367 bool ForceRValue) {
2368 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002369 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002370 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002371 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002372 // candidate functions in the usual way.113) A given name can refer to one
2373 // or more function templates and also to a set of overloaded non-template
2374 // functions. In such a case, the candidate functions generated from each
2375 // function template are combined with the set of non-template candidate
2376 // functions.
2377 TemplateDeductionInfo Info(Context);
2378 FunctionDecl *Specialization = 0;
2379 if (TemplateDeductionResult Result
Douglas Gregor89026b52009-06-30 23:57:56 +00002380 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2381 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2382 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002383 // FIXME: Record what happened with template argument deduction, so
2384 // that we can give the user a beautiful diagnostic.
2385 (void)Result;
2386 return;
2387 }
Mike Stump11289f42009-09-09 15:08:12 +00002388
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002389 // Add the function template specialization produced by template argument
2390 // deduction as a candidate.
2391 assert(Specialization && "Missing function template specialization?");
2392 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2393 SuppressUserConversions, ForceRValue);
2394}
Mike Stump11289f42009-09-09 15:08:12 +00002395
Douglas Gregora1f013e2008-11-07 22:36:19 +00002396/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002397/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002398/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002399/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002400/// (which may or may not be the same type as the type that the
2401/// conversion function produces).
2402void
2403Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2404 Expr *From, QualType ToType,
2405 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002406 assert(!Conversion->getDescribedFunctionTemplate() &&
2407 "Conversion function templates use AddTemplateConversionCandidate");
2408
Douglas Gregora1f013e2008-11-07 22:36:19 +00002409 // Add this candidate
2410 CandidateSet.push_back(OverloadCandidate());
2411 OverloadCandidate& Candidate = CandidateSet.back();
2412 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002413 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002414 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002415 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002416 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002417 = Conversion->getConversionType().getAsOpaquePtr();
2418 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2419
Douglas Gregor436424c2008-11-18 23:14:02 +00002420 // Determine the implicit conversion sequence for the implicit
2421 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002422 Candidate.Viable = true;
2423 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002424 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregora1f013e2008-11-07 22:36:19 +00002425
Mike Stump11289f42009-09-09 15:08:12 +00002426 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002427 == ImplicitConversionSequence::BadConversion) {
2428 Candidate.Viable = false;
2429 return;
2430 }
2431
2432 // To determine what the conversion from the result of calling the
2433 // conversion function to the type we're eventually trying to
2434 // convert to (ToType), we need to synthesize a call to the
2435 // conversion function and attempt copy initialization from it. This
2436 // makes sure that we get the right semantics with respect to
2437 // lvalues/rvalues and the type. Fortunately, we can allocate this
2438 // call on the stack and we don't need its arguments to be
2439 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002440 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregora1f013e2008-11-07 22:36:19 +00002441 SourceLocation());
2442 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlssona2615922009-07-31 00:48:10 +00002443 CastExpr::CK_Unknown,
Douglas Gregora11693b2008-11-12 17:17:38 +00002444 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002445
2446 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002447 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2448 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002449 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002450 Conversion->getConversionType().getNonReferenceType(),
2451 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002452 ImplicitConversionSequence ICS =
2453 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002454 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002455 /*ForceRValue=*/false,
2456 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002457
Douglas Gregora1f013e2008-11-07 22:36:19 +00002458 switch (ICS.ConversionKind) {
2459 case ImplicitConversionSequence::StandardConversion:
2460 Candidate.FinalConversion = ICS.Standard;
2461 break;
2462
2463 case ImplicitConversionSequence::BadConversion:
2464 Candidate.Viable = false;
2465 break;
2466
2467 default:
Mike Stump11289f42009-09-09 15:08:12 +00002468 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002469 "Can only end up with a standard conversion sequence or failure");
2470 }
2471}
2472
Douglas Gregor05155d82009-08-21 23:19:43 +00002473/// \brief Adds a conversion function template specialization
2474/// candidate to the overload set, using template argument deduction
2475/// to deduce the template arguments of the conversion function
2476/// template from the type that we are converting to (C++
2477/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002478void
Douglas Gregor05155d82009-08-21 23:19:43 +00002479Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2480 Expr *From, QualType ToType,
2481 OverloadCandidateSet &CandidateSet) {
2482 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2483 "Only conversion function templates permitted here");
2484
2485 TemplateDeductionInfo Info(Context);
2486 CXXConversionDecl *Specialization = 0;
2487 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002488 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002489 Specialization, Info)) {
2490 // FIXME: Record what happened with template argument deduction, so
2491 // that we can give the user a beautiful diagnostic.
2492 (void)Result;
2493 return;
2494 }
Mike Stump11289f42009-09-09 15:08:12 +00002495
Douglas Gregor05155d82009-08-21 23:19:43 +00002496 // Add the conversion function template specialization produced by
2497 // template argument deduction as a candidate.
2498 assert(Specialization && "Missing function template specialization?");
2499 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2500}
2501
Douglas Gregorab7897a2008-11-19 22:57:39 +00002502/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2503/// converts the given @c Object to a function pointer via the
2504/// conversion function @c Conversion, and then attempts to call it
2505/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2506/// the type of function that we'll eventually be calling.
2507void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002508 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002509 Expr *Object, Expr **Args, unsigned NumArgs,
2510 OverloadCandidateSet& CandidateSet) {
2511 CandidateSet.push_back(OverloadCandidate());
2512 OverloadCandidate& Candidate = CandidateSet.back();
2513 Candidate.Function = 0;
2514 Candidate.Surrogate = Conversion;
2515 Candidate.Viable = true;
2516 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002517 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002518 Candidate.Conversions.resize(NumArgs + 1);
2519
2520 // Determine the implicit conversion sequence for the implicit
2521 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002522 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002523 = TryObjectArgumentInitialization(Object, Conversion);
2524 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2525 Candidate.Viable = false;
2526 return;
2527 }
2528
2529 // The first conversion is actually a user-defined conversion whose
2530 // first conversion is ObjectInit's standard conversion (which is
2531 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002532 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002533 = ImplicitConversionSequence::UserDefinedConversion;
2534 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2535 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002536 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002537 = Candidate.Conversions[0].UserDefined.Before;
2538 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2539
Mike Stump11289f42009-09-09 15:08:12 +00002540 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002541 unsigned NumArgsInProto = Proto->getNumArgs();
2542
2543 // (C++ 13.3.2p2): A candidate function having fewer than m
2544 // parameters is viable only if it has an ellipsis in its parameter
2545 // list (8.3.5).
2546 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2547 Candidate.Viable = false;
2548 return;
2549 }
2550
2551 // Function types don't have any default arguments, so just check if
2552 // we have enough arguments.
2553 if (NumArgs < NumArgsInProto) {
2554 // Not enough arguments.
2555 Candidate.Viable = false;
2556 return;
2557 }
2558
2559 // Determine the implicit conversion sequences for each of the
2560 // arguments.
2561 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2562 if (ArgIdx < NumArgsInProto) {
2563 // (C++ 13.3.2p3): for F to be a viable function, there shall
2564 // exist for each argument an implicit conversion sequence
2565 // (13.3.3.1) that converts that argument to the corresponding
2566 // parameter of F.
2567 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002568 Candidate.Conversions[ArgIdx + 1]
2569 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002570 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002571 /*ForceRValue=*/false,
2572 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002573 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002574 == ImplicitConversionSequence::BadConversion) {
2575 Candidate.Viable = false;
2576 break;
2577 }
2578 } else {
2579 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2580 // argument for which there is no corresponding parameter is
2581 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002582 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002583 = ImplicitConversionSequence::EllipsisConversion;
2584 }
2585 }
2586}
2587
Mike Stump87c57ac2009-05-16 07:39:55 +00002588// FIXME: This will eventually be removed, once we've migrated all of the
2589// operator overloading logic over to the scheme used by binary operators, which
2590// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002591void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002592 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002593 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002594 OverloadCandidateSet& CandidateSet,
2595 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002596
2597 FunctionSet Functions;
2598
2599 QualType T1 = Args[0]->getType();
2600 QualType T2;
2601 if (NumArgs > 1)
2602 T2 = Args[1]->getType();
2603
2604 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002605 if (S)
2606 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002607 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2608 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2609 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2610 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2611}
2612
2613/// \brief Add overload candidates for overloaded operators that are
2614/// member functions.
2615///
2616/// Add the overloaded operator candidates that are member functions
2617/// for the operator Op that was used in an operator expression such
2618/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2619/// CandidateSet will store the added overload candidates. (C++
2620/// [over.match.oper]).
2621void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2622 SourceLocation OpLoc,
2623 Expr **Args, unsigned NumArgs,
2624 OverloadCandidateSet& CandidateSet,
2625 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002626 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2627
2628 // C++ [over.match.oper]p3:
2629 // For a unary operator @ with an operand of a type whose
2630 // cv-unqualified version is T1, and for a binary operator @ with
2631 // a left operand of a type whose cv-unqualified version is T1 and
2632 // a right operand of a type whose cv-unqualified version is T2,
2633 // three sets of candidate functions, designated member
2634 // candidates, non-member candidates and built-in candidates, are
2635 // constructed as follows:
2636 QualType T1 = Args[0]->getType();
2637 QualType T2;
2638 if (NumArgs > 1)
2639 T2 = Args[1]->getType();
2640
2641 // -- If T1 is a class type, the set of member candidates is the
2642 // result of the qualified lookup of T1::operator@
2643 // (13.3.1.1.1); otherwise, the set of member candidates is
2644 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002645 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002646 // Complete the type if it can be completed. Otherwise, we're done.
2647 if (RequireCompleteType(OpLoc, T1, PartialDiagnostic(0)))
2648 return;
Mike Stump11289f42009-09-09 15:08:12 +00002649
2650 LookupResult Operators = LookupQualifiedName(T1Rec->getDecl(), OpName,
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002651 LookupOrdinaryName, false);
Mike Stump11289f42009-09-09 15:08:12 +00002652 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002653 OperEnd = Operators.end();
2654 Oper != OperEnd;
2655 ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00002656 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
Douglas Gregor55297ac2008-12-23 00:26:44 +00002657 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor436424c2008-11-18 23:14:02 +00002658 /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002659 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002660}
2661
Douglas Gregora11693b2008-11-12 17:17:38 +00002662/// AddBuiltinCandidate - Add a candidate for a built-in
2663/// operator. ResultTy and ParamTys are the result and parameter types
2664/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002665/// arguments being passed to the candidate. IsAssignmentOperator
2666/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002667/// operator. NumContextualBoolArguments is the number of arguments
2668/// (at the beginning of the argument list) that will be contextually
2669/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002670void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002671 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002672 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002673 bool IsAssignmentOperator,
2674 unsigned NumContextualBoolArguments) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002675 // Add this candidate
2676 CandidateSet.push_back(OverloadCandidate());
2677 OverloadCandidate& Candidate = CandidateSet.back();
2678 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002679 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002680 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002681 Candidate.BuiltinTypes.ResultTy = ResultTy;
2682 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2683 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2684
2685 // Determine the implicit conversion sequences for each of the
2686 // arguments.
2687 Candidate.Viable = true;
2688 Candidate.Conversions.resize(NumArgs);
2689 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002690 // C++ [over.match.oper]p4:
2691 // For the built-in assignment operators, conversions of the
2692 // left operand are restricted as follows:
2693 // -- no temporaries are introduced to hold the left operand, and
2694 // -- no user-defined conversions are applied to the left
2695 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002696 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002697 //
2698 // We block these conversions by turning off user-defined
2699 // conversions, since that is the only way that initialization of
2700 // a reference to a non-class type can occur from something that
2701 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002702 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002703 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002704 "Contextual conversion to bool requires bool type");
2705 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2706 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002707 Candidate.Conversions[ArgIdx]
2708 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002709 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002710 /*ForceRValue=*/false,
2711 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002712 }
Mike Stump11289f42009-09-09 15:08:12 +00002713 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002714 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002715 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002716 break;
2717 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002718 }
2719}
2720
2721/// BuiltinCandidateTypeSet - A set of types that will be used for the
2722/// candidate operator functions for built-in operators (C++
2723/// [over.built]). The types are separated into pointer types and
2724/// enumeration types.
2725class BuiltinCandidateTypeSet {
2726 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002727 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002728
2729 /// PointerTypes - The set of pointer types that will be used in the
2730 /// built-in candidates.
2731 TypeSet PointerTypes;
2732
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002733 /// MemberPointerTypes - The set of member pointer types that will be
2734 /// used in the built-in candidates.
2735 TypeSet MemberPointerTypes;
2736
Douglas Gregora11693b2008-11-12 17:17:38 +00002737 /// EnumerationTypes - The set of enumeration types that will be
2738 /// used in the built-in candidates.
2739 TypeSet EnumerationTypes;
2740
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002741 /// Sema - The semantic analysis instance where we are building the
2742 /// candidate type set.
2743 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002744
Douglas Gregora11693b2008-11-12 17:17:38 +00002745 /// Context - The AST context in which we will build the type sets.
2746 ASTContext &Context;
2747
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002748 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2749 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002750
2751public:
2752 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002753 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002754
Mike Stump11289f42009-09-09 15:08:12 +00002755 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002756 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002757
Douglas Gregor5fb53972009-01-14 15:45:31 +00002758 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2759 bool AllowExplicitConversions);
Douglas Gregora11693b2008-11-12 17:17:38 +00002760
2761 /// pointer_begin - First pointer type found;
2762 iterator pointer_begin() { return PointerTypes.begin(); }
2763
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002764 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002765 iterator pointer_end() { return PointerTypes.end(); }
2766
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002767 /// member_pointer_begin - First member pointer type found;
2768 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2769
2770 /// member_pointer_end - Past the last member pointer type found;
2771 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2772
Douglas Gregora11693b2008-11-12 17:17:38 +00002773 /// enumeration_begin - First enumeration type found;
2774 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2775
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002776 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002777 iterator enumeration_end() { return EnumerationTypes.end(); }
2778};
2779
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002780/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00002781/// the set of pointer types along with any more-qualified variants of
2782/// that type. For example, if @p Ty is "int const *", this routine
2783/// will add "int const *", "int const volatile *", "int const
2784/// restrict *", and "int const volatile restrict *" to the set of
2785/// pointer types. Returns true if the add of @p Ty itself succeeded,
2786/// false otherwise.
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002787bool
2788BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002789 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002790 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002791 return false;
2792
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002793 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002794 QualType PointeeTy = PointerTy->getPointeeType();
2795 // FIXME: Optimize this so that we don't keep trying to add the same types.
2796
Mike Stump87c57ac2009-05-16 07:39:55 +00002797 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2798 // pointer conversions that don't cast away constness?
Douglas Gregora11693b2008-11-12 17:17:38 +00002799 if (!PointeeTy.isConstQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002800 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002801 (Context.getPointerType(PointeeTy.withConst()));
2802 if (!PointeeTy.isVolatileQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002803 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002804 (Context.getPointerType(PointeeTy.withVolatile()));
2805 if (!PointeeTy.isRestrictQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002806 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002807 (Context.getPointerType(PointeeTy.withRestrict()));
2808 }
2809
2810 return true;
2811}
2812
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002813/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2814/// to the set of pointer types along with any more-qualified variants of
2815/// that type. For example, if @p Ty is "int const *", this routine
2816/// will add "int const *", "int const volatile *", "int const
2817/// restrict *", and "int const volatile restrict *" to the set of
2818/// pointer types. Returns true if the add of @p Ty itself succeeded,
2819/// false otherwise.
2820bool
2821BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2822 QualType Ty) {
2823 // Insert this type.
2824 if (!MemberPointerTypes.insert(Ty))
2825 return false;
2826
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002827 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002828 QualType PointeeTy = PointerTy->getPointeeType();
2829 const Type *ClassTy = PointerTy->getClass();
2830 // FIXME: Optimize this so that we don't keep trying to add the same types.
2831
2832 if (!PointeeTy.isConstQualified())
2833 AddMemberPointerWithMoreQualifiedTypeVariants
2834 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2835 if (!PointeeTy.isVolatileQualified())
2836 AddMemberPointerWithMoreQualifiedTypeVariants
2837 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2838 if (!PointeeTy.isRestrictQualified())
2839 AddMemberPointerWithMoreQualifiedTypeVariants
2840 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2841 }
2842
2843 return true;
2844}
2845
Douglas Gregora11693b2008-11-12 17:17:38 +00002846/// AddTypesConvertedFrom - Add each of the types to which the type @p
2847/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002848/// primarily interested in pointer types and enumeration types. We also
2849/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002850/// AllowUserConversions is true if we should look at the conversion
2851/// functions of a class type, and AllowExplicitConversions if we
2852/// should also include the explicit conversion functions of a class
2853/// type.
Mike Stump11289f42009-09-09 15:08:12 +00002854void
Douglas Gregor5fb53972009-01-14 15:45:31 +00002855BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2856 bool AllowUserConversions,
2857 bool AllowExplicitConversions) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002858 // Only deal with canonical types.
2859 Ty = Context.getCanonicalType(Ty);
2860
2861 // Look through reference types; they aren't part of the type of an
2862 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002863 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00002864 Ty = RefTy->getPointeeType();
2865
2866 // We don't care about qualifiers on the type.
2867 Ty = Ty.getUnqualifiedType();
2868
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002869 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002870 QualType PointeeTy = PointerTy->getPointeeType();
2871
2872 // Insert our type, and its more-qualified variants, into the set
2873 // of types.
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002874 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002875 return;
2876
2877 // Add 'cv void*' to our set of types.
2878 if (!Ty->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002879 QualType QualVoid
Douglas Gregora11693b2008-11-12 17:17:38 +00002880 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002881 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregora11693b2008-11-12 17:17:38 +00002882 }
2883
2884 // If this is a pointer to a class type, add pointers to its bases
2885 // (with the same level of cv-qualification as the original
2886 // derived class, of course).
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002887 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002888 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2889 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2890 Base != ClassDecl->bases_end(); ++Base) {
2891 QualType BaseTy = Context.getCanonicalType(Base->getType());
2892 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2893
2894 // Add the pointer type, recursively, so that we get all of
2895 // the indirect base classes, too.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002896 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00002897 }
2898 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002899 } else if (Ty->isMemberPointerType()) {
2900 // Member pointers are far easier, since the pointee can't be converted.
2901 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2902 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00002903 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00002904 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002905 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002906 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002907 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2908 // No conversion functions in incomplete types.
2909 return;
2910 }
Mike Stump11289f42009-09-09 15:08:12 +00002911
Douglas Gregora11693b2008-11-12 17:17:38 +00002912 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2913 // FIXME: Visit conversion functions in the base classes, too.
Mike Stump11289f42009-09-09 15:08:12 +00002914 OverloadedFunctionDecl *Conversions
Douglas Gregora11693b2008-11-12 17:17:38 +00002915 = ClassDecl->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00002916 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregora11693b2008-11-12 17:17:38 +00002917 = Conversions->function_begin();
2918 Func != Conversions->function_end(); ++Func) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002919 CXXConversionDecl *Conv;
2920 FunctionTemplateDecl *ConvTemplate;
2921 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2922
Mike Stump11289f42009-09-09 15:08:12 +00002923 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00002924 // about which builtin types we can convert to.
2925 if (ConvTemplate)
2926 continue;
2927
Douglas Gregor5fb53972009-01-14 15:45:31 +00002928 if (AllowExplicitConversions || !Conv->isExplicit())
2929 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00002930 }
2931 }
2932 }
2933}
2934
Douglas Gregor84605ae2009-08-24 13:43:27 +00002935/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2936/// the volatile- and non-volatile-qualified assignment operators for the
2937/// given type to the candidate set.
2938static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2939 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00002940 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00002941 unsigned NumArgs,
2942 OverloadCandidateSet &CandidateSet) {
2943 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002944
Douglas Gregor84605ae2009-08-24 13:43:27 +00002945 // T& operator=(T&, T)
2946 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2947 ParamTypes[1] = T;
2948 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2949 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002950
Douglas Gregor84605ae2009-08-24 13:43:27 +00002951 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2952 // volatile T& operator=(volatile T&, T)
2953 ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
2954 ParamTypes[1] = T;
2955 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002956 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00002957 }
2958}
Mike Stump11289f42009-09-09 15:08:12 +00002959
Douglas Gregord08452f2008-11-19 15:42:04 +00002960/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2961/// operator overloads to the candidate set (C++ [over.built]), based
2962/// on the operator @p Op and the arguments given. For example, if the
2963/// operator is a binary '+', this routine might add "int
2964/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00002965void
Mike Stump11289f42009-09-09 15:08:12 +00002966Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregord08452f2008-11-19 15:42:04 +00002967 Expr **Args, unsigned NumArgs,
2968 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002969 // The set of "promoted arithmetic types", which are the arithmetic
2970 // types are that preserved by promotion (C++ [over.built]p2). Note
2971 // that the first few of these types are the promoted integral
2972 // types; these types need to be first.
2973 // FIXME: What about complex?
2974 const unsigned FirstIntegralType = 0;
2975 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00002976 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00002977 LastPromotedIntegralType = 13;
2978 const unsigned FirstPromotedArithmeticType = 7,
2979 LastPromotedArithmeticType = 16;
2980 const unsigned NumArithmeticTypes = 16;
2981 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00002982 Context.BoolTy, Context.CharTy, Context.WCharTy,
2983// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00002984 Context.SignedCharTy, Context.ShortTy,
2985 Context.UnsignedCharTy, Context.UnsignedShortTy,
2986 Context.IntTy, Context.LongTy, Context.LongLongTy,
2987 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2988 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2989 };
2990
2991 // Find all of the types that the arguments can convert to, but only
2992 // if the operator we're looking at has built-in operator candidates
2993 // that make use of these types.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002994 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00002995 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2996 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00002997 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00002998 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00002999 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003000 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003001 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003002 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3003 true,
3004 (Op == OO_Exclaim ||
3005 Op == OO_AmpAmp ||
3006 Op == OO_PipePipe));
Douglas Gregora11693b2008-11-12 17:17:38 +00003007 }
3008
3009 bool isComparison = false;
3010 switch (Op) {
3011 case OO_None:
3012 case NUM_OVERLOADED_OPERATORS:
3013 assert(false && "Expected an overloaded operator");
3014 break;
3015
Douglas Gregord08452f2008-11-19 15:42:04 +00003016 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003017 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003018 goto UnaryStar;
3019 else
3020 goto BinaryStar;
3021 break;
3022
3023 case OO_Plus: // '+' is either unary or binary
3024 if (NumArgs == 1)
3025 goto UnaryPlus;
3026 else
3027 goto BinaryPlus;
3028 break;
3029
3030 case OO_Minus: // '-' is either unary or binary
3031 if (NumArgs == 1)
3032 goto UnaryMinus;
3033 else
3034 goto BinaryMinus;
3035 break;
3036
3037 case OO_Amp: // '&' is either unary or binary
3038 if (NumArgs == 1)
3039 goto UnaryAmp;
3040 else
3041 goto BinaryAmp;
3042
3043 case OO_PlusPlus:
3044 case OO_MinusMinus:
3045 // C++ [over.built]p3:
3046 //
3047 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3048 // is either volatile or empty, there exist candidate operator
3049 // functions of the form
3050 //
3051 // VQ T& operator++(VQ T&);
3052 // T operator++(VQ T&, int);
3053 //
3054 // C++ [over.built]p4:
3055 //
3056 // For every pair (T, VQ), where T is an arithmetic type other
3057 // than bool, and VQ is either volatile or empty, there exist
3058 // candidate operator functions of the form
3059 //
3060 // VQ T& operator--(VQ T&);
3061 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003062 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003063 Arith < NumArithmeticTypes; ++Arith) {
3064 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003065 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003066 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003067
3068 // Non-volatile version.
3069 if (NumArgs == 1)
3070 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3071 else
3072 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3073
3074 // Volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003075 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregord08452f2008-11-19 15:42:04 +00003076 if (NumArgs == 1)
3077 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3078 else
3079 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3080 }
3081
3082 // C++ [over.built]p5:
3083 //
3084 // For every pair (T, VQ), where T is a cv-qualified or
3085 // cv-unqualified object type, and VQ is either volatile or
3086 // empty, there exist candidate operator functions of the form
3087 //
3088 // T*VQ& operator++(T*VQ&);
3089 // T*VQ& operator--(T*VQ&);
3090 // T* operator++(T*VQ&, int);
3091 // T* operator--(T*VQ&, int);
3092 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3093 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3094 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003095 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003096 continue;
3097
Mike Stump11289f42009-09-09 15:08:12 +00003098 QualType ParamTypes[2] = {
3099 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003100 };
Mike Stump11289f42009-09-09 15:08:12 +00003101
Douglas Gregord08452f2008-11-19 15:42:04 +00003102 // Without volatile
3103 if (NumArgs == 1)
3104 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3105 else
3106 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3107
3108 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3109 // With volatile
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003110 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregord08452f2008-11-19 15:42:04 +00003111 if (NumArgs == 1)
3112 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3113 else
3114 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3115 }
3116 }
3117 break;
3118
3119 UnaryStar:
3120 // C++ [over.built]p6:
3121 // For every cv-qualified or cv-unqualified object type T, there
3122 // exist candidate operator functions of the form
3123 //
3124 // T& operator*(T*);
3125 //
3126 // C++ [over.built]p7:
3127 // For every function type T, there exist candidate operator
3128 // functions of the form
3129 // T& operator*(T*);
3130 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3131 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3132 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003133 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003134 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003135 &ParamTy, Args, 1, CandidateSet);
3136 }
3137 break;
3138
3139 UnaryPlus:
3140 // C++ [over.built]p8:
3141 // For every type T, there exist candidate operator functions of
3142 // the form
3143 //
3144 // T* operator+(T*);
3145 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3146 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3147 QualType ParamTy = *Ptr;
3148 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3149 }
Mike Stump11289f42009-09-09 15:08:12 +00003150
Douglas Gregord08452f2008-11-19 15:42:04 +00003151 // Fall through
3152
3153 UnaryMinus:
3154 // C++ [over.built]p9:
3155 // For every promoted arithmetic type T, there exist candidate
3156 // operator functions of the form
3157 //
3158 // T operator+(T);
3159 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003160 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003161 Arith < LastPromotedArithmeticType; ++Arith) {
3162 QualType ArithTy = ArithmeticTypes[Arith];
3163 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3164 }
3165 break;
3166
3167 case OO_Tilde:
3168 // C++ [over.built]p10:
3169 // For every promoted integral type T, there exist candidate
3170 // operator functions of the form
3171 //
3172 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003173 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003174 Int < LastPromotedIntegralType; ++Int) {
3175 QualType IntTy = ArithmeticTypes[Int];
3176 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3177 }
3178 break;
3179
Douglas Gregora11693b2008-11-12 17:17:38 +00003180 case OO_New:
3181 case OO_Delete:
3182 case OO_Array_New:
3183 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003184 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003185 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003186 break;
3187
3188 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003189 UnaryAmp:
3190 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003191 // C++ [over.match.oper]p3:
3192 // -- For the operator ',', the unary operator '&', or the
3193 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003194 break;
3195
Douglas Gregor84605ae2009-08-24 13:43:27 +00003196 case OO_EqualEqual:
3197 case OO_ExclaimEqual:
3198 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003199 // For every pointer to member type T, there exist candidate operator
3200 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003201 //
3202 // bool operator==(T,T);
3203 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003204 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003205 MemPtr = CandidateTypes.member_pointer_begin(),
3206 MemPtrEnd = CandidateTypes.member_pointer_end();
3207 MemPtr != MemPtrEnd;
3208 ++MemPtr) {
3209 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3210 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3211 }
Mike Stump11289f42009-09-09 15:08:12 +00003212
Douglas Gregor84605ae2009-08-24 13:43:27 +00003213 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003214
Douglas Gregora11693b2008-11-12 17:17:38 +00003215 case OO_Less:
3216 case OO_Greater:
3217 case OO_LessEqual:
3218 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003219 // C++ [over.built]p15:
3220 //
3221 // For every pointer or enumeration type T, there exist
3222 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003223 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003224 // bool operator<(T, T);
3225 // bool operator>(T, T);
3226 // bool operator<=(T, T);
3227 // bool operator>=(T, T);
3228 // bool operator==(T, T);
3229 // bool operator!=(T, T);
3230 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3231 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3232 QualType ParamTypes[2] = { *Ptr, *Ptr };
3233 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3234 }
Mike Stump11289f42009-09-09 15:08:12 +00003235 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003236 = CandidateTypes.enumeration_begin();
3237 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3238 QualType ParamTypes[2] = { *Enum, *Enum };
3239 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3240 }
3241
3242 // Fall through.
3243 isComparison = true;
3244
Douglas Gregord08452f2008-11-19 15:42:04 +00003245 BinaryPlus:
3246 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003247 if (!isComparison) {
3248 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3249
3250 // C++ [over.built]p13:
3251 //
3252 // For every cv-qualified or cv-unqualified object type T
3253 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003254 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003255 // T* operator+(T*, ptrdiff_t);
3256 // T& operator[](T*, ptrdiff_t); [BELOW]
3257 // T* operator-(T*, ptrdiff_t);
3258 // T* operator+(ptrdiff_t, T*);
3259 // T& operator[](ptrdiff_t, T*); [BELOW]
3260 //
3261 // C++ [over.built]p14:
3262 //
3263 // For every T, where T is a pointer to object type, there
3264 // exist candidate operator functions of the form
3265 //
3266 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003267 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003268 = CandidateTypes.pointer_begin();
3269 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3270 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3271
3272 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3273 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3274
3275 if (Op == OO_Plus) {
3276 // T* operator+(ptrdiff_t, T*);
3277 ParamTypes[0] = ParamTypes[1];
3278 ParamTypes[1] = *Ptr;
3279 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3280 } else {
3281 // ptrdiff_t operator-(T, T);
3282 ParamTypes[1] = *Ptr;
3283 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3284 Args, 2, CandidateSet);
3285 }
3286 }
3287 }
3288 // Fall through
3289
Douglas Gregora11693b2008-11-12 17:17:38 +00003290 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003291 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003292 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003293 // C++ [over.built]p12:
3294 //
3295 // For every pair of promoted arithmetic types L and R, there
3296 // exist candidate operator functions of the form
3297 //
3298 // LR operator*(L, R);
3299 // LR operator/(L, R);
3300 // LR operator+(L, R);
3301 // LR operator-(L, R);
3302 // bool operator<(L, R);
3303 // bool operator>(L, R);
3304 // bool operator<=(L, R);
3305 // bool operator>=(L, R);
3306 // bool operator==(L, R);
3307 // bool operator!=(L, R);
3308 //
3309 // where LR is the result of the usual arithmetic conversions
3310 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003311 //
3312 // C++ [over.built]p24:
3313 //
3314 // For every pair of promoted arithmetic types L and R, there exist
3315 // candidate operator functions of the form
3316 //
3317 // LR operator?(bool, L, R);
3318 //
3319 // where LR is the result of the usual arithmetic conversions
3320 // between types L and R.
3321 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003322 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003323 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003324 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003325 Right < LastPromotedArithmeticType; ++Right) {
3326 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003327 QualType Result
3328 = isComparison
3329 ? Context.BoolTy
3330 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003331 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3332 }
3333 }
3334 break;
3335
3336 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003337 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003338 case OO_Caret:
3339 case OO_Pipe:
3340 case OO_LessLess:
3341 case OO_GreaterGreater:
3342 // C++ [over.built]p17:
3343 //
3344 // For every pair of promoted integral types L and R, there
3345 // exist candidate operator functions of the form
3346 //
3347 // LR operator%(L, R);
3348 // LR operator&(L, R);
3349 // LR operator^(L, R);
3350 // LR operator|(L, R);
3351 // L operator<<(L, R);
3352 // L operator>>(L, R);
3353 //
3354 // where LR is the result of the usual arithmetic conversions
3355 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003356 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003357 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003358 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003359 Right < LastPromotedIntegralType; ++Right) {
3360 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3361 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3362 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003363 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003364 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3365 }
3366 }
3367 break;
3368
3369 case OO_Equal:
3370 // C++ [over.built]p20:
3371 //
3372 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003373 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003374 // empty, there exist candidate operator functions of the form
3375 //
3376 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003377 for (BuiltinCandidateTypeSet::iterator
3378 Enum = CandidateTypes.enumeration_begin(),
3379 EnumEnd = CandidateTypes.enumeration_end();
3380 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003381 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003382 CandidateSet);
3383 for (BuiltinCandidateTypeSet::iterator
3384 MemPtr = CandidateTypes.member_pointer_begin(),
3385 MemPtrEnd = CandidateTypes.member_pointer_end();
3386 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003387 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003388 CandidateSet);
3389 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003390
3391 case OO_PlusEqual:
3392 case OO_MinusEqual:
3393 // C++ [over.built]p19:
3394 //
3395 // For every pair (T, VQ), where T is any type and VQ is either
3396 // volatile or empty, there exist candidate operator functions
3397 // of the form
3398 //
3399 // T*VQ& operator=(T*VQ&, T*);
3400 //
3401 // C++ [over.built]p21:
3402 //
3403 // For every pair (T, VQ), where T is a cv-qualified or
3404 // cv-unqualified object type and VQ is either volatile or
3405 // empty, there exist candidate operator functions of the form
3406 //
3407 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3408 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3409 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3410 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3411 QualType ParamTypes[2];
3412 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3413
3414 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003415 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003416 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3417 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003418
Douglas Gregord08452f2008-11-19 15:42:04 +00003419 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3420 // volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003421 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorc5e61072009-01-13 00:52:54 +00003422 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3423 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003424 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003425 }
3426 // Fall through.
3427
3428 case OO_StarEqual:
3429 case OO_SlashEqual:
3430 // C++ [over.built]p18:
3431 //
3432 // For every triple (L, VQ, R), where L is an arithmetic type,
3433 // VQ is either volatile or empty, and R is a promoted
3434 // arithmetic type, there exist candidate operator functions of
3435 // the form
3436 //
3437 // VQ L& operator=(VQ L&, R);
3438 // VQ L& operator*=(VQ L&, R);
3439 // VQ L& operator/=(VQ L&, R);
3440 // VQ L& operator+=(VQ L&, R);
3441 // VQ L& operator-=(VQ L&, R);
3442 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003443 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003444 Right < LastPromotedArithmeticType; ++Right) {
3445 QualType ParamTypes[2];
3446 ParamTypes[1] = ArithmeticTypes[Right];
3447
3448 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003449 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003450 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3451 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003452
3453 // Add this built-in operator as a candidate (VQ is 'volatile').
3454 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003455 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003456 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3457 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003458 }
3459 }
3460 break;
3461
3462 case OO_PercentEqual:
3463 case OO_LessLessEqual:
3464 case OO_GreaterGreaterEqual:
3465 case OO_AmpEqual:
3466 case OO_CaretEqual:
3467 case OO_PipeEqual:
3468 // C++ [over.built]p22:
3469 //
3470 // For every triple (L, VQ, R), where L is an integral type, VQ
3471 // is either volatile or empty, and R is a promoted integral
3472 // type, there exist candidate operator functions of the form
3473 //
3474 // VQ L& operator%=(VQ L&, R);
3475 // VQ L& operator<<=(VQ L&, R);
3476 // VQ L& operator>>=(VQ L&, R);
3477 // VQ L& operator&=(VQ L&, R);
3478 // VQ L& operator^=(VQ L&, R);
3479 // VQ L& operator|=(VQ L&, R);
3480 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003481 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003482 Right < LastPromotedIntegralType; ++Right) {
3483 QualType ParamTypes[2];
3484 ParamTypes[1] = ArithmeticTypes[Right];
3485
3486 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003487 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003488 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3489
3490 // Add this built-in operator as a candidate (VQ is 'volatile').
3491 ParamTypes[0] = ArithmeticTypes[Left];
3492 ParamTypes[0].addVolatile();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003493 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003494 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3495 }
3496 }
3497 break;
3498
Douglas Gregord08452f2008-11-19 15:42:04 +00003499 case OO_Exclaim: {
3500 // C++ [over.operator]p23:
3501 //
3502 // There also exist candidate operator functions of the form
3503 //
Mike Stump11289f42009-09-09 15:08:12 +00003504 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003505 // bool operator&&(bool, bool); [BELOW]
3506 // bool operator||(bool, bool); [BELOW]
3507 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003508 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3509 /*IsAssignmentOperator=*/false,
3510 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003511 break;
3512 }
3513
Douglas Gregora11693b2008-11-12 17:17:38 +00003514 case OO_AmpAmp:
3515 case OO_PipePipe: {
3516 // C++ [over.operator]p23:
3517 //
3518 // There also exist candidate operator functions of the form
3519 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003520 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003521 // bool operator&&(bool, bool);
3522 // bool operator||(bool, bool);
3523 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003524 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3525 /*IsAssignmentOperator=*/false,
3526 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003527 break;
3528 }
3529
3530 case OO_Subscript:
3531 // C++ [over.built]p13:
3532 //
3533 // For every cv-qualified or cv-unqualified object type T there
3534 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003535 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003536 // T* operator+(T*, ptrdiff_t); [ABOVE]
3537 // T& operator[](T*, ptrdiff_t);
3538 // T* operator-(T*, ptrdiff_t); [ABOVE]
3539 // T* operator+(ptrdiff_t, T*); [ABOVE]
3540 // T& operator[](ptrdiff_t, T*);
3541 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3542 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3543 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003544 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003545 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003546
3547 // T& operator[](T*, ptrdiff_t)
3548 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3549
3550 // T& operator[](ptrdiff_t, T*);
3551 ParamTypes[0] = ParamTypes[1];
3552 ParamTypes[1] = *Ptr;
3553 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3554 }
3555 break;
3556
3557 case OO_ArrowStar:
3558 // FIXME: No support for pointer-to-members yet.
3559 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003560
3561 case OO_Conditional:
3562 // Note that we don't consider the first argument, since it has been
3563 // contextually converted to bool long ago. The candidates below are
3564 // therefore added as binary.
3565 //
3566 // C++ [over.built]p24:
3567 // For every type T, where T is a pointer or pointer-to-member type,
3568 // there exist candidate operator functions of the form
3569 //
3570 // T operator?(bool, T, T);
3571 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003572 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3573 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3574 QualType ParamTypes[2] = { *Ptr, *Ptr };
3575 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3576 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003577 for (BuiltinCandidateTypeSet::iterator Ptr =
3578 CandidateTypes.member_pointer_begin(),
3579 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3580 QualType ParamTypes[2] = { *Ptr, *Ptr };
3581 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3582 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003583 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003584 }
3585}
3586
Douglas Gregore254f902009-02-04 00:32:51 +00003587/// \brief Add function candidates found via argument-dependent lookup
3588/// to the set of overloading candidates.
3589///
3590/// This routine performs argument-dependent name lookup based on the
3591/// given function name (which may also be an operator name) and adds
3592/// all of the overload candidates found by ADL to the overload
3593/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003594void
Douglas Gregore254f902009-02-04 00:32:51 +00003595Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3596 Expr **Args, unsigned NumArgs,
3597 OverloadCandidateSet& CandidateSet) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003598 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003599
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003600 // Record all of the function candidates that we've already
3601 // added to the overload set, so that we don't add those same
3602 // candidates a second time.
3603 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3604 CandEnd = CandidateSet.end();
3605 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003606 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003607 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003608 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3609 Functions.insert(FunTmpl);
3610 }
Douglas Gregore254f902009-02-04 00:32:51 +00003611
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003612 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003613
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003614 // Erase all of the candidates we already knew about.
3615 // FIXME: This is suboptimal. Is there a better way?
3616 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3617 CandEnd = CandidateSet.end();
3618 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003619 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003620 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003621 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3622 Functions.erase(FunTmpl);
3623 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003624
3625 // For each of the ADL candidates we found, add it to the overload
3626 // set.
3627 for (FunctionSet::iterator Func = Functions.begin(),
3628 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00003629 Func != FuncEnd; ++Func) {
3630 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3631 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3632 else
Mike Stump11289f42009-09-09 15:08:12 +00003633 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregor89026b52009-06-30 23:57:56 +00003634 /*FIXME: explicit args */false, 0, 0,
3635 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00003636 }
Douglas Gregore254f902009-02-04 00:32:51 +00003637}
3638
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003639/// isBetterOverloadCandidate - Determines whether the first overload
3640/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00003641bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003642Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00003643 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003644 // Define viable functions to be better candidates than non-viable
3645 // functions.
3646 if (!Cand2.Viable)
3647 return Cand1.Viable;
3648 else if (!Cand1.Viable)
3649 return false;
3650
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003651 // C++ [over.match.best]p1:
3652 //
3653 // -- if F is a static member function, ICS1(F) is defined such
3654 // that ICS1(F) is neither better nor worse than ICS1(G) for
3655 // any function G, and, symmetrically, ICS1(G) is neither
3656 // better nor worse than ICS1(F).
3657 unsigned StartArg = 0;
3658 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3659 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003660
Douglas Gregord3cb3562009-07-07 23:38:56 +00003661 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00003662 // A viable function F1 is defined to be a better function than another
3663 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00003664 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003665 unsigned NumArgs = Cand1.Conversions.size();
3666 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3667 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003668 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003669 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3670 Cand2.Conversions[ArgIdx])) {
3671 case ImplicitConversionSequence::Better:
3672 // Cand1 has a better conversion sequence.
3673 HasBetterConversion = true;
3674 break;
3675
3676 case ImplicitConversionSequence::Worse:
3677 // Cand1 can't be better than Cand2.
3678 return false;
3679
3680 case ImplicitConversionSequence::Indistinguishable:
3681 // Do nothing.
3682 break;
3683 }
3684 }
3685
Mike Stump11289f42009-09-09 15:08:12 +00003686 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00003687 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003688 if (HasBetterConversion)
3689 return true;
3690
Mike Stump11289f42009-09-09 15:08:12 +00003691 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00003692 // specialization, or, if not that,
3693 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3694 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3695 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003696
3697 // -- F1 and F2 are function template specializations, and the function
3698 // template for F1 is more specialized than the template for F2
3699 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00003700 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00003701 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3702 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00003703 if (FunctionTemplateDecl *BetterTemplate
3704 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3705 Cand2.Function->getPrimaryTemplate(),
3706 true))
3707 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003708
Douglas Gregora1f013e2008-11-07 22:36:19 +00003709 // -- the context is an initialization by user-defined conversion
3710 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3711 // from the return type of F1 to the destination type (i.e.,
3712 // the type of the entity being initialized) is a better
3713 // conversion sequence than the standard conversion sequence
3714 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00003715 if (Cand1.Function && Cand2.Function &&
3716 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003717 isa<CXXConversionDecl>(Cand2.Function)) {
3718 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3719 Cand2.FinalConversion)) {
3720 case ImplicitConversionSequence::Better:
3721 // Cand1 has a better conversion sequence.
3722 return true;
3723
3724 case ImplicitConversionSequence::Worse:
3725 // Cand1 can't be better than Cand2.
3726 return false;
3727
3728 case ImplicitConversionSequence::Indistinguishable:
3729 // Do nothing
3730 break;
3731 }
3732 }
3733
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003734 return false;
3735}
3736
Mike Stump11289f42009-09-09 15:08:12 +00003737/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003738/// within an overload candidate set.
3739///
3740/// \param CandidateSet the set of candidate functions.
3741///
3742/// \param Loc the location of the function name (or operator symbol) for
3743/// which overload resolution occurs.
3744///
Mike Stump11289f42009-09-09 15:08:12 +00003745/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003746/// function, Best points to the candidate function found.
3747///
3748/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00003749Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003750Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003751 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003752 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003753 // Find the best viable function.
3754 Best = CandidateSet.end();
3755 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3756 Cand != CandidateSet.end(); ++Cand) {
3757 if (Cand->Viable) {
3758 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3759 Best = Cand;
3760 }
3761 }
3762
3763 // If we didn't find any viable functions, abort.
3764 if (Best == CandidateSet.end())
3765 return OR_No_Viable_Function;
3766
3767 // Make sure that this function is better than every other viable
3768 // function. If not, we have an ambiguity.
3769 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3770 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00003771 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003772 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00003773 !isBetterOverloadCandidate(*Best, *Cand)) {
3774 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003775 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003776 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003777 }
Mike Stump11289f42009-09-09 15:08:12 +00003778
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003779 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003780 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00003781 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003782 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003783 return OR_Deleted;
3784
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003785 // C++ [basic.def.odr]p2:
3786 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00003787 // when referred to from a potentially-evaluated expression. [Note: this
3788 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003789 // (clause 13), user-defined conversions (12.3.2), allocation function for
3790 // placement new (5.3.4), as well as non-default initialization (8.5).
3791 if (Best->Function)
3792 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003793 return OR_Success;
3794}
3795
3796/// PrintOverloadCandidates - When overload resolution fails, prints
3797/// diagnostic messages containing the candidates in the candidate
3798/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00003799void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003800Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003801 bool OnlyViable) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003802 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3803 LastCand = CandidateSet.end();
3804 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003805 if (Cand->Viable || !OnlyViable) {
3806 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003807 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003808 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003809 // Deleted or "unavailable" function.
3810 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3811 << Cand->Function->isDeleted();
3812 } else {
3813 // Normal function
3814 // FIXME: Give a better reason!
3815 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3816 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00003817 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003818 // Desugar the type of the surrogate down to a function type,
3819 // retaining as many typedefs as possible while still showing
3820 // the function type (and, therefore, its parameter types).
3821 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003822 bool isLValueReference = false;
3823 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003824 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003825 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003826 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003827 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003828 isLValueReference = true;
3829 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003830 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003831 FnType = FnTypeRef->getPointeeType();
3832 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003833 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003834 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003835 FnType = FnTypePtr->getPointeeType();
3836 isPointer = true;
3837 }
3838 // Desugar down to a function type.
3839 FnType = QualType(FnType->getAsFunctionType(), 0);
3840 // Reconstruct the pointer/reference as appropriate.
3841 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003842 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3843 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003844
Douglas Gregorab7897a2008-11-19 22:57:39 +00003845 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003846 << FnType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003847 } else {
3848 // FIXME: We need to get the identifier in here
Mike Stump87c57ac2009-05-16 07:39:55 +00003849 // FIXME: Do we want the error message to point at the operator?
3850 // (built-ins won't have a location)
Mike Stump11289f42009-09-09 15:08:12 +00003851 QualType FnType
Douglas Gregora11693b2008-11-12 17:17:38 +00003852 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3853 Cand->BuiltinTypes.ParamTypes,
3854 Cand->Conversions.size(),
3855 false, 0);
3856
Chris Lattner1e5665e2008-11-24 06:25:27 +00003857 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003858 }
3859 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003860 }
3861}
3862
Douglas Gregorcd695e52008-11-10 20:40:00 +00003863/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3864/// an overloaded function (C++ [over.over]), where @p From is an
3865/// expression with overloaded function type and @p ToType is the type
3866/// we're trying to resolve to. For example:
3867///
3868/// @code
3869/// int f(double);
3870/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00003871///
Douglas Gregorcd695e52008-11-10 20:40:00 +00003872/// int (*pfd)(double) = f; // selects f(double)
3873/// @endcode
3874///
3875/// This routine returns the resulting FunctionDecl if it could be
3876/// resolved, and NULL otherwise. When @p Complain is true, this
3877/// routine will emit diagnostics if there is an error.
3878FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003879Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003880 bool Complain) {
3881 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003882 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003883 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00003884 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003885 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00003886 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003887 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003888 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003889 FunctionType = MemTypePtr->getPointeeType();
3890 IsMember = true;
3891 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003892
3893 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00003894 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00003895 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00003896 return 0;
3897
3898 // Find the actual overloaded function declaration.
3899 OverloadedFunctionDecl *Ovl = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003900
Douglas Gregorcd695e52008-11-10 20:40:00 +00003901 // C++ [over.over]p1:
3902 // [...] [Note: any redundant set of parentheses surrounding the
3903 // overloaded function name is ignored (5.1). ]
3904 Expr *OvlExpr = From->IgnoreParens();
3905
3906 // C++ [over.over]p1:
3907 // [...] The overloaded function name can be preceded by the &
3908 // operator.
3909 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3910 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3911 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3912 }
3913
3914 // Try to dig out the overloaded function.
Douglas Gregor9b146582009-07-08 20:55:45 +00003915 FunctionTemplateDecl *FunctionTemplate = 0;
3916 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00003917 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor9b146582009-07-08 20:55:45 +00003918 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3919 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003920
Mike Stump11289f42009-09-09 15:08:12 +00003921 // If there's no overloaded function declaration or function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00003922 // we're done.
3923 if (!Ovl && !FunctionTemplate)
Douglas Gregorcd695e52008-11-10 20:40:00 +00003924 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003925
Douglas Gregor9b146582009-07-08 20:55:45 +00003926 OverloadIterator Fun;
3927 if (Ovl)
3928 Fun = Ovl;
3929 else
3930 Fun = FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00003931
Douglas Gregorcd695e52008-11-10 20:40:00 +00003932 // Look through all of the overloaded functions, searching for one
3933 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003934 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Mike Stump11289f42009-09-09 15:08:12 +00003935
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003936 bool FoundNonTemplateFunction = false;
Douglas Gregor9b146582009-07-08 20:55:45 +00003937 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00003938 // C++ [over.over]p3:
3939 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00003940 // targets of type "pointer-to-function" or "reference-to-function."
3941 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003942 // type "pointer-to-member-function."
3943 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00003944
Mike Stump11289f42009-09-09 15:08:12 +00003945 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor9b146582009-07-08 20:55:45 +00003946 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump11289f42009-09-09 15:08:12 +00003947 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003948 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003949 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003950 // static when converting to member pointer.
3951 if (Method->isStatic() == IsMember)
3952 continue;
3953 } else if (IsMember)
3954 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003955
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003956 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003957 // If the name is a function template, template argument deduction is
3958 // done (14.8.2.2), and if the argument deduction succeeds, the
3959 // resulting template argument list is used to generate a single
3960 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003961 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00003962 FunctionDecl *Specialization = 0;
3963 TemplateDeductionInfo Info(Context);
3964 if (TemplateDeductionResult Result
3965 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3966 /*FIXME:*/0, /*FIXME:*/0,
3967 FunctionType, Specialization, Info)) {
3968 // FIXME: make a note of the failed deduction for diagnostics.
3969 (void)Result;
3970 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003971 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00003972 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003973 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003974 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00003975 }
3976 }
Mike Stump11289f42009-09-09 15:08:12 +00003977
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003978 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3979 // Skip non-static functions when converting to pointer, and static
3980 // when converting to member pointer.
3981 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00003982 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003983 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003984 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00003985
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003986 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003987 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003988 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003989 FoundNonTemplateFunction = true;
3990 }
Mike Stump11289f42009-09-09 15:08:12 +00003991 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003992 }
3993
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003994 // If there were 0 or 1 matches, we're done.
3995 if (Matches.empty())
3996 return 0;
3997 else if (Matches.size() == 1)
3998 return *Matches.begin();
3999
4000 // C++ [over.over]p4:
4001 // If more than one function is selected, [...]
4002 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor05155d82009-08-21 23:19:43 +00004003 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004004 if (FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004005 // [...] any function template specializations in the set are
4006 // eliminated if the set also contains a non-template function, [...]
4007 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004008 if ((*M)->getPrimaryTemplate() == 0)
4009 RemainingMatches.push_back(*M);
4010 } else {
Douglas Gregor05155d82009-08-21 23:19:43 +00004011 // [...] and any given function template specialization F1 is
4012 // eliminated if the set contains a second function template
4013 // specialization whose function template is more specialized
4014 // than the function template of F1 according to the partial
4015 // ordering rules of 14.5.5.2.
4016
4017 // The algorithm specified above is quadratic. We instead use a
4018 // two-pass algorithm (similar to the one used to identify the
4019 // best viable function in an overload set) that identifies the
4020 // best function template (if it exists).
4021 MatchIter Best = Matches.begin();
4022 MatchIter M = Best, MEnd = Matches.end();
4023 // Find the most specialized function.
4024 for (++M; M != MEnd; ++M)
4025 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4026 (*Best)->getPrimaryTemplate(),
Mike Stump11289f42009-09-09 15:08:12 +00004027 false)
Douglas Gregor05155d82009-08-21 23:19:43 +00004028 == (*M)->getPrimaryTemplate())
4029 Best = M;
4030
4031 // Determine whether this function template is more specialized
4032 // that all of the others.
4033 bool Ambiguous = false;
4034 for (M = Matches.begin(); M != MEnd; ++M) {
4035 if (M != Best &&
4036 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4037 (*Best)->getPrimaryTemplate(),
4038 false)
4039 != (*Best)->getPrimaryTemplate()) {
4040 Ambiguous = true;
4041 break;
4042 }
4043 }
4044
4045 // If one function template was more specialized than all of the
4046 // others, return it.
4047 if (!Ambiguous)
4048 return *Best;
4049
4050 // We could not find a most-specialized function template, which
4051 // is equivalent to having a set of function templates with more
4052 // than one such template. So, we place all of the function
4053 // templates into the set of remaining matches and produce a
4054 // diagnostic below. FIXME: we could perform the quadratic
4055 // algorithm here, pruning the result set to limit the number of
4056 // candidates output later.
4057 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004058 }
Mike Stump11289f42009-09-09 15:08:12 +00004059
4060 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004061 // selected function.
4062 if (RemainingMatches.size() == 1)
4063 return RemainingMatches.front();
Mike Stump11289f42009-09-09 15:08:12 +00004064
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004065 // FIXME: We should probably return the same thing that BestViableFunction
4066 // returns (even if we issue the diagnostics here).
4067 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4068 << RemainingMatches[0]->getDeclName();
4069 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4070 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004071 return 0;
4072}
4073
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004074/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004075/// (which eventually refers to the declaration Func) and the call
4076/// arguments Args/NumArgs, attempt to resolve the function call down
4077/// to a specific function. If overload resolution succeeds, returns
4078/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004079/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004080/// arguments and Fn, and returns NULL.
Douglas Gregore254f902009-02-04 00:32:51 +00004081FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004082 DeclarationName UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00004083 bool HasExplicitTemplateArgs,
4084 const TemplateArgument *ExplicitTemplateArgs,
4085 unsigned NumExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004086 SourceLocation LParenLoc,
4087 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004088 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004089 SourceLocation RParenLoc,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004090 bool &ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004091 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004092
4093 // Add the functions denoted by Callee to the set of candidate
4094 // functions. While we're doing so, track whether argument-dependent
4095 // lookup still applies, per:
4096 //
4097 // C++0x [basic.lookup.argdep]p3:
4098 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4099 // and let Y be the lookup set produced by argument dependent
4100 // lookup (defined as follows). If X contains
4101 //
Mike Stump11289f42009-09-09 15:08:12 +00004102 // -- a declaration of a class member, or
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004103 //
4104 // -- a block-scope function declaration that is not a
Mike Stump11289f42009-09-09 15:08:12 +00004105 // using-declaration, or
4106 //
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004107 // -- a declaration that is neither a function or a function
4108 // template
4109 //
Mike Stump11289f42009-09-09 15:08:12 +00004110 // then Y is empty.
4111 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004112 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4113 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4114 FuncEnd = Ovl->function_end();
4115 Func != FuncEnd; ++Func) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004116 DeclContext *Ctx = 0;
4117 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregor89026b52009-06-30 23:57:56 +00004118 if (HasExplicitTemplateArgs)
4119 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004120
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004121 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4122 Ctx = FunDecl->getDeclContext();
4123 } else {
4124 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregor89026b52009-06-30 23:57:56 +00004125 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4126 ExplicitTemplateArgs,
4127 NumExplicitTemplateArgs,
4128 Args, NumArgs, CandidateSet);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004129 Ctx = FunTmpl->getDeclContext();
4130 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004131
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004132
4133 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004134 ArgumentDependentLookup = false;
4135 }
4136 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregor89026b52009-06-30 23:57:56 +00004137 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004138 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4139
4140 if (Func->getDeclContext()->isRecord() ||
4141 Func->getDeclContext()->isFunctionOrMethod())
4142 ArgumentDependentLookup = false;
Mike Stump11289f42009-09-09 15:08:12 +00004143 } else if (FunctionTemplateDecl *FuncTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004144 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregor89026b52009-06-30 23:57:56 +00004145 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4146 ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004147 NumExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004148 Args, NumArgs, CandidateSet);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004149
4150 if (FuncTemplate->getDeclContext()->isRecord())
4151 ArgumentDependentLookup = false;
4152 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004153
4154 if (Callee)
4155 UnqualifiedName = Callee->getDeclName();
4156
Douglas Gregor89026b52009-06-30 23:57:56 +00004157 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregore254f902009-02-04 00:32:51 +00004158 if (ArgumentDependentLookup)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004159 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregore254f902009-02-04 00:32:51 +00004160 CandidateSet);
4161
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004162 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004163 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004164 case OR_Success:
4165 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004166
4167 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004168 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004169 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004170 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004171 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4172 break;
4173
4174 case OR_Ambiguous:
4175 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004176 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004177 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4178 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004179
4180 case OR_Deleted:
4181 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4182 << Best->Function->isDeleted()
4183 << UnqualifiedName
4184 << Fn->getSourceRange();
4185 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4186 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004187 }
4188
4189 // Overload resolution failed. Destroy all of the subexpressions and
4190 // return NULL.
4191 Fn->Destroy(Context);
4192 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4193 Args[Arg]->Destroy(Context);
4194 return 0;
4195}
4196
Douglas Gregor084d8552009-03-13 23:49:33 +00004197/// \brief Create a unary operation that may resolve to an overloaded
4198/// operator.
4199///
4200/// \param OpLoc The location of the operator itself (e.g., '*').
4201///
4202/// \param OpcIn The UnaryOperator::Opcode that describes this
4203/// operator.
4204///
4205/// \param Functions The set of non-member functions that will be
4206/// considered by overload resolution. The caller needs to build this
4207/// set based on the context using, e.g.,
4208/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4209/// set should not contain any member functions; those will be added
4210/// by CreateOverloadedUnaryOp().
4211///
4212/// \param input The input argument.
4213Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4214 unsigned OpcIn,
4215 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004216 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004217 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4218 Expr *Input = (Expr *)input.get();
4219
4220 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4221 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4222 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4223
4224 Expr *Args[2] = { Input, 0 };
4225 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004226
Douglas Gregor084d8552009-03-13 23:49:33 +00004227 // For post-increment and post-decrement, add the implicit '0' as
4228 // the second argument, so that we know this is a post-increment or
4229 // post-decrement.
4230 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4231 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004232 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004233 SourceLocation());
4234 NumArgs = 2;
4235 }
4236
4237 if (Input->isTypeDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00004238 OverloadedFunctionDecl *Overloads
Douglas Gregor084d8552009-03-13 23:49:33 +00004239 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004240 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004241 FuncEnd = Functions.end();
4242 Func != FuncEnd; ++Func)
4243 Overloads->addOverload(*Func);
4244
4245 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4246 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004247
Douglas Gregor084d8552009-03-13 23:49:33 +00004248 input.release();
4249 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4250 &Args[0], NumArgs,
4251 Context.DependentTy,
4252 OpLoc));
4253 }
4254
4255 // Build an empty overload set.
4256 OverloadCandidateSet CandidateSet;
4257
4258 // Add the candidates from the given function set.
4259 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4260
4261 // Add operator candidates that are member functions.
4262 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4263
4264 // Add builtin operator candidates.
4265 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4266
4267 // Perform overload resolution.
4268 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004269 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004270 case OR_Success: {
4271 // We found a built-in operator or an overloaded operator.
4272 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004273
Douglas Gregor084d8552009-03-13 23:49:33 +00004274 if (FnDecl) {
4275 // We matched an overloaded operator. Build a call to that
4276 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004277
Douglas Gregor084d8552009-03-13 23:49:33 +00004278 // Convert the arguments.
4279 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4280 if (PerformObjectArgumentInitialization(Input, Method))
4281 return ExprError();
4282 } else {
4283 // Convert the arguments.
4284 if (PerformCopyInitialization(Input,
4285 FnDecl->getParamDecl(0)->getType(),
4286 "passing"))
4287 return ExprError();
4288 }
4289
4290 // Determine the result type
4291 QualType ResultTy
4292 = FnDecl->getType()->getAsFunctionType()->getResultType();
4293 ResultTy = ResultTy.getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004294
Douglas Gregor084d8552009-03-13 23:49:33 +00004295 // Build the actual expression node.
4296 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4297 SourceLocation());
4298 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004299
Douglas Gregor084d8552009-03-13 23:49:33 +00004300 input.release();
Mike Stump11289f42009-09-09 15:08:12 +00004301
4302 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004303 &Input, 1, ResultTy, OpLoc);
4304 return MaybeBindToTemporary(CE);
Douglas Gregor084d8552009-03-13 23:49:33 +00004305 } else {
4306 // We matched a built-in operator. Convert the arguments, then
4307 // break out so that we will build the appropriate built-in
4308 // operator node.
4309 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4310 Best->Conversions[0], "passing"))
4311 return ExprError();
4312
4313 break;
4314 }
4315 }
4316
4317 case OR_No_Viable_Function:
4318 // No viable function; fall through to handling this as a
4319 // built-in operator, which will produce an error message for us.
4320 break;
4321
4322 case OR_Ambiguous:
4323 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4324 << UnaryOperator::getOpcodeStr(Opc)
4325 << Input->getSourceRange();
4326 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4327 return ExprError();
4328
4329 case OR_Deleted:
4330 Diag(OpLoc, diag::err_ovl_deleted_oper)
4331 << Best->Function->isDeleted()
4332 << UnaryOperator::getOpcodeStr(Opc)
4333 << Input->getSourceRange();
4334 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4335 return ExprError();
4336 }
4337
4338 // Either we found no viable overloaded operator or we matched a
4339 // built-in operator. In either case, fall through to trying to
4340 // build a built-in operation.
4341 input.release();
4342 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4343}
4344
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004345/// \brief Create a binary operation that may resolve to an overloaded
4346/// operator.
4347///
4348/// \param OpLoc The location of the operator itself (e.g., '+').
4349///
4350/// \param OpcIn The BinaryOperator::Opcode that describes this
4351/// operator.
4352///
4353/// \param Functions The set of non-member functions that will be
4354/// considered by overload resolution. The caller needs to build this
4355/// set based on the context using, e.g.,
4356/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4357/// set should not contain any member functions; those will be added
4358/// by CreateOverloadedBinOp().
4359///
4360/// \param LHS Left-hand argument.
4361/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004362Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004363Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004364 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004365 FunctionSet &Functions,
4366 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004367 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004368 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004369
4370 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4371 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4372 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4373
4374 // If either side is type-dependent, create an appropriate dependent
4375 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004376 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004377 // .* cannot be overloaded.
4378 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004379 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004380 Context.DependentTy, OpLoc));
4381
Mike Stump11289f42009-09-09 15:08:12 +00004382 OverloadedFunctionDecl *Overloads
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004383 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004384 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004385 FuncEnd = Functions.end();
4386 Func != FuncEnd; ++Func)
4387 Overloads->addOverload(*Func);
4388
4389 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4390 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004391
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004392 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004393 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004394 Context.DependentTy,
4395 OpLoc));
4396 }
4397
4398 // If this is the .* operator, which is not overloadable, just
4399 // create a built-in binary operator.
4400 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004401 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004402
4403 // If this is one of the assignment operators, we only perform
4404 // overload resolution if the left-hand side is a class or
4405 // enumeration type (C++ [expr.ass]p3).
4406 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregore9899d92009-08-26 17:08:25 +00004407 !Args[0]->getType()->isOverloadableType())
4408 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004409
Douglas Gregor084d8552009-03-13 23:49:33 +00004410 // Build an empty overload set.
4411 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004412
4413 // Add the candidates from the given function set.
4414 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4415
4416 // Add operator candidates that are member functions.
4417 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4418
4419 // Add builtin operator candidates.
4420 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4421
4422 // Perform overload resolution.
4423 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004424 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004425 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004426 // We found a built-in operator or an overloaded operator.
4427 FunctionDecl *FnDecl = Best->Function;
4428
4429 if (FnDecl) {
4430 // We matched an overloaded operator. Build a call to that
4431 // operator.
4432
4433 // Convert the arguments.
4434 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004435 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4436 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004437 "passing"))
4438 return ExprError();
4439 } else {
4440 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004441 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004442 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004443 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004444 "passing"))
4445 return ExprError();
4446 }
4447
4448 // Determine the result type
4449 QualType ResultTy
4450 = FnDecl->getType()->getAsFunctionType()->getResultType();
4451 ResultTy = ResultTy.getNonReferenceType();
4452
4453 // Build the actual expression node.
4454 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004455 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004456 UsualUnaryConversions(FnExpr);
4457
Mike Stump11289f42009-09-09 15:08:12 +00004458 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004459 Args, 2, ResultTy, OpLoc);
4460 return MaybeBindToTemporary(CE);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004461 } else {
4462 // We matched a built-in operator. Convert the arguments, then
4463 // break out so that we will build the appropriate built-in
4464 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004465 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004466 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004467 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004468 Best->Conversions[1], "passing"))
4469 return ExprError();
4470
4471 break;
4472 }
4473 }
4474
4475 case OR_No_Viable_Function:
Sebastian Redl027de2a2009-05-21 11:50:50 +00004476 // For class as left operand for assignment or compound assigment operator
4477 // do not fall through to handling in built-in, but report that no overloaded
4478 // assignment operator found
Douglas Gregore9899d92009-08-26 17:08:25 +00004479 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004480 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4481 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004482 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl027de2a2009-05-21 11:50:50 +00004483 return ExprError();
4484 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004485 // No viable function; fall through to handling this as a
4486 // built-in operator, which will produce an error message for us.
4487 break;
4488
4489 case OR_Ambiguous:
4490 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4491 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004492 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004493 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4494 return ExprError();
4495
4496 case OR_Deleted:
4497 Diag(OpLoc, diag::err_ovl_deleted_oper)
4498 << Best->Function->isDeleted()
4499 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004500 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004501 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4502 return ExprError();
4503 }
4504
4505 // Either we found no viable overloaded operator or we matched a
4506 // built-in operator. In either case, try to build a built-in
4507 // operation.
Douglas Gregore9899d92009-08-26 17:08:25 +00004508 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004509}
4510
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004511/// BuildCallToMemberFunction - Build a call to a member
4512/// function. MemExpr is the expression that refers to the member
4513/// function (and includes the object parameter), Args/NumArgs are the
4514/// arguments to the function call (not including the object
4515/// parameter). The caller needs to validate that the member
4516/// expression refers to a member function or an overloaded member
4517/// function.
4518Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00004519Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4520 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004521 unsigned NumArgs, SourceLocation *CommaLocs,
4522 SourceLocation RParenLoc) {
4523 // Dig out the member expression. This holds both the object
4524 // argument and the member function we're referring to.
4525 MemberExpr *MemExpr = 0;
4526 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4527 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4528 else
4529 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4530 assert(MemExpr && "Building member call without member expression");
4531
4532 // Extract the object argument.
4533 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004534
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004535 CXXMethodDecl *Method = 0;
Douglas Gregor97628d62009-08-21 00:16:32 +00004536 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4537 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004538 // Add overload candidates
4539 OverloadCandidateSet CandidateSet;
Douglas Gregor97628d62009-08-21 00:16:32 +00004540 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004541
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004542 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4543 Func != FuncEnd; ++Func) {
4544 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
Mike Stump11289f42009-09-09 15:08:12 +00004545 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004546 /*SuppressUserConversions=*/false);
4547 else
Douglas Gregor84f14dd2009-09-01 00:37:14 +00004548 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4549 MemExpr->hasExplicitTemplateArgumentList(),
4550 MemExpr->getTemplateArgs(),
4551 MemExpr->getNumTemplateArgs(),
4552 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004553 CandidateSet,
4554 /*SuppressUsedConversions=*/false);
4555 }
Mike Stump11289f42009-09-09 15:08:12 +00004556
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004557 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004558 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004559 case OR_Success:
4560 Method = cast<CXXMethodDecl>(Best->Function);
4561 break;
4562
4563 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004564 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004565 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004566 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004567 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4568 // FIXME: Leaking incoming expressions!
4569 return true;
4570
4571 case OR_Ambiguous:
Mike Stump11289f42009-09-09 15:08:12 +00004572 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004573 diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004574 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004575 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4576 // FIXME: Leaking incoming expressions!
4577 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004578
4579 case OR_Deleted:
Mike Stump11289f42009-09-09 15:08:12 +00004580 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00004581 diag::err_ovl_deleted_member_call)
4582 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00004583 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004584 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4585 // FIXME: Leaking incoming expressions!
4586 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004587 }
4588
4589 FixOverloadedFunctionReference(MemExpr, Method);
4590 } else {
4591 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4592 }
4593
4594 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00004595 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004596 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00004597 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004598 Method->getResultType().getNonReferenceType(),
4599 RParenLoc));
4600
4601 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00004602 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004603 PerformObjectArgumentInitialization(ObjectArg, Method))
4604 return true;
4605 MemExpr->setBase(ObjectArg);
4606
4607 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004608 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004609 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004610 RParenLoc))
4611 return true;
4612
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004613 if (CheckFunctionCall(Method, TheCall.get()))
4614 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00004615
4616 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004617}
4618
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004619/// BuildCallToObjectOfClassType - Build a call to an object of class
4620/// type (C++ [over.call.object]), which can end up invoking an
4621/// overloaded function call operator (@c operator()) or performing a
4622/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00004623Sema::ExprResult
4624Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00004625 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004626 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004627 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004628 SourceLocation RParenLoc) {
4629 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004630 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00004631
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004632 // C++ [over.call.object]p1:
4633 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00004634 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004635 // candidate functions includes at least the function call
4636 // operators of T. The function call operators of T are obtained by
4637 // ordinary lookup of the name operator() in the context of
4638 // (E).operator().
4639 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00004640 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004641 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004642 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004643 Oper != OperEnd; ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00004644 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor55297ac2008-12-23 00:26:44 +00004645 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004646
Douglas Gregorab7897a2008-11-19 22:57:39 +00004647 // C++ [over.call.object]p2:
4648 // In addition, for each conversion function declared in T of the
4649 // form
4650 //
4651 // operator conversion-type-id () cv-qualifier;
4652 //
4653 // where cv-qualifier is the same cv-qualification as, or a
4654 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00004655 // denotes the type "pointer to function of (P1,...,Pn) returning
4656 // R", or the type "reference to pointer to function of
4657 // (P1,...,Pn) returning R", or the type "reference to function
4658 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00004659 // is also considered as a candidate function. Similarly,
4660 // surrogate call functions are added to the set of candidate
4661 // functions for each conversion function declared in an
4662 // accessible base class provided the function is not hidden
4663 // within T by another intervening declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004664
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004665 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4666 // FIXME: Look in base classes for more conversion operators!
Mike Stump11289f42009-09-09 15:08:12 +00004667 OverloadedFunctionDecl *Conversions
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004668 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00004669 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004670 Func = Conversions->function_begin(),
4671 FuncEnd = Conversions->function_end();
4672 Func != FuncEnd; ++Func) {
4673 CXXConversionDecl *Conv;
4674 FunctionTemplateDecl *ConvTemplate;
4675 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00004676
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004677 // Skip over templated conversion functions; they aren't
4678 // surrogates.
4679 if (ConvTemplate)
4680 continue;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004681
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004682 // Strip the reference type (if any) and then the pointer type (if
4683 // any) to get down to what might be a function type.
4684 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4685 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4686 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004687
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004688 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
4689 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4690 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004691 }
Mike Stump11289f42009-09-09 15:08:12 +00004692
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004693 // Perform overload resolution.
4694 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004695 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004696 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00004697 // Overload resolution succeeded; we'll build the appropriate call
4698 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004699 break;
4700
4701 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004702 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00004703 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004704 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00004705 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004706 break;
4707
4708 case OR_Ambiguous:
4709 Diag(Object->getSourceRange().getBegin(),
4710 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004711 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004712 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4713 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004714
4715 case OR_Deleted:
4716 Diag(Object->getSourceRange().getBegin(),
4717 diag::err_ovl_deleted_object_call)
4718 << Best->Function->isDeleted()
4719 << Object->getType() << Object->getSourceRange();
4720 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4721 break;
Mike Stump11289f42009-09-09 15:08:12 +00004722 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004723
Douglas Gregorab7897a2008-11-19 22:57:39 +00004724 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004725 // We had an error; delete all of the subexpressions and return
4726 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00004727 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004728 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00004729 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004730 return true;
4731 }
4732
Douglas Gregorab7897a2008-11-19 22:57:39 +00004733 if (Best->Function == 0) {
4734 // Since there is no function declaration, this is one of the
4735 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00004736 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00004737 = cast<CXXConversionDecl>(
4738 Best->Conversions[0].UserDefined.ConversionFunction);
4739
4740 // We selected one of the surrogate functions that converts the
4741 // object parameter to a function pointer. Perform the conversion
4742 // on the object argument, then let ActOnCallExpr finish the job.
4743 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004744 ImpCastExprToType(Object,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004745 Conv->getConversionType().getNonReferenceType(),
Anders Carlssona076d142009-07-31 01:23:52 +00004746 CastExpr::CK_Unknown,
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004747 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004748 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4749 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4750 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004751 }
4752
4753 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4754 // that calls this method, using Object for the implicit object
4755 // parameter and passing along the remaining arguments.
4756 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004757 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004758
4759 unsigned NumArgsInProto = Proto->getNumArgs();
4760 unsigned NumArgsToCheck = NumArgs;
4761
4762 // Build the full argument list for the method call (the
4763 // implicit object parameter is placed at the beginning of the
4764 // list).
4765 Expr **MethodArgs;
4766 if (NumArgs < NumArgsInProto) {
4767 NumArgsToCheck = NumArgsInProto;
4768 MethodArgs = new Expr*[NumArgsInProto + 1];
4769 } else {
4770 MethodArgs = new Expr*[NumArgs + 1];
4771 }
4772 MethodArgs[0] = Object;
4773 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4774 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00004775
4776 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004777 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004778 UsualUnaryConversions(NewFn);
4779
4780 // Once we've built TheCall, all of the expressions are properly
4781 // owned.
4782 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004783 ExprOwningPtr<CXXOperatorCallExpr>
4784 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004785 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00004786 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004787 delete [] MethodArgs;
4788
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004789 // We may have default arguments. If so, we need to allocate more
4790 // slots in the call for them.
4791 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00004792 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004793 else if (NumArgs > NumArgsInProto)
4794 NumArgsToCheck = NumArgsInProto;
4795
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004796 bool IsError = false;
4797
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004798 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004799 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004800 TheCall->setArg(0, Object);
4801
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004802
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004803 // Check the argument types.
4804 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004805 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004806 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004807 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00004808
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004809 // Pass the argument.
4810 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004811 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004812 } else {
Anders Carlssone8271232009-08-14 18:30:22 +00004813 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004814 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004815
4816 TheCall->setArg(i + 1, Arg);
4817 }
4818
4819 // If this is a variadic call, handle args passed through "...".
4820 if (Proto->isVariadic()) {
4821 // Promote the arguments (C99 6.5.2.2p7).
4822 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4823 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004824 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004825 TheCall->setArg(i + 1, Arg);
4826 }
4827 }
4828
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004829 if (IsError) return true;
4830
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004831 if (CheckFunctionCall(Method, TheCall.get()))
4832 return true;
4833
Anders Carlsson1c83deb2009-08-16 03:53:54 +00004834 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004835}
4836
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004837/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00004838/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004839/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00004840Sema::OwningExprResult
4841Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4842 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004843 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00004844
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004845 // C++ [over.ref]p1:
4846 //
4847 // [...] An expression x->m is interpreted as (x.operator->())->m
4848 // for a class object x of type T if T::operator->() exists and if
4849 // the operator is selected as the best match function by the
4850 // overload resolution mechanism (13.3).
4851 // FIXME: look in base classes.
4852 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4853 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004854 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00004855
Anders Carlsson78b54932009-09-10 23:18:36 +00004856 LookupResult R = LookupQualifiedName(BaseRecord->getDecl(), OpName,
4857 LookupOrdinaryName);
4858
4859 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
4860 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00004861 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004862 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004863
4864 // Perform overload resolution.
4865 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004866 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004867 case OR_Success:
4868 // Overload resolution succeeded; we'll build the call below.
4869 break;
4870
4871 case OR_No_Viable_Function:
4872 if (CandidateSet.empty())
4873 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00004874 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004875 else
4876 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00004877 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004878 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00004879 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004880
4881 case OR_Ambiguous:
4882 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00004883 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004884 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00004885 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004886
4887 case OR_Deleted:
4888 Diag(OpLoc, diag::err_ovl_deleted_oper)
4889 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00004890 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004891 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00004892 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004893 }
4894
4895 // Convert the object parameter.
4896 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00004897 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00004898 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00004899
4900 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00004901 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004902
4903 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00004904 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4905 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004906 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004907 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004908 Method->getResultType().getNonReferenceType(),
4909 OpLoc);
Douglas Gregord8061562009-08-06 03:17:00 +00004910 return Owned(Base);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004911}
4912
Douglas Gregorcd695e52008-11-10 20:40:00 +00004913/// FixOverloadedFunctionReference - E is an expression that refers to
4914/// a C++ overloaded function (possibly with some parentheses and
4915/// perhaps a '&' around it). We have resolved the overloaded function
4916/// to the function declaration Fn, so patch up the expression E to
4917/// refer (possibly indirectly) to Fn.
4918void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4919 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4920 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4921 E->setType(PE->getSubExpr()->getType());
4922 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00004923 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00004924 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004925 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4926 if (Method->isStatic()) {
4927 // Do nothing: static member functions aren't any different
4928 // from non-member functions.
Mike Stump11289f42009-09-09 15:08:12 +00004929 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004930 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4931 // We have taken the address of a pointer to member
4932 // function. Perform the computation here so that we get the
4933 // appropriate pointer to member type.
4934 DRE->setDecl(Fn);
4935 DRE->setType(Fn->getType());
4936 QualType ClassType
4937 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
Mike Stump11289f42009-09-09 15:08:12 +00004938 E->setType(Context.getMemberPointerType(Fn->getType(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004939 ClassType.getTypePtr()));
4940 return;
4941 }
4942 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004943 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00004944 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregorcd695e52008-11-10 20:40:00 +00004945 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor9b146582009-07-08 20:55:45 +00004946 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Mike Stump11289f42009-09-09 15:08:12 +00004947 isa<FunctionTemplateDecl>(DR->getDecl())) &&
Douglas Gregor9b146582009-07-08 20:55:45 +00004948 "Expected overloaded function or function template");
Douglas Gregorcd695e52008-11-10 20:40:00 +00004949 DR->setDecl(Fn);
4950 E->setType(Fn->getType());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004951 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4952 MemExpr->setMemberDecl(Fn);
4953 E->setType(Fn->getType());
Douglas Gregorcd695e52008-11-10 20:40:00 +00004954 } else {
4955 assert(false && "Invalid reference to overloaded function");
4956 }
4957}
4958
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004959} // end namespace clang