blob: 4891527e7b2a4feb64666c1fa4160c40145e7881 [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
Fariborz Jahanianc571f792009-09-10 22:26:16 +00001334void
1335Sema::AddAllConversionCandidate(CXXRecordDecl *ClassDecl, Expr *From,
1336 QualType ToType, bool AllowExplicit,
1337 OverloadCandidateSet &CandidateSet) {
1338 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1339 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1340 CXXRecordDecl *BaseClassDecl
1341 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1342 AddAllConversionCandidate(BaseClassDecl, From, ToType, AllowExplicit,
1343 CandidateSet);
1344 }
1345 for (CXXRecordDecl::base_class_iterator Base =
1346 ClassDecl->bases_begin(),
1347 E = ClassDecl->bases_end(); Base != E; ++Base) {
1348 if (Base->isVirtual())
1349 continue;
1350 CXXRecordDecl *BaseClassDecl
1351 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1352 AddAllConversionCandidate(BaseClassDecl, From, ToType, AllowExplicit,
1353 CandidateSet);
1354 }
1355
1356 OverloadedFunctionDecl *Conversions
1357 = ClassDecl->getConversionFunctions();
1358
1359 for (OverloadedFunctionDecl::function_iterator Func
1360 = Conversions->function_begin();
1361 Func != Conversions->function_end(); ++Func) {
1362 CXXConversionDecl *Conv;
1363 FunctionTemplateDecl *ConvTemplate;
1364 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1365 if (ConvTemplate)
1366 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1367 else
1368 Conv = dyn_cast<CXXConversionDecl>(*Func);
1369
1370 if (AllowExplicit || !Conv->isExplicit()) {
1371 if (ConvTemplate)
1372 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1373 CandidateSet);
1374 else
1375 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1376 }
1377 }
1378}
Douglas Gregor05155d82009-08-21 23:19:43 +00001379
Douglas Gregor576e98c2009-01-30 23:27:23 +00001380/// Determines whether there is a user-defined conversion sequence
1381/// (C++ [over.ics.user]) that converts expression From to the type
1382/// ToType. If such a conversion exists, User will contain the
1383/// user-defined conversion sequence that performs such a conversion
1384/// and this routine will return true. Otherwise, this routine returns
1385/// false and User is unspecified.
1386///
1387/// \param AllowConversionFunctions true if the conversion should
1388/// consider conversion functions at all. If false, only constructors
1389/// will be considered.
1390///
1391/// \param AllowExplicit true if the conversion should consider C++0x
1392/// "explicit" conversion functions as well as non-explicit conversion
1393/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001394///
1395/// \param ForceRValue true if the expression should be treated as an rvalue
1396/// for overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00001397bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001398 UserDefinedConversionSequence& User,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001399 bool AllowConversionFunctions,
Mike Stump11289f42009-09-09 15:08:12 +00001400 bool AllowExplicit, bool ForceRValue) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001401 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001402 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001403 if (CXXRecordDecl *ToRecordDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001404 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1405 // C++ [over.match.ctor]p1:
1406 // When objects of class type are direct-initialized (8.5), or
1407 // copy-initialized from an expression of the same or a
1408 // derived class type (8.5), overload resolution selects the
1409 // constructor. [...] For copy-initialization, the candidate
1410 // functions are all the converting constructors (12.3.1) of
1411 // that class. The argument list is the expression-list within
1412 // the parentheses of the initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001413 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001414 = Context.DeclarationNames.getCXXConstructorName(
1415 Context.getCanonicalType(ToType).getUnqualifiedType());
1416 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001417 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001418 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001419 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001420 // Find the constructor (which may be a template).
1421 CXXConstructorDecl *Constructor = 0;
1422 FunctionTemplateDecl *ConstructorTmpl
1423 = dyn_cast<FunctionTemplateDecl>(*Con);
1424 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001425 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001426 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1427 else
1428 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump11289f42009-09-09 15:08:12 +00001429
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001430 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001431 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001432 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001433 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001434 1, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00001435 /*SuppressUserConversions=*/true,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001436 ForceRValue);
1437 else
1438 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1439 /*SuppressUserConversions=*/true, ForceRValue);
1440 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001441 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001442 }
1443 }
1444
Douglas Gregor576e98c2009-01-30 23:27:23 +00001445 if (!AllowConversionFunctions) {
1446 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001447 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1448 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001449 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001450 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001451 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001452 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001453 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianc571f792009-09-10 22:26:16 +00001454 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl()))
1455 // Add all of the conversion functions as candidates.
1456 AddAllConversionCandidate(FromRecordDecl, From, ToType, AllowExplicit,
1457 CandidateSet);
Douglas Gregora1f013e2008-11-07 22:36:19 +00001458 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001459
1460 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001461 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001462 case OR_Success:
1463 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001464 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001465 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1466 // C++ [over.ics.user]p1:
1467 // If the user-defined conversion is specified by a
1468 // constructor (12.3.1), the initial standard conversion
1469 // sequence converts the source type to the type required by
1470 // the argument of the constructor.
1471 //
1472 // FIXME: What about ellipsis conversions?
1473 QualType ThisType = Constructor->getThisType(Context);
1474 User.Before = Best->Conversions[0].Standard;
1475 User.ConversionFunction = Constructor;
1476 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001477 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001478 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001479 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1480 return true;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001481 } else if (CXXConversionDecl *Conversion
1482 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1483 // C++ [over.ics.user]p1:
1484 //
1485 // [...] If the user-defined conversion is specified by a
1486 // conversion function (12.3.2), the initial standard
1487 // conversion sequence converts the source type to the
1488 // implicit object parameter of the conversion function.
1489 User.Before = Best->Conversions[0].Standard;
1490 User.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00001491
1492 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001493 // The second standard conversion sequence converts the
1494 // result of the user-defined conversion to the target type
1495 // for the sequence. Since an implicit conversion sequence
1496 // is an initialization, the special rules for
1497 // initialization by user-defined conversion apply when
1498 // selecting the best user-defined conversion for a
1499 // user-defined conversion sequence (see 13.3.3 and
1500 // 13.3.3.1).
1501 User.After = Best->FinalConversion;
1502 return true;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001503 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001504 assert(false && "Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001505 return false;
1506 }
Mike Stump11289f42009-09-09 15:08:12 +00001507
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001508 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001509 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001510 // No conversion here! We're done.
1511 return false;
1512
1513 case OR_Ambiguous:
1514 // FIXME: See C++ [over.best.ics]p10 for the handling of
1515 // ambiguous conversion sequences.
1516 return false;
1517 }
1518
1519 return false;
1520}
1521
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001522/// CompareImplicitConversionSequences - Compare two implicit
1523/// conversion sequences to determine whether one is better than the
1524/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001525ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001526Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1527 const ImplicitConversionSequence& ICS2)
1528{
1529 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1530 // conversion sequences (as defined in 13.3.3.1)
1531 // -- a standard conversion sequence (13.3.3.1.1) is a better
1532 // conversion sequence than a user-defined conversion sequence or
1533 // an ellipsis conversion sequence, and
1534 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1535 // conversion sequence than an ellipsis conversion sequence
1536 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001537 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001538 if (ICS1.ConversionKind < ICS2.ConversionKind)
1539 return ImplicitConversionSequence::Better;
1540 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1541 return ImplicitConversionSequence::Worse;
1542
1543 // Two implicit conversion sequences of the same form are
1544 // indistinguishable conversion sequences unless one of the
1545 // following rules apply: (C++ 13.3.3.2p3):
1546 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1547 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001548 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001549 ImplicitConversionSequence::UserDefinedConversion) {
1550 // User-defined conversion sequence U1 is a better conversion
1551 // sequence than another user-defined conversion sequence U2 if
1552 // they contain the same user-defined conversion function or
1553 // constructor and if the second standard conversion sequence of
1554 // U1 is better than the second standard conversion sequence of
1555 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001556 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001557 ICS2.UserDefined.ConversionFunction)
1558 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1559 ICS2.UserDefined.After);
1560 }
1561
1562 return ImplicitConversionSequence::Indistinguishable;
1563}
1564
1565/// CompareStandardConversionSequences - Compare two standard
1566/// conversion sequences to determine whether one is better than the
1567/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001568ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001569Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1570 const StandardConversionSequence& SCS2)
1571{
1572 // Standard conversion sequence S1 is a better conversion sequence
1573 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1574
1575 // -- S1 is a proper subsequence of S2 (comparing the conversion
1576 // sequences in the canonical form defined by 13.3.3.1.1,
1577 // excluding any Lvalue Transformation; the identity conversion
1578 // sequence is considered to be a subsequence of any
1579 // non-identity conversion sequence) or, if not that,
1580 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1581 // Neither is a proper subsequence of the other. Do nothing.
1582 ;
1583 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1584 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001585 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001586 SCS1.Third == ICK_Identity))
1587 // SCS1 is a proper subsequence of SCS2.
1588 return ImplicitConversionSequence::Better;
1589 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1590 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001591 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001592 SCS2.Third == ICK_Identity))
1593 // SCS2 is a proper subsequence of SCS1.
1594 return ImplicitConversionSequence::Worse;
1595
1596 // -- the rank of S1 is better than the rank of S2 (by the rules
1597 // defined below), or, if not that,
1598 ImplicitConversionRank Rank1 = SCS1.getRank();
1599 ImplicitConversionRank Rank2 = SCS2.getRank();
1600 if (Rank1 < Rank2)
1601 return ImplicitConversionSequence::Better;
1602 else if (Rank2 < Rank1)
1603 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001604
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001605 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1606 // are indistinguishable unless one of the following rules
1607 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001608
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001609 // A conversion that is not a conversion of a pointer, or
1610 // pointer to member, to bool is better than another conversion
1611 // that is such a conversion.
1612 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1613 return SCS2.isPointerConversionToBool()
1614 ? ImplicitConversionSequence::Better
1615 : ImplicitConversionSequence::Worse;
1616
Douglas Gregor5c407d92008-10-23 00:40:37 +00001617 // C++ [over.ics.rank]p4b2:
1618 //
1619 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001620 // conversion of B* to A* is better than conversion of B* to
1621 // void*, and conversion of A* to void* is better than conversion
1622 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001623 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001624 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001625 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001626 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001627 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1628 // Exactly one of the conversion sequences is a conversion to
1629 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001630 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1631 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001632 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1633 // Neither conversion sequence converts to a void pointer; compare
1634 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001635 if (ImplicitConversionSequence::CompareKind DerivedCK
1636 = CompareDerivedToBaseConversions(SCS1, SCS2))
1637 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001638 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1639 // Both conversion sequences are conversions to void
1640 // pointers. Compare the source types to determine if there's an
1641 // inheritance relationship in their sources.
1642 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1643 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1644
1645 // Adjust the types we're converting from via the array-to-pointer
1646 // conversion, if we need to.
1647 if (SCS1.First == ICK_Array_To_Pointer)
1648 FromType1 = Context.getArrayDecayedType(FromType1);
1649 if (SCS2.First == ICK_Array_To_Pointer)
1650 FromType2 = Context.getArrayDecayedType(FromType2);
1651
Mike Stump11289f42009-09-09 15:08:12 +00001652 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001653 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001654 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001655 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001656
1657 if (IsDerivedFrom(FromPointee2, FromPointee1))
1658 return ImplicitConversionSequence::Better;
1659 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1660 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001661
1662 // Objective-C++: If one interface is more specific than the
1663 // other, it is the better one.
1664 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1665 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1666 if (FromIface1 && FromIface1) {
1667 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1668 return ImplicitConversionSequence::Better;
1669 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1670 return ImplicitConversionSequence::Worse;
1671 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001672 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001673
1674 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1675 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001676 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001677 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001678 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001679
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001680 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001681 // C++0x [over.ics.rank]p3b4:
1682 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1683 // implicit object parameter of a non-static member function declared
1684 // without a ref-qualifier, and S1 binds an rvalue reference to an
1685 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001686 // FIXME: We don't know if we're dealing with the implicit object parameter,
1687 // or if the member function in this case has a ref qualifier.
1688 // (Of course, we don't have ref qualifiers yet.)
1689 if (SCS1.RRefBinding != SCS2.RRefBinding)
1690 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1691 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001692
1693 // C++ [over.ics.rank]p3b4:
1694 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1695 // which the references refer are the same type except for
1696 // top-level cv-qualifiers, and the type to which the reference
1697 // initialized by S2 refers is more cv-qualified than the type
1698 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001699 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1700 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001701 T1 = Context.getCanonicalType(T1);
1702 T2 = Context.getCanonicalType(T2);
1703 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1704 if (T2.isMoreQualifiedThan(T1))
1705 return ImplicitConversionSequence::Better;
1706 else if (T1.isMoreQualifiedThan(T2))
1707 return ImplicitConversionSequence::Worse;
1708 }
1709 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001710
1711 return ImplicitConversionSequence::Indistinguishable;
1712}
1713
1714/// CompareQualificationConversions - Compares two standard conversion
1715/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001716/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1717ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001718Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001719 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001720 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001721 // -- S1 and S2 differ only in their qualification conversion and
1722 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1723 // cv-qualification signature of type T1 is a proper subset of
1724 // the cv-qualification signature of type T2, and S1 is not the
1725 // deprecated string literal array-to-pointer conversion (4.2).
1726 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1727 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1728 return ImplicitConversionSequence::Indistinguishable;
1729
1730 // FIXME: the example in the standard doesn't use a qualification
1731 // conversion (!)
1732 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1733 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1734 T1 = Context.getCanonicalType(T1);
1735 T2 = Context.getCanonicalType(T2);
1736
1737 // If the types are the same, we won't learn anything by unwrapped
1738 // them.
1739 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1740 return ImplicitConversionSequence::Indistinguishable;
1741
Mike Stump11289f42009-09-09 15:08:12 +00001742 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001743 = ImplicitConversionSequence::Indistinguishable;
1744 while (UnwrapSimilarPointerTypes(T1, T2)) {
1745 // Within each iteration of the loop, we check the qualifiers to
1746 // determine if this still looks like a qualification
1747 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001748 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001749 // until there are no more pointers or pointers-to-members left
1750 // to unwrap. This essentially mimics what
1751 // IsQualificationConversion does, but here we're checking for a
1752 // strict subset of qualifiers.
1753 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1754 // The qualifiers are the same, so this doesn't tell us anything
1755 // about how the sequences rank.
1756 ;
1757 else if (T2.isMoreQualifiedThan(T1)) {
1758 // T1 has fewer qualifiers, so it could be the better sequence.
1759 if (Result == ImplicitConversionSequence::Worse)
1760 // Neither has qualifiers that are a subset of the other's
1761 // qualifiers.
1762 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001763
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001764 Result = ImplicitConversionSequence::Better;
1765 } else if (T1.isMoreQualifiedThan(T2)) {
1766 // T2 has fewer qualifiers, so it could be the better sequence.
1767 if (Result == ImplicitConversionSequence::Better)
1768 // Neither has qualifiers that are a subset of the other's
1769 // qualifiers.
1770 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001771
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001772 Result = ImplicitConversionSequence::Worse;
1773 } else {
1774 // Qualifiers are disjoint.
1775 return ImplicitConversionSequence::Indistinguishable;
1776 }
1777
1778 // If the types after this point are equivalent, we're done.
1779 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1780 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001781 }
1782
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001783 // Check that the winning standard conversion sequence isn't using
1784 // the deprecated string literal array to pointer conversion.
1785 switch (Result) {
1786 case ImplicitConversionSequence::Better:
1787 if (SCS1.Deprecated)
1788 Result = ImplicitConversionSequence::Indistinguishable;
1789 break;
1790
1791 case ImplicitConversionSequence::Indistinguishable:
1792 break;
1793
1794 case ImplicitConversionSequence::Worse:
1795 if (SCS2.Deprecated)
1796 Result = ImplicitConversionSequence::Indistinguishable;
1797 break;
1798 }
1799
1800 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001801}
1802
Douglas Gregor5c407d92008-10-23 00:40:37 +00001803/// CompareDerivedToBaseConversions - Compares two standard conversion
1804/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001805/// various kinds of derived-to-base conversions (C++
1806/// [over.ics.rank]p4b3). As part of these checks, we also look at
1807/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001808ImplicitConversionSequence::CompareKind
1809Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1810 const StandardConversionSequence& SCS2) {
1811 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1812 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1813 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1814 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1815
1816 // Adjust the types we're converting from via the array-to-pointer
1817 // conversion, if we need to.
1818 if (SCS1.First == ICK_Array_To_Pointer)
1819 FromType1 = Context.getArrayDecayedType(FromType1);
1820 if (SCS2.First == ICK_Array_To_Pointer)
1821 FromType2 = Context.getArrayDecayedType(FromType2);
1822
1823 // Canonicalize all of the types.
1824 FromType1 = Context.getCanonicalType(FromType1);
1825 ToType1 = Context.getCanonicalType(ToType1);
1826 FromType2 = Context.getCanonicalType(FromType2);
1827 ToType2 = Context.getCanonicalType(ToType2);
1828
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001829 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001830 //
1831 // If class B is derived directly or indirectly from class A and
1832 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001833 //
1834 // For Objective-C, we let A, B, and C also be Objective-C
1835 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001836
1837 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001838 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001839 SCS2.Second == ICK_Pointer_Conversion &&
1840 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1841 FromType1->isPointerType() && FromType2->isPointerType() &&
1842 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001843 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001844 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001845 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001846 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001847 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001848 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001849 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001850 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001851
1852 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1853 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1854 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1855 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1856
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001857 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001858 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1859 if (IsDerivedFrom(ToPointee1, ToPointee2))
1860 return ImplicitConversionSequence::Better;
1861 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1862 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001863
1864 if (ToIface1 && ToIface2) {
1865 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1866 return ImplicitConversionSequence::Better;
1867 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1868 return ImplicitConversionSequence::Worse;
1869 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001870 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001871
1872 // -- conversion of B* to A* is better than conversion of C* to A*,
1873 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1874 if (IsDerivedFrom(FromPointee2, FromPointee1))
1875 return ImplicitConversionSequence::Better;
1876 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1877 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001878
Douglas Gregor237f96c2008-11-26 23:31:11 +00001879 if (FromIface1 && FromIface2) {
1880 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1881 return ImplicitConversionSequence::Better;
1882 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1883 return ImplicitConversionSequence::Worse;
1884 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001885 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001886 }
1887
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001888 // Compare based on reference bindings.
1889 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1890 SCS1.Second == ICK_Derived_To_Base) {
1891 // -- binding of an expression of type C to a reference of type
1892 // B& is better than binding an expression of type C to a
1893 // reference of type A&,
1894 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1895 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1896 if (IsDerivedFrom(ToType1, ToType2))
1897 return ImplicitConversionSequence::Better;
1898 else if (IsDerivedFrom(ToType2, ToType1))
1899 return ImplicitConversionSequence::Worse;
1900 }
1901
Douglas Gregor2fe98832008-11-03 19:09:14 +00001902 // -- binding of an expression of type B to a reference of type
1903 // A& is better than binding an expression of type C to a
1904 // reference of type A&,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001905 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1906 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1907 if (IsDerivedFrom(FromType2, FromType1))
1908 return ImplicitConversionSequence::Better;
1909 else if (IsDerivedFrom(FromType1, FromType2))
1910 return ImplicitConversionSequence::Worse;
1911 }
1912 }
1913
1914
1915 // FIXME: conversion of A::* to B::* is better than conversion of
1916 // A::* to C::*,
1917
1918 // FIXME: conversion of B::* to C::* is better than conversion of
1919 // A::* to C::*, and
1920
Douglas Gregor2fe98832008-11-03 19:09:14 +00001921 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1922 SCS1.Second == ICK_Derived_To_Base) {
1923 // -- conversion of C to B is better than conversion of C to A,
1924 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1925 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1926 if (IsDerivedFrom(ToType1, ToType2))
1927 return ImplicitConversionSequence::Better;
1928 else if (IsDerivedFrom(ToType2, ToType1))
1929 return ImplicitConversionSequence::Worse;
1930 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001931
Douglas Gregor2fe98832008-11-03 19:09:14 +00001932 // -- conversion of B to A is better than conversion of C to A.
1933 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1934 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1935 if (IsDerivedFrom(FromType2, FromType1))
1936 return ImplicitConversionSequence::Better;
1937 else if (IsDerivedFrom(FromType1, FromType2))
1938 return ImplicitConversionSequence::Worse;
1939 }
1940 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001941
Douglas Gregor5c407d92008-10-23 00:40:37 +00001942 return ImplicitConversionSequence::Indistinguishable;
1943}
1944
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001945/// TryCopyInitialization - Try to copy-initialize a value of type
1946/// ToType from the expression From. Return the implicit conversion
1947/// sequence required to pass this argument, which may be a bad
1948/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00001949/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00001950/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1951/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00001952ImplicitConversionSequence
1953Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00001954 bool SuppressUserConversions, bool ForceRValue,
1955 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001956 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001957 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00001958 CheckReferenceInit(From, ToType,
Anders Carlsson271e3a42009-08-27 17:30:43 +00001959 SuppressUserConversions,
1960 /*AllowExplicit=*/false,
1961 ForceRValue,
1962 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001963 return ICS;
1964 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001965 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001966 SuppressUserConversions,
1967 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001968 ForceRValue,
1969 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001970 }
1971}
1972
Sebastian Redl42e92c42009-04-12 17:16:29 +00001973/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1974/// the expression @p From. Returns true (and emits a diagnostic) if there was
1975/// an error, returns false if the initialization succeeded. Elidable should
1976/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1977/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00001978bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00001979 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001980 if (!getLangOptions().CPlusPlus) {
1981 // In C, argument passing is the same as performing an assignment.
1982 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001983
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001984 AssignConvertType ConvTy =
1985 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00001986 if (ConvTy != Compatible &&
1987 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1988 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00001989
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001990 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1991 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001992 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00001993
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001994 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00001995 return CheckReferenceInit(From, ToType,
1996 /*SuppressUserConversions=*/false,
1997 /*AllowExplicit=*/false,
1998 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001999
Sebastian Redl42e92c42009-04-12 17:16:29 +00002000 if (!PerformImplicitConversion(From, ToType, Flavor,
2001 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002002 return false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00002003
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002004 return Diag(From->getSourceRange().getBegin(),
2005 diag::err_typecheck_convert_incompatible)
2006 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002007}
2008
Douglas Gregor436424c2008-11-18 23:14:02 +00002009/// TryObjectArgumentInitialization - Try to initialize the object
2010/// parameter of the given member function (@c Method) from the
2011/// expression @p From.
2012ImplicitConversionSequence
2013Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2014 QualType ClassType = Context.getTypeDeclType(Method->getParent());
2015 unsigned MethodQuals = Method->getTypeQualifiers();
2016 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
2017
2018 // Set up the conversion sequence as a "bad" conversion, to allow us
2019 // to exit early.
2020 ImplicitConversionSequence ICS;
2021 ICS.Standard.setAsIdentityConversion();
2022 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2023
2024 // We need to have an object of class type.
2025 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002026 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002027 FromType = PT->getPointeeType();
2028
2029 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002030
2031 // The implicit object parmeter is has the type "reference to cv X",
2032 // where X is the class of which the function is a member
2033 // (C++ [over.match.funcs]p4). However, when finding an implicit
2034 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002035 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002036 // (C++ [over.match.funcs]p5). We perform a simplified version of
2037 // reference binding here, that allows class rvalues to bind to
2038 // non-constant references.
2039
2040 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2041 // with the implicit object parameter (C++ [over.match.funcs]p5).
2042 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2043 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2044 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2045 return ICS;
2046
2047 // Check that we have either the same type or a derived type. It
2048 // affects the conversion rank.
2049 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2050 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2051 ICS.Standard.Second = ICK_Identity;
2052 else if (IsDerivedFrom(FromType, ClassType))
2053 ICS.Standard.Second = ICK_Derived_To_Base;
2054 else
2055 return ICS;
2056
2057 // Success. Mark this as a reference binding.
2058 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2059 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2060 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2061 ICS.Standard.ReferenceBinding = true;
2062 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002063 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002064 return ICS;
2065}
2066
2067/// PerformObjectArgumentInitialization - Perform initialization of
2068/// the implicit object parameter for the given Method with the given
2069/// expression.
2070bool
2071Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002072 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002073 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002074 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002075
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002076 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002077 FromRecordType = PT->getPointeeType();
2078 DestType = Method->getThisType(Context);
2079 } else {
2080 FromRecordType = From->getType();
2081 DestType = ImplicitParamRecordType;
2082 }
2083
Mike Stump11289f42009-09-09 15:08:12 +00002084 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002085 = TryObjectArgumentInitialization(From, Method);
2086 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2087 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002088 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002089 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002090
Douglas Gregor436424c2008-11-18 23:14:02 +00002091 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002092 CheckDerivedToBaseConversion(FromRecordType,
2093 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002094 From->getSourceRange().getBegin(),
2095 From->getSourceRange()))
2096 return true;
2097
Mike Stump11289f42009-09-09 15:08:12 +00002098 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002099 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002100 return false;
2101}
2102
Douglas Gregor5fb53972009-01-14 15:45:31 +00002103/// TryContextuallyConvertToBool - Attempt to contextually convert the
2104/// expression From to bool (C++0x [conv]p3).
2105ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002106 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002107 // FIXME: Are these flags correct?
2108 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002109 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002110 /*ForceRValue=*/false,
2111 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002112}
2113
2114/// PerformContextuallyConvertToBool - Perform a contextual conversion
2115/// of the expression From to bool (C++0x [conv]p3).
2116bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2117 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2118 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2119 return false;
2120
Mike Stump11289f42009-09-09 15:08:12 +00002121 return Diag(From->getSourceRange().getBegin(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002122 diag::err_typecheck_bool_condition)
2123 << From->getType() << From->getSourceRange();
2124}
2125
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002126/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002127/// candidate functions, using the given function call arguments. If
2128/// @p SuppressUserConversions, then don't allow user-defined
2129/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002130/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2131/// hacky way to implement the overloading rules for elidable copy
2132/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002133void
2134Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002135 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002136 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002137 bool SuppressUserConversions,
Mike Stump11289f42009-09-09 15:08:12 +00002138 bool ForceRValue) {
2139 const FunctionProtoType* Proto
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002140 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002141 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002142 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002143 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002144 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002145 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002146
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002147 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002148 if (!isa<CXXConstructorDecl>(Method)) {
2149 // If we get here, it's because we're calling a member function
2150 // that is named without a member access expression (e.g.,
2151 // "this->f") that was either written explicitly or created
2152 // implicitly. This can happen with a qualified call to a member
2153 // function, e.g., X::f(). We use a NULL object as the implied
2154 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002155 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002156 SuppressUserConversions, ForceRValue);
2157 return;
2158 }
2159 // We treat a constructor like a non-member function, since its object
2160 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002161 }
2162
2163
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002164 // Add this candidate
2165 CandidateSet.push_back(OverloadCandidate());
2166 OverloadCandidate& Candidate = CandidateSet.back();
2167 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002168 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002169 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002170 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002171
2172 unsigned NumArgsInProto = Proto->getNumArgs();
2173
2174 // (C++ 13.3.2p2): A candidate function having fewer than m
2175 // parameters is viable only if it has an ellipsis in its parameter
2176 // list (8.3.5).
2177 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2178 Candidate.Viable = false;
2179 return;
2180 }
2181
2182 // (C++ 13.3.2p2): A candidate function having more than m parameters
2183 // is viable only if the (m+1)st parameter has a default argument
2184 // (8.3.6). For the purposes of overload resolution, the
2185 // parameter list is truncated on the right, so that there are
2186 // exactly m parameters.
2187 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2188 if (NumArgs < MinRequiredArgs) {
2189 // Not enough arguments.
2190 Candidate.Viable = false;
2191 return;
2192 }
2193
2194 // Determine the implicit conversion sequences for each of the
2195 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002196 Candidate.Conversions.resize(NumArgs);
2197 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2198 if (ArgIdx < NumArgsInProto) {
2199 // (C++ 13.3.2p3): for F to be a viable function, there shall
2200 // exist for each argument an implicit conversion sequence
2201 // (13.3.3.1) that converts that argument to the corresponding
2202 // parameter of F.
2203 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002204 Candidate.Conversions[ArgIdx]
2205 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002206 SuppressUserConversions, ForceRValue,
2207 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002208 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002209 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002210 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002211 break;
2212 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002213 } else {
2214 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2215 // argument for which there is no corresponding parameter is
2216 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002217 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002218 = ImplicitConversionSequence::EllipsisConversion;
2219 }
2220 }
2221}
2222
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002223/// \brief Add all of the function declarations in the given function set to
2224/// the overload canddiate set.
2225void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2226 Expr **Args, unsigned NumArgs,
2227 OverloadCandidateSet& CandidateSet,
2228 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002229 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002230 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002231 F != FEnd; ++F) {
2232 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
Mike Stump11289f42009-09-09 15:08:12 +00002233 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002234 SuppressUserConversions);
2235 else
Douglas Gregor89026b52009-06-30 23:57:56 +00002236 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2237 /*FIXME: explicit args */false, 0, 0,
Mike Stump11289f42009-09-09 15:08:12 +00002238 Args, NumArgs, CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002239 SuppressUserConversions);
2240 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002241}
2242
Douglas Gregor436424c2008-11-18 23:14:02 +00002243/// AddMethodCandidate - Adds the given C++ member function to the set
2244/// of candidate functions, using the given function call arguments
2245/// and the object argument (@c Object). For example, in a call
2246/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2247/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2248/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002249/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2250/// a slightly hacky way to implement the overloading rules for elidable copy
2251/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002252void
Douglas Gregor436424c2008-11-18 23:14:02 +00002253Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2254 Expr **Args, unsigned NumArgs,
2255 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002256 bool SuppressUserConversions, bool ForceRValue) {
2257 const FunctionProtoType* Proto
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002258 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002259 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002260 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002261 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002262 assert(!isa<CXXConstructorDecl>(Method) &&
2263 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002264
2265 // Add this candidate
2266 CandidateSet.push_back(OverloadCandidate());
2267 OverloadCandidate& Candidate = CandidateSet.back();
2268 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002269 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002270 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002271
2272 unsigned NumArgsInProto = Proto->getNumArgs();
2273
2274 // (C++ 13.3.2p2): A candidate function having fewer than m
2275 // parameters is viable only if it has an ellipsis in its parameter
2276 // list (8.3.5).
2277 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2278 Candidate.Viable = false;
2279 return;
2280 }
2281
2282 // (C++ 13.3.2p2): A candidate function having more than m parameters
2283 // is viable only if the (m+1)st parameter has a default argument
2284 // (8.3.6). For the purposes of overload resolution, the
2285 // parameter list is truncated on the right, so that there are
2286 // exactly m parameters.
2287 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2288 if (NumArgs < MinRequiredArgs) {
2289 // Not enough arguments.
2290 Candidate.Viable = false;
2291 return;
2292 }
2293
2294 Candidate.Viable = true;
2295 Candidate.Conversions.resize(NumArgs + 1);
2296
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002297 if (Method->isStatic() || !Object)
2298 // The implicit object argument is ignored.
2299 Candidate.IgnoreObjectArgument = true;
2300 else {
2301 // Determine the implicit conversion sequence for the object
2302 // parameter.
2303 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002304 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002305 == ImplicitConversionSequence::BadConversion) {
2306 Candidate.Viable = false;
2307 return;
2308 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002309 }
2310
2311 // Determine the implicit conversion sequences for each of the
2312 // arguments.
2313 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2314 if (ArgIdx < NumArgsInProto) {
2315 // (C++ 13.3.2p3): for F to be a viable function, there shall
2316 // exist for each argument an implicit conversion sequence
2317 // (13.3.3.1) that converts that argument to the corresponding
2318 // parameter of F.
2319 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002320 Candidate.Conversions[ArgIdx + 1]
2321 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002322 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002323 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002324 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002325 == ImplicitConversionSequence::BadConversion) {
2326 Candidate.Viable = false;
2327 break;
2328 }
2329 } else {
2330 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2331 // argument for which there is no corresponding parameter is
2332 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002333 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002334 = ImplicitConversionSequence::EllipsisConversion;
2335 }
2336 }
2337}
2338
Douglas Gregor97628d62009-08-21 00:16:32 +00002339/// \brief Add a C++ member function template as a candidate to the candidate
2340/// set, using template argument deduction to produce an appropriate member
2341/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002342void
Douglas Gregor97628d62009-08-21 00:16:32 +00002343Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2344 bool HasExplicitTemplateArgs,
2345 const TemplateArgument *ExplicitTemplateArgs,
2346 unsigned NumExplicitTemplateArgs,
2347 Expr *Object, Expr **Args, unsigned NumArgs,
2348 OverloadCandidateSet& CandidateSet,
2349 bool SuppressUserConversions,
2350 bool ForceRValue) {
2351 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002352 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002353 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002354 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002355 // candidate functions in the usual way.113) A given name can refer to one
2356 // or more function templates and also to a set of overloaded non-template
2357 // functions. In such a case, the candidate functions generated from each
2358 // function template are combined with the set of non-template candidate
2359 // functions.
2360 TemplateDeductionInfo Info(Context);
2361 FunctionDecl *Specialization = 0;
2362 if (TemplateDeductionResult Result
2363 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2364 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2365 Args, NumArgs, Specialization, Info)) {
2366 // FIXME: Record what happened with template argument deduction, so
2367 // that we can give the user a beautiful diagnostic.
2368 (void)Result;
2369 return;
2370 }
Mike Stump11289f42009-09-09 15:08:12 +00002371
Douglas Gregor97628d62009-08-21 00:16:32 +00002372 // Add the function template specialization produced by template argument
2373 // deduction as a candidate.
2374 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002375 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002376 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002377 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002378 CandidateSet, SuppressUserConversions, ForceRValue);
2379}
2380
Douglas Gregor05155d82009-08-21 23:19:43 +00002381/// \brief Add a C++ function template specialization as a candidate
2382/// in the candidate set, using template argument deduction to produce
2383/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002384void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002385Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor89026b52009-06-30 23:57:56 +00002386 bool HasExplicitTemplateArgs,
2387 const TemplateArgument *ExplicitTemplateArgs,
2388 unsigned NumExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002389 Expr **Args, unsigned NumArgs,
2390 OverloadCandidateSet& CandidateSet,
2391 bool SuppressUserConversions,
2392 bool ForceRValue) {
2393 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002394 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002395 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002396 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002397 // candidate functions in the usual way.113) A given name can refer to one
2398 // or more function templates and also to a set of overloaded non-template
2399 // functions. In such a case, the candidate functions generated from each
2400 // function template are combined with the set of non-template candidate
2401 // functions.
2402 TemplateDeductionInfo Info(Context);
2403 FunctionDecl *Specialization = 0;
2404 if (TemplateDeductionResult Result
Douglas Gregor89026b52009-06-30 23:57:56 +00002405 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2406 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2407 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002408 // FIXME: Record what happened with template argument deduction, so
2409 // that we can give the user a beautiful diagnostic.
2410 (void)Result;
2411 return;
2412 }
Mike Stump11289f42009-09-09 15:08:12 +00002413
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002414 // Add the function template specialization produced by template argument
2415 // deduction as a candidate.
2416 assert(Specialization && "Missing function template specialization?");
2417 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2418 SuppressUserConversions, ForceRValue);
2419}
Mike Stump11289f42009-09-09 15:08:12 +00002420
Douglas Gregora1f013e2008-11-07 22:36:19 +00002421/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002422/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002423/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002424/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002425/// (which may or may not be the same type as the type that the
2426/// conversion function produces).
2427void
2428Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2429 Expr *From, QualType ToType,
2430 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002431 assert(!Conversion->getDescribedFunctionTemplate() &&
2432 "Conversion function templates use AddTemplateConversionCandidate");
2433
Douglas Gregora1f013e2008-11-07 22:36:19 +00002434 // Add this candidate
2435 CandidateSet.push_back(OverloadCandidate());
2436 OverloadCandidate& Candidate = CandidateSet.back();
2437 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002438 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002439 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002440 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002441 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002442 = Conversion->getConversionType().getAsOpaquePtr();
2443 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2444
Douglas Gregor436424c2008-11-18 23:14:02 +00002445 // Determine the implicit conversion sequence for the implicit
2446 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002447 Candidate.Viable = true;
2448 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002449 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregora1f013e2008-11-07 22:36:19 +00002450
Mike Stump11289f42009-09-09 15:08:12 +00002451 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002452 == ImplicitConversionSequence::BadConversion) {
2453 Candidate.Viable = false;
2454 return;
2455 }
2456
2457 // To determine what the conversion from the result of calling the
2458 // conversion function to the type we're eventually trying to
2459 // convert to (ToType), we need to synthesize a call to the
2460 // conversion function and attempt copy initialization from it. This
2461 // makes sure that we get the right semantics with respect to
2462 // lvalues/rvalues and the type. Fortunately, we can allocate this
2463 // call on the stack and we don't need its arguments to be
2464 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002465 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregora1f013e2008-11-07 22:36:19 +00002466 SourceLocation());
2467 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlssona2615922009-07-31 00:48:10 +00002468 CastExpr::CK_Unknown,
Douglas Gregora11693b2008-11-12 17:17:38 +00002469 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002470
2471 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002472 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2473 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002474 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002475 Conversion->getConversionType().getNonReferenceType(),
2476 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002477 ImplicitConversionSequence ICS =
2478 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002479 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002480 /*ForceRValue=*/false,
2481 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002482
Douglas Gregora1f013e2008-11-07 22:36:19 +00002483 switch (ICS.ConversionKind) {
2484 case ImplicitConversionSequence::StandardConversion:
2485 Candidate.FinalConversion = ICS.Standard;
2486 break;
2487
2488 case ImplicitConversionSequence::BadConversion:
2489 Candidate.Viable = false;
2490 break;
2491
2492 default:
Mike Stump11289f42009-09-09 15:08:12 +00002493 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002494 "Can only end up with a standard conversion sequence or failure");
2495 }
2496}
2497
Douglas Gregor05155d82009-08-21 23:19:43 +00002498/// \brief Adds a conversion function template specialization
2499/// candidate to the overload set, using template argument deduction
2500/// to deduce the template arguments of the conversion function
2501/// template from the type that we are converting to (C++
2502/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002503void
Douglas Gregor05155d82009-08-21 23:19:43 +00002504Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2505 Expr *From, QualType ToType,
2506 OverloadCandidateSet &CandidateSet) {
2507 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2508 "Only conversion function templates permitted here");
2509
2510 TemplateDeductionInfo Info(Context);
2511 CXXConversionDecl *Specialization = 0;
2512 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002513 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002514 Specialization, Info)) {
2515 // FIXME: Record what happened with template argument deduction, so
2516 // that we can give the user a beautiful diagnostic.
2517 (void)Result;
2518 return;
2519 }
Mike Stump11289f42009-09-09 15:08:12 +00002520
Douglas Gregor05155d82009-08-21 23:19:43 +00002521 // Add the conversion function template specialization produced by
2522 // template argument deduction as a candidate.
2523 assert(Specialization && "Missing function template specialization?");
2524 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2525}
2526
Douglas Gregorab7897a2008-11-19 22:57:39 +00002527/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2528/// converts the given @c Object to a function pointer via the
2529/// conversion function @c Conversion, and then attempts to call it
2530/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2531/// the type of function that we'll eventually be calling.
2532void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002533 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002534 Expr *Object, Expr **Args, unsigned NumArgs,
2535 OverloadCandidateSet& CandidateSet) {
2536 CandidateSet.push_back(OverloadCandidate());
2537 OverloadCandidate& Candidate = CandidateSet.back();
2538 Candidate.Function = 0;
2539 Candidate.Surrogate = Conversion;
2540 Candidate.Viable = true;
2541 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002542 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002543 Candidate.Conversions.resize(NumArgs + 1);
2544
2545 // Determine the implicit conversion sequence for the implicit
2546 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002547 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002548 = TryObjectArgumentInitialization(Object, Conversion);
2549 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2550 Candidate.Viable = false;
2551 return;
2552 }
2553
2554 // The first conversion is actually a user-defined conversion whose
2555 // first conversion is ObjectInit's standard conversion (which is
2556 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002557 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002558 = ImplicitConversionSequence::UserDefinedConversion;
2559 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2560 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002561 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002562 = Candidate.Conversions[0].UserDefined.Before;
2563 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2564
Mike Stump11289f42009-09-09 15:08:12 +00002565 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002566 unsigned NumArgsInProto = Proto->getNumArgs();
2567
2568 // (C++ 13.3.2p2): A candidate function having fewer than m
2569 // parameters is viable only if it has an ellipsis in its parameter
2570 // list (8.3.5).
2571 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2572 Candidate.Viable = false;
2573 return;
2574 }
2575
2576 // Function types don't have any default arguments, so just check if
2577 // we have enough arguments.
2578 if (NumArgs < NumArgsInProto) {
2579 // Not enough arguments.
2580 Candidate.Viable = false;
2581 return;
2582 }
2583
2584 // Determine the implicit conversion sequences for each of the
2585 // arguments.
2586 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2587 if (ArgIdx < NumArgsInProto) {
2588 // (C++ 13.3.2p3): for F to be a viable function, there shall
2589 // exist for each argument an implicit conversion sequence
2590 // (13.3.3.1) that converts that argument to the corresponding
2591 // parameter of F.
2592 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002593 Candidate.Conversions[ArgIdx + 1]
2594 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002595 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002596 /*ForceRValue=*/false,
2597 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002598 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002599 == ImplicitConversionSequence::BadConversion) {
2600 Candidate.Viable = false;
2601 break;
2602 }
2603 } else {
2604 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2605 // argument for which there is no corresponding parameter is
2606 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002607 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002608 = ImplicitConversionSequence::EllipsisConversion;
2609 }
2610 }
2611}
2612
Mike Stump87c57ac2009-05-16 07:39:55 +00002613// FIXME: This will eventually be removed, once we've migrated all of the
2614// operator overloading logic over to the scheme used by binary operators, which
2615// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002616void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002617 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002618 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002619 OverloadCandidateSet& CandidateSet,
2620 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002621
2622 FunctionSet Functions;
2623
2624 QualType T1 = Args[0]->getType();
2625 QualType T2;
2626 if (NumArgs > 1)
2627 T2 = Args[1]->getType();
2628
2629 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002630 if (S)
2631 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002632 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2633 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2634 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2635 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2636}
2637
2638/// \brief Add overload candidates for overloaded operators that are
2639/// member functions.
2640///
2641/// Add the overloaded operator candidates that are member functions
2642/// for the operator Op that was used in an operator expression such
2643/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2644/// CandidateSet will store the added overload candidates. (C++
2645/// [over.match.oper]).
2646void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2647 SourceLocation OpLoc,
2648 Expr **Args, unsigned NumArgs,
2649 OverloadCandidateSet& CandidateSet,
2650 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002651 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2652
2653 // C++ [over.match.oper]p3:
2654 // For a unary operator @ with an operand of a type whose
2655 // cv-unqualified version is T1, and for a binary operator @ with
2656 // a left operand of a type whose cv-unqualified version is T1 and
2657 // a right operand of a type whose cv-unqualified version is T2,
2658 // three sets of candidate functions, designated member
2659 // candidates, non-member candidates and built-in candidates, are
2660 // constructed as follows:
2661 QualType T1 = Args[0]->getType();
2662 QualType T2;
2663 if (NumArgs > 1)
2664 T2 = Args[1]->getType();
2665
2666 // -- If T1 is a class type, the set of member candidates is the
2667 // result of the qualified lookup of T1::operator@
2668 // (13.3.1.1.1); otherwise, the set of member candidates is
2669 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002670 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002671 // Complete the type if it can be completed. Otherwise, we're done.
2672 if (RequireCompleteType(OpLoc, T1, PartialDiagnostic(0)))
2673 return;
Mike Stump11289f42009-09-09 15:08:12 +00002674
2675 LookupResult Operators = LookupQualifiedName(T1Rec->getDecl(), OpName,
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002676 LookupOrdinaryName, false);
Mike Stump11289f42009-09-09 15:08:12 +00002677 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002678 OperEnd = Operators.end();
2679 Oper != OperEnd;
2680 ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00002681 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
Douglas Gregor55297ac2008-12-23 00:26:44 +00002682 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor436424c2008-11-18 23:14:02 +00002683 /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002684 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002685}
2686
Douglas Gregora11693b2008-11-12 17:17:38 +00002687/// AddBuiltinCandidate - Add a candidate for a built-in
2688/// operator. ResultTy and ParamTys are the result and parameter types
2689/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002690/// arguments being passed to the candidate. IsAssignmentOperator
2691/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002692/// operator. NumContextualBoolArguments is the number of arguments
2693/// (at the beginning of the argument list) that will be contextually
2694/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002695void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002696 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002697 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002698 bool IsAssignmentOperator,
2699 unsigned NumContextualBoolArguments) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002700 // Add this candidate
2701 CandidateSet.push_back(OverloadCandidate());
2702 OverloadCandidate& Candidate = CandidateSet.back();
2703 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002704 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002705 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002706 Candidate.BuiltinTypes.ResultTy = ResultTy;
2707 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2708 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2709
2710 // Determine the implicit conversion sequences for each of the
2711 // arguments.
2712 Candidate.Viable = true;
2713 Candidate.Conversions.resize(NumArgs);
2714 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002715 // C++ [over.match.oper]p4:
2716 // For the built-in assignment operators, conversions of the
2717 // left operand are restricted as follows:
2718 // -- no temporaries are introduced to hold the left operand, and
2719 // -- no user-defined conversions are applied to the left
2720 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002721 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002722 //
2723 // We block these conversions by turning off user-defined
2724 // conversions, since that is the only way that initialization of
2725 // a reference to a non-class type can occur from something that
2726 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002727 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002728 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002729 "Contextual conversion to bool requires bool type");
2730 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2731 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002732 Candidate.Conversions[ArgIdx]
2733 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002734 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002735 /*ForceRValue=*/false,
2736 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002737 }
Mike Stump11289f42009-09-09 15:08:12 +00002738 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002739 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002740 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002741 break;
2742 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002743 }
2744}
2745
2746/// BuiltinCandidateTypeSet - A set of types that will be used for the
2747/// candidate operator functions for built-in operators (C++
2748/// [over.built]). The types are separated into pointer types and
2749/// enumeration types.
2750class BuiltinCandidateTypeSet {
2751 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002752 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002753
2754 /// PointerTypes - The set of pointer types that will be used in the
2755 /// built-in candidates.
2756 TypeSet PointerTypes;
2757
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002758 /// MemberPointerTypes - The set of member pointer types that will be
2759 /// used in the built-in candidates.
2760 TypeSet MemberPointerTypes;
2761
Douglas Gregora11693b2008-11-12 17:17:38 +00002762 /// EnumerationTypes - The set of enumeration types that will be
2763 /// used in the built-in candidates.
2764 TypeSet EnumerationTypes;
2765
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002766 /// Sema - The semantic analysis instance where we are building the
2767 /// candidate type set.
2768 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002769
Douglas Gregora11693b2008-11-12 17:17:38 +00002770 /// Context - The AST context in which we will build the type sets.
2771 ASTContext &Context;
2772
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002773 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2774 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002775
2776public:
2777 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002778 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002779
Mike Stump11289f42009-09-09 15:08:12 +00002780 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002781 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002782
Douglas Gregor5fb53972009-01-14 15:45:31 +00002783 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2784 bool AllowExplicitConversions);
Douglas Gregora11693b2008-11-12 17:17:38 +00002785
2786 /// pointer_begin - First pointer type found;
2787 iterator pointer_begin() { return PointerTypes.begin(); }
2788
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002789 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002790 iterator pointer_end() { return PointerTypes.end(); }
2791
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002792 /// member_pointer_begin - First member pointer type found;
2793 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2794
2795 /// member_pointer_end - Past the last member pointer type found;
2796 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2797
Douglas Gregora11693b2008-11-12 17:17:38 +00002798 /// enumeration_begin - First enumeration type found;
2799 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2800
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002801 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002802 iterator enumeration_end() { return EnumerationTypes.end(); }
2803};
2804
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002805/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00002806/// the set of pointer types along with any more-qualified variants of
2807/// that type. For example, if @p Ty is "int const *", this routine
2808/// will add "int const *", "int const volatile *", "int const
2809/// restrict *", and "int const volatile restrict *" to the set of
2810/// pointer types. Returns true if the add of @p Ty itself succeeded,
2811/// false otherwise.
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002812bool
2813BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002814 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002815 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002816 return false;
2817
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002818 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002819 QualType PointeeTy = PointerTy->getPointeeType();
2820 // FIXME: Optimize this so that we don't keep trying to add the same types.
2821
Mike Stump87c57ac2009-05-16 07:39:55 +00002822 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2823 // pointer conversions that don't cast away constness?
Douglas Gregora11693b2008-11-12 17:17:38 +00002824 if (!PointeeTy.isConstQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002825 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002826 (Context.getPointerType(PointeeTy.withConst()));
2827 if (!PointeeTy.isVolatileQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002828 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002829 (Context.getPointerType(PointeeTy.withVolatile()));
2830 if (!PointeeTy.isRestrictQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002831 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002832 (Context.getPointerType(PointeeTy.withRestrict()));
2833 }
2834
2835 return true;
2836}
2837
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002838/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2839/// to the set of pointer types along with any more-qualified variants of
2840/// that type. For example, if @p Ty is "int const *", this routine
2841/// will add "int const *", "int const volatile *", "int const
2842/// restrict *", and "int const volatile restrict *" to the set of
2843/// pointer types. Returns true if the add of @p Ty itself succeeded,
2844/// false otherwise.
2845bool
2846BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2847 QualType Ty) {
2848 // Insert this type.
2849 if (!MemberPointerTypes.insert(Ty))
2850 return false;
2851
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002852 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002853 QualType PointeeTy = PointerTy->getPointeeType();
2854 const Type *ClassTy = PointerTy->getClass();
2855 // FIXME: Optimize this so that we don't keep trying to add the same types.
2856
2857 if (!PointeeTy.isConstQualified())
2858 AddMemberPointerWithMoreQualifiedTypeVariants
2859 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2860 if (!PointeeTy.isVolatileQualified())
2861 AddMemberPointerWithMoreQualifiedTypeVariants
2862 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2863 if (!PointeeTy.isRestrictQualified())
2864 AddMemberPointerWithMoreQualifiedTypeVariants
2865 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2866 }
2867
2868 return true;
2869}
2870
Douglas Gregora11693b2008-11-12 17:17:38 +00002871/// AddTypesConvertedFrom - Add each of the types to which the type @p
2872/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002873/// primarily interested in pointer types and enumeration types. We also
2874/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002875/// AllowUserConversions is true if we should look at the conversion
2876/// functions of a class type, and AllowExplicitConversions if we
2877/// should also include the explicit conversion functions of a class
2878/// type.
Mike Stump11289f42009-09-09 15:08:12 +00002879void
Douglas Gregor5fb53972009-01-14 15:45:31 +00002880BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2881 bool AllowUserConversions,
2882 bool AllowExplicitConversions) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002883 // Only deal with canonical types.
2884 Ty = Context.getCanonicalType(Ty);
2885
2886 // Look through reference types; they aren't part of the type of an
2887 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002888 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00002889 Ty = RefTy->getPointeeType();
2890
2891 // We don't care about qualifiers on the type.
2892 Ty = Ty.getUnqualifiedType();
2893
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002894 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002895 QualType PointeeTy = PointerTy->getPointeeType();
2896
2897 // Insert our type, and its more-qualified variants, into the set
2898 // of types.
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002899 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002900 return;
2901
2902 // Add 'cv void*' to our set of types.
2903 if (!Ty->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002904 QualType QualVoid
Douglas Gregora11693b2008-11-12 17:17:38 +00002905 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002906 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregora11693b2008-11-12 17:17:38 +00002907 }
2908
2909 // If this is a pointer to a class type, add pointers to its bases
2910 // (with the same level of cv-qualification as the original
2911 // derived class, of course).
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002912 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002913 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2914 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2915 Base != ClassDecl->bases_end(); ++Base) {
2916 QualType BaseTy = Context.getCanonicalType(Base->getType());
2917 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2918
2919 // Add the pointer type, recursively, so that we get all of
2920 // the indirect base classes, too.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002921 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00002922 }
2923 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002924 } else if (Ty->isMemberPointerType()) {
2925 // Member pointers are far easier, since the pointee can't be converted.
2926 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2927 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00002928 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00002929 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002930 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002931 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002932 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2933 // No conversion functions in incomplete types.
2934 return;
2935 }
Mike Stump11289f42009-09-09 15:08:12 +00002936
Douglas Gregora11693b2008-11-12 17:17:38 +00002937 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2938 // FIXME: Visit conversion functions in the base classes, too.
Mike Stump11289f42009-09-09 15:08:12 +00002939 OverloadedFunctionDecl *Conversions
Douglas Gregora11693b2008-11-12 17:17:38 +00002940 = ClassDecl->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00002941 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregora11693b2008-11-12 17:17:38 +00002942 = Conversions->function_begin();
2943 Func != Conversions->function_end(); ++Func) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002944 CXXConversionDecl *Conv;
2945 FunctionTemplateDecl *ConvTemplate;
2946 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2947
Mike Stump11289f42009-09-09 15:08:12 +00002948 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00002949 // about which builtin types we can convert to.
2950 if (ConvTemplate)
2951 continue;
2952
Douglas Gregor5fb53972009-01-14 15:45:31 +00002953 if (AllowExplicitConversions || !Conv->isExplicit())
2954 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00002955 }
2956 }
2957 }
2958}
2959
Douglas Gregor84605ae2009-08-24 13:43:27 +00002960/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2961/// the volatile- and non-volatile-qualified assignment operators for the
2962/// given type to the candidate set.
2963static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2964 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00002965 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00002966 unsigned NumArgs,
2967 OverloadCandidateSet &CandidateSet) {
2968 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002969
Douglas Gregor84605ae2009-08-24 13:43:27 +00002970 // T& operator=(T&, T)
2971 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2972 ParamTypes[1] = T;
2973 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2974 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002975
Douglas Gregor84605ae2009-08-24 13:43:27 +00002976 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2977 // volatile T& operator=(volatile T&, T)
2978 ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
2979 ParamTypes[1] = T;
2980 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002981 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00002982 }
2983}
Mike Stump11289f42009-09-09 15:08:12 +00002984
Douglas Gregord08452f2008-11-19 15:42:04 +00002985/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2986/// operator overloads to the candidate set (C++ [over.built]), based
2987/// on the operator @p Op and the arguments given. For example, if the
2988/// operator is a binary '+', this routine might add "int
2989/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00002990void
Mike Stump11289f42009-09-09 15:08:12 +00002991Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregord08452f2008-11-19 15:42:04 +00002992 Expr **Args, unsigned NumArgs,
2993 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002994 // The set of "promoted arithmetic types", which are the arithmetic
2995 // types are that preserved by promotion (C++ [over.built]p2). Note
2996 // that the first few of these types are the promoted integral
2997 // types; these types need to be first.
2998 // FIXME: What about complex?
2999 const unsigned FirstIntegralType = 0;
3000 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003001 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003002 LastPromotedIntegralType = 13;
3003 const unsigned FirstPromotedArithmeticType = 7,
3004 LastPromotedArithmeticType = 16;
3005 const unsigned NumArithmeticTypes = 16;
3006 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003007 Context.BoolTy, Context.CharTy, Context.WCharTy,
3008// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003009 Context.SignedCharTy, Context.ShortTy,
3010 Context.UnsignedCharTy, Context.UnsignedShortTy,
3011 Context.IntTy, Context.LongTy, Context.LongLongTy,
3012 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3013 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3014 };
3015
3016 // Find all of the types that the arguments can convert to, but only
3017 // if the operator we're looking at has built-in operator candidates
3018 // that make use of these types.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003019 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003020 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3021 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003022 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003023 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003024 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003025 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003026 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003027 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3028 true,
3029 (Op == OO_Exclaim ||
3030 Op == OO_AmpAmp ||
3031 Op == OO_PipePipe));
Douglas Gregora11693b2008-11-12 17:17:38 +00003032 }
3033
3034 bool isComparison = false;
3035 switch (Op) {
3036 case OO_None:
3037 case NUM_OVERLOADED_OPERATORS:
3038 assert(false && "Expected an overloaded operator");
3039 break;
3040
Douglas Gregord08452f2008-11-19 15:42:04 +00003041 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003042 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003043 goto UnaryStar;
3044 else
3045 goto BinaryStar;
3046 break;
3047
3048 case OO_Plus: // '+' is either unary or binary
3049 if (NumArgs == 1)
3050 goto UnaryPlus;
3051 else
3052 goto BinaryPlus;
3053 break;
3054
3055 case OO_Minus: // '-' is either unary or binary
3056 if (NumArgs == 1)
3057 goto UnaryMinus;
3058 else
3059 goto BinaryMinus;
3060 break;
3061
3062 case OO_Amp: // '&' is either unary or binary
3063 if (NumArgs == 1)
3064 goto UnaryAmp;
3065 else
3066 goto BinaryAmp;
3067
3068 case OO_PlusPlus:
3069 case OO_MinusMinus:
3070 // C++ [over.built]p3:
3071 //
3072 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3073 // is either volatile or empty, there exist candidate operator
3074 // functions of the form
3075 //
3076 // VQ T& operator++(VQ T&);
3077 // T operator++(VQ T&, int);
3078 //
3079 // C++ [over.built]p4:
3080 //
3081 // For every pair (T, VQ), where T is an arithmetic type other
3082 // than bool, and VQ is either volatile or empty, there exist
3083 // candidate operator functions of the form
3084 //
3085 // VQ T& operator--(VQ T&);
3086 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003087 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003088 Arith < NumArithmeticTypes; ++Arith) {
3089 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003090 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003091 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003092
3093 // Non-volatile version.
3094 if (NumArgs == 1)
3095 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3096 else
3097 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3098
3099 // Volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003100 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregord08452f2008-11-19 15:42:04 +00003101 if (NumArgs == 1)
3102 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3103 else
3104 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3105 }
3106
3107 // C++ [over.built]p5:
3108 //
3109 // For every pair (T, VQ), where T is a cv-qualified or
3110 // cv-unqualified object type, and VQ is either volatile or
3111 // empty, there exist candidate operator functions of the form
3112 //
3113 // T*VQ& operator++(T*VQ&);
3114 // T*VQ& operator--(T*VQ&);
3115 // T* operator++(T*VQ&, int);
3116 // T* operator--(T*VQ&, int);
3117 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3118 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3119 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003120 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003121 continue;
3122
Mike Stump11289f42009-09-09 15:08:12 +00003123 QualType ParamTypes[2] = {
3124 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003125 };
Mike Stump11289f42009-09-09 15:08:12 +00003126
Douglas Gregord08452f2008-11-19 15:42:04 +00003127 // Without volatile
3128 if (NumArgs == 1)
3129 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3130 else
3131 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3132
3133 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3134 // With volatile
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003135 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregord08452f2008-11-19 15:42:04 +00003136 if (NumArgs == 1)
3137 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3138 else
3139 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3140 }
3141 }
3142 break;
3143
3144 UnaryStar:
3145 // C++ [over.built]p6:
3146 // For every cv-qualified or cv-unqualified object type T, there
3147 // exist candidate operator functions of the form
3148 //
3149 // T& operator*(T*);
3150 //
3151 // C++ [over.built]p7:
3152 // For every function type T, there exist candidate operator
3153 // functions of the form
3154 // T& operator*(T*);
3155 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3156 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3157 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003158 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003159 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003160 &ParamTy, Args, 1, CandidateSet);
3161 }
3162 break;
3163
3164 UnaryPlus:
3165 // C++ [over.built]p8:
3166 // For every type T, there exist candidate operator functions of
3167 // the form
3168 //
3169 // T* operator+(T*);
3170 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3171 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3172 QualType ParamTy = *Ptr;
3173 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3174 }
Mike Stump11289f42009-09-09 15:08:12 +00003175
Douglas Gregord08452f2008-11-19 15:42:04 +00003176 // Fall through
3177
3178 UnaryMinus:
3179 // C++ [over.built]p9:
3180 // For every promoted arithmetic type T, there exist candidate
3181 // operator functions of the form
3182 //
3183 // T operator+(T);
3184 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003185 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003186 Arith < LastPromotedArithmeticType; ++Arith) {
3187 QualType ArithTy = ArithmeticTypes[Arith];
3188 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3189 }
3190 break;
3191
3192 case OO_Tilde:
3193 // C++ [over.built]p10:
3194 // For every promoted integral type T, there exist candidate
3195 // operator functions of the form
3196 //
3197 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003198 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003199 Int < LastPromotedIntegralType; ++Int) {
3200 QualType IntTy = ArithmeticTypes[Int];
3201 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3202 }
3203 break;
3204
Douglas Gregora11693b2008-11-12 17:17:38 +00003205 case OO_New:
3206 case OO_Delete:
3207 case OO_Array_New:
3208 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003209 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003210 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003211 break;
3212
3213 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003214 UnaryAmp:
3215 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003216 // C++ [over.match.oper]p3:
3217 // -- For the operator ',', the unary operator '&', or the
3218 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003219 break;
3220
Douglas Gregor84605ae2009-08-24 13:43:27 +00003221 case OO_EqualEqual:
3222 case OO_ExclaimEqual:
3223 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003224 // For every pointer to member type T, there exist candidate operator
3225 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003226 //
3227 // bool operator==(T,T);
3228 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003229 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003230 MemPtr = CandidateTypes.member_pointer_begin(),
3231 MemPtrEnd = CandidateTypes.member_pointer_end();
3232 MemPtr != MemPtrEnd;
3233 ++MemPtr) {
3234 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3235 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3236 }
Mike Stump11289f42009-09-09 15:08:12 +00003237
Douglas Gregor84605ae2009-08-24 13:43:27 +00003238 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003239
Douglas Gregora11693b2008-11-12 17:17:38 +00003240 case OO_Less:
3241 case OO_Greater:
3242 case OO_LessEqual:
3243 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003244 // C++ [over.built]p15:
3245 //
3246 // For every pointer or enumeration type T, there exist
3247 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003248 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003249 // bool operator<(T, T);
3250 // bool operator>(T, T);
3251 // bool operator<=(T, T);
3252 // bool operator>=(T, T);
3253 // bool operator==(T, T);
3254 // bool operator!=(T, T);
3255 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3256 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3257 QualType ParamTypes[2] = { *Ptr, *Ptr };
3258 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3259 }
Mike Stump11289f42009-09-09 15:08:12 +00003260 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003261 = CandidateTypes.enumeration_begin();
3262 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3263 QualType ParamTypes[2] = { *Enum, *Enum };
3264 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3265 }
3266
3267 // Fall through.
3268 isComparison = true;
3269
Douglas Gregord08452f2008-11-19 15:42:04 +00003270 BinaryPlus:
3271 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003272 if (!isComparison) {
3273 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3274
3275 // C++ [over.built]p13:
3276 //
3277 // For every cv-qualified or cv-unqualified object type T
3278 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003279 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003280 // T* operator+(T*, ptrdiff_t);
3281 // T& operator[](T*, ptrdiff_t); [BELOW]
3282 // T* operator-(T*, ptrdiff_t);
3283 // T* operator+(ptrdiff_t, T*);
3284 // T& operator[](ptrdiff_t, T*); [BELOW]
3285 //
3286 // C++ [over.built]p14:
3287 //
3288 // For every T, where T is a pointer to object type, there
3289 // exist candidate operator functions of the form
3290 //
3291 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003292 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003293 = CandidateTypes.pointer_begin();
3294 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3295 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3296
3297 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3298 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3299
3300 if (Op == OO_Plus) {
3301 // T* operator+(ptrdiff_t, T*);
3302 ParamTypes[0] = ParamTypes[1];
3303 ParamTypes[1] = *Ptr;
3304 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3305 } else {
3306 // ptrdiff_t operator-(T, T);
3307 ParamTypes[1] = *Ptr;
3308 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3309 Args, 2, CandidateSet);
3310 }
3311 }
3312 }
3313 // Fall through
3314
Douglas Gregora11693b2008-11-12 17:17:38 +00003315 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003316 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003317 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003318 // C++ [over.built]p12:
3319 //
3320 // For every pair of promoted arithmetic types L and R, there
3321 // exist candidate operator functions of the form
3322 //
3323 // LR operator*(L, R);
3324 // LR operator/(L, R);
3325 // LR operator+(L, R);
3326 // LR operator-(L, R);
3327 // bool operator<(L, R);
3328 // bool operator>(L, R);
3329 // bool operator<=(L, R);
3330 // bool operator>=(L, R);
3331 // bool operator==(L, R);
3332 // bool operator!=(L, R);
3333 //
3334 // where LR is the result of the usual arithmetic conversions
3335 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003336 //
3337 // C++ [over.built]p24:
3338 //
3339 // For every pair of promoted arithmetic types L and R, there exist
3340 // candidate operator functions of the form
3341 //
3342 // LR operator?(bool, L, R);
3343 //
3344 // where LR is the result of the usual arithmetic conversions
3345 // between types L and R.
3346 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003347 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003348 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003349 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003350 Right < LastPromotedArithmeticType; ++Right) {
3351 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003352 QualType Result
3353 = isComparison
3354 ? Context.BoolTy
3355 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003356 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3357 }
3358 }
3359 break;
3360
3361 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003362 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003363 case OO_Caret:
3364 case OO_Pipe:
3365 case OO_LessLess:
3366 case OO_GreaterGreater:
3367 // C++ [over.built]p17:
3368 //
3369 // For every pair of promoted integral types L and R, there
3370 // exist candidate operator functions of the form
3371 //
3372 // LR operator%(L, R);
3373 // LR operator&(L, R);
3374 // LR operator^(L, R);
3375 // LR operator|(L, R);
3376 // L operator<<(L, R);
3377 // L operator>>(L, R);
3378 //
3379 // where LR is the result of the usual arithmetic conversions
3380 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003381 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003382 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003383 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003384 Right < LastPromotedIntegralType; ++Right) {
3385 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3386 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3387 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003388 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003389 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3390 }
3391 }
3392 break;
3393
3394 case OO_Equal:
3395 // C++ [over.built]p20:
3396 //
3397 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003398 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003399 // empty, there exist candidate operator functions of the form
3400 //
3401 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003402 for (BuiltinCandidateTypeSet::iterator
3403 Enum = CandidateTypes.enumeration_begin(),
3404 EnumEnd = CandidateTypes.enumeration_end();
3405 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003406 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003407 CandidateSet);
3408 for (BuiltinCandidateTypeSet::iterator
3409 MemPtr = CandidateTypes.member_pointer_begin(),
3410 MemPtrEnd = CandidateTypes.member_pointer_end();
3411 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003412 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003413 CandidateSet);
3414 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003415
3416 case OO_PlusEqual:
3417 case OO_MinusEqual:
3418 // C++ [over.built]p19:
3419 //
3420 // For every pair (T, VQ), where T is any type and VQ is either
3421 // volatile or empty, there exist candidate operator functions
3422 // of the form
3423 //
3424 // T*VQ& operator=(T*VQ&, T*);
3425 //
3426 // C++ [over.built]p21:
3427 //
3428 // For every pair (T, VQ), where T is a cv-qualified or
3429 // cv-unqualified object type and VQ is either volatile or
3430 // empty, there exist candidate operator functions of the form
3431 //
3432 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3433 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3434 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3435 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3436 QualType ParamTypes[2];
3437 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3438
3439 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003440 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003441 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3442 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003443
Douglas Gregord08452f2008-11-19 15:42:04 +00003444 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3445 // volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003446 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorc5e61072009-01-13 00:52:54 +00003447 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3448 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003449 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003450 }
3451 // Fall through.
3452
3453 case OO_StarEqual:
3454 case OO_SlashEqual:
3455 // C++ [over.built]p18:
3456 //
3457 // For every triple (L, VQ, R), where L is an arithmetic type,
3458 // VQ is either volatile or empty, and R is a promoted
3459 // arithmetic type, there exist candidate operator functions of
3460 // the form
3461 //
3462 // VQ L& operator=(VQ L&, R);
3463 // VQ L& operator*=(VQ L&, R);
3464 // VQ L& operator/=(VQ L&, R);
3465 // VQ L& operator+=(VQ L&, R);
3466 // VQ L& operator-=(VQ L&, R);
3467 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003468 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003469 Right < LastPromotedArithmeticType; ++Right) {
3470 QualType ParamTypes[2];
3471 ParamTypes[1] = ArithmeticTypes[Right];
3472
3473 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003474 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003475 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3476 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003477
3478 // Add this built-in operator as a candidate (VQ is 'volatile').
3479 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003480 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003481 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3482 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003483 }
3484 }
3485 break;
3486
3487 case OO_PercentEqual:
3488 case OO_LessLessEqual:
3489 case OO_GreaterGreaterEqual:
3490 case OO_AmpEqual:
3491 case OO_CaretEqual:
3492 case OO_PipeEqual:
3493 // C++ [over.built]p22:
3494 //
3495 // For every triple (L, VQ, R), where L is an integral type, VQ
3496 // is either volatile or empty, and R is a promoted integral
3497 // type, there exist candidate operator functions of the form
3498 //
3499 // VQ L& operator%=(VQ L&, R);
3500 // VQ L& operator<<=(VQ L&, R);
3501 // VQ L& operator>>=(VQ L&, R);
3502 // VQ L& operator&=(VQ L&, R);
3503 // VQ L& operator^=(VQ L&, R);
3504 // VQ L& operator|=(VQ L&, R);
3505 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003506 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003507 Right < LastPromotedIntegralType; ++Right) {
3508 QualType ParamTypes[2];
3509 ParamTypes[1] = ArithmeticTypes[Right];
3510
3511 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003512 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003513 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3514
3515 // Add this built-in operator as a candidate (VQ is 'volatile').
3516 ParamTypes[0] = ArithmeticTypes[Left];
3517 ParamTypes[0].addVolatile();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003518 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003519 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3520 }
3521 }
3522 break;
3523
Douglas Gregord08452f2008-11-19 15:42:04 +00003524 case OO_Exclaim: {
3525 // C++ [over.operator]p23:
3526 //
3527 // There also exist candidate operator functions of the form
3528 //
Mike Stump11289f42009-09-09 15:08:12 +00003529 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003530 // bool operator&&(bool, bool); [BELOW]
3531 // bool operator||(bool, bool); [BELOW]
3532 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003533 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3534 /*IsAssignmentOperator=*/false,
3535 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003536 break;
3537 }
3538
Douglas Gregora11693b2008-11-12 17:17:38 +00003539 case OO_AmpAmp:
3540 case OO_PipePipe: {
3541 // C++ [over.operator]p23:
3542 //
3543 // There also exist candidate operator functions of the form
3544 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003545 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003546 // bool operator&&(bool, bool);
3547 // bool operator||(bool, bool);
3548 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003549 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3550 /*IsAssignmentOperator=*/false,
3551 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003552 break;
3553 }
3554
3555 case OO_Subscript:
3556 // C++ [over.built]p13:
3557 //
3558 // For every cv-qualified or cv-unqualified object type T there
3559 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003560 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003561 // T* operator+(T*, ptrdiff_t); [ABOVE]
3562 // T& operator[](T*, ptrdiff_t);
3563 // T* operator-(T*, ptrdiff_t); [ABOVE]
3564 // T* operator+(ptrdiff_t, T*); [ABOVE]
3565 // T& operator[](ptrdiff_t, T*);
3566 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3567 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3568 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003569 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003570 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003571
3572 // T& operator[](T*, ptrdiff_t)
3573 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3574
3575 // T& operator[](ptrdiff_t, T*);
3576 ParamTypes[0] = ParamTypes[1];
3577 ParamTypes[1] = *Ptr;
3578 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3579 }
3580 break;
3581
3582 case OO_ArrowStar:
3583 // FIXME: No support for pointer-to-members yet.
3584 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003585
3586 case OO_Conditional:
3587 // Note that we don't consider the first argument, since it has been
3588 // contextually converted to bool long ago. The candidates below are
3589 // therefore added as binary.
3590 //
3591 // C++ [over.built]p24:
3592 // For every type T, where T is a pointer or pointer-to-member type,
3593 // there exist candidate operator functions of the form
3594 //
3595 // T operator?(bool, T, T);
3596 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003597 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3598 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3599 QualType ParamTypes[2] = { *Ptr, *Ptr };
3600 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3601 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003602 for (BuiltinCandidateTypeSet::iterator Ptr =
3603 CandidateTypes.member_pointer_begin(),
3604 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3605 QualType ParamTypes[2] = { *Ptr, *Ptr };
3606 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3607 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003608 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003609 }
3610}
3611
Douglas Gregore254f902009-02-04 00:32:51 +00003612/// \brief Add function candidates found via argument-dependent lookup
3613/// to the set of overloading candidates.
3614///
3615/// This routine performs argument-dependent name lookup based on the
3616/// given function name (which may also be an operator name) and adds
3617/// all of the overload candidates found by ADL to the overload
3618/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003619void
Douglas Gregore254f902009-02-04 00:32:51 +00003620Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3621 Expr **Args, unsigned NumArgs,
3622 OverloadCandidateSet& CandidateSet) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003623 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003624
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003625 // Record all of the function candidates that we've already
3626 // added to the overload set, so that we don't add those same
3627 // candidates a second time.
3628 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3629 CandEnd = CandidateSet.end();
3630 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003631 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003632 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003633 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3634 Functions.insert(FunTmpl);
3635 }
Douglas Gregore254f902009-02-04 00:32:51 +00003636
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003637 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003638
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003639 // Erase all of the candidates we already knew about.
3640 // FIXME: This is suboptimal. Is there a better way?
3641 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3642 CandEnd = CandidateSet.end();
3643 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003644 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003645 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003646 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3647 Functions.erase(FunTmpl);
3648 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003649
3650 // For each of the ADL candidates we found, add it to the overload
3651 // set.
3652 for (FunctionSet::iterator Func = Functions.begin(),
3653 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00003654 Func != FuncEnd; ++Func) {
3655 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3656 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3657 else
Mike Stump11289f42009-09-09 15:08:12 +00003658 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregor89026b52009-06-30 23:57:56 +00003659 /*FIXME: explicit args */false, 0, 0,
3660 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00003661 }
Douglas Gregore254f902009-02-04 00:32:51 +00003662}
3663
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003664/// isBetterOverloadCandidate - Determines whether the first overload
3665/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00003666bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003667Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00003668 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003669 // Define viable functions to be better candidates than non-viable
3670 // functions.
3671 if (!Cand2.Viable)
3672 return Cand1.Viable;
3673 else if (!Cand1.Viable)
3674 return false;
3675
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003676 // C++ [over.match.best]p1:
3677 //
3678 // -- if F is a static member function, ICS1(F) is defined such
3679 // that ICS1(F) is neither better nor worse than ICS1(G) for
3680 // any function G, and, symmetrically, ICS1(G) is neither
3681 // better nor worse than ICS1(F).
3682 unsigned StartArg = 0;
3683 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3684 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003685
Douglas Gregord3cb3562009-07-07 23:38:56 +00003686 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00003687 // A viable function F1 is defined to be a better function than another
3688 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00003689 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003690 unsigned NumArgs = Cand1.Conversions.size();
3691 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3692 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003693 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003694 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3695 Cand2.Conversions[ArgIdx])) {
3696 case ImplicitConversionSequence::Better:
3697 // Cand1 has a better conversion sequence.
3698 HasBetterConversion = true;
3699 break;
3700
3701 case ImplicitConversionSequence::Worse:
3702 // Cand1 can't be better than Cand2.
3703 return false;
3704
3705 case ImplicitConversionSequence::Indistinguishable:
3706 // Do nothing.
3707 break;
3708 }
3709 }
3710
Mike Stump11289f42009-09-09 15:08:12 +00003711 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00003712 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003713 if (HasBetterConversion)
3714 return true;
3715
Mike Stump11289f42009-09-09 15:08:12 +00003716 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00003717 // specialization, or, if not that,
3718 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3719 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3720 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003721
3722 // -- F1 and F2 are function template specializations, and the function
3723 // template for F1 is more specialized than the template for F2
3724 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00003725 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00003726 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3727 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00003728 if (FunctionTemplateDecl *BetterTemplate
3729 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3730 Cand2.Function->getPrimaryTemplate(),
3731 true))
3732 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003733
Douglas Gregora1f013e2008-11-07 22:36:19 +00003734 // -- the context is an initialization by user-defined conversion
3735 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3736 // from the return type of F1 to the destination type (i.e.,
3737 // the type of the entity being initialized) is a better
3738 // conversion sequence than the standard conversion sequence
3739 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00003740 if (Cand1.Function && Cand2.Function &&
3741 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003742 isa<CXXConversionDecl>(Cand2.Function)) {
3743 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3744 Cand2.FinalConversion)) {
3745 case ImplicitConversionSequence::Better:
3746 // Cand1 has a better conversion sequence.
3747 return true;
3748
3749 case ImplicitConversionSequence::Worse:
3750 // Cand1 can't be better than Cand2.
3751 return false;
3752
3753 case ImplicitConversionSequence::Indistinguishable:
3754 // Do nothing
3755 break;
3756 }
3757 }
3758
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003759 return false;
3760}
3761
Mike Stump11289f42009-09-09 15:08:12 +00003762/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003763/// within an overload candidate set.
3764///
3765/// \param CandidateSet the set of candidate functions.
3766///
3767/// \param Loc the location of the function name (or operator symbol) for
3768/// which overload resolution occurs.
3769///
Mike Stump11289f42009-09-09 15:08:12 +00003770/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003771/// function, Best points to the candidate function found.
3772///
3773/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00003774Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003775Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003776 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003777 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003778 // Find the best viable function.
3779 Best = CandidateSet.end();
3780 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3781 Cand != CandidateSet.end(); ++Cand) {
3782 if (Cand->Viable) {
3783 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3784 Best = Cand;
3785 }
3786 }
3787
3788 // If we didn't find any viable functions, abort.
3789 if (Best == CandidateSet.end())
3790 return OR_No_Viable_Function;
3791
3792 // Make sure that this function is better than every other viable
3793 // function. If not, we have an ambiguity.
3794 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3795 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00003796 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003797 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00003798 !isBetterOverloadCandidate(*Best, *Cand)) {
3799 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003800 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003801 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003802 }
Mike Stump11289f42009-09-09 15:08:12 +00003803
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003804 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003805 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00003806 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003807 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003808 return OR_Deleted;
3809
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003810 // C++ [basic.def.odr]p2:
3811 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00003812 // when referred to from a potentially-evaluated expression. [Note: this
3813 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003814 // (clause 13), user-defined conversions (12.3.2), allocation function for
3815 // placement new (5.3.4), as well as non-default initialization (8.5).
3816 if (Best->Function)
3817 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003818 return OR_Success;
3819}
3820
3821/// PrintOverloadCandidates - When overload resolution fails, prints
3822/// diagnostic messages containing the candidates in the candidate
3823/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00003824void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003825Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003826 bool OnlyViable) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003827 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3828 LastCand = CandidateSet.end();
3829 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003830 if (Cand->Viable || !OnlyViable) {
3831 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003832 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003833 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003834 // Deleted or "unavailable" function.
3835 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3836 << Cand->Function->isDeleted();
3837 } else {
3838 // Normal function
3839 // FIXME: Give a better reason!
3840 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3841 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00003842 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003843 // Desugar the type of the surrogate down to a function type,
3844 // retaining as many typedefs as possible while still showing
3845 // the function type (and, therefore, its parameter types).
3846 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003847 bool isLValueReference = false;
3848 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003849 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003850 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003851 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003852 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003853 isLValueReference = true;
3854 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003855 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003856 FnType = FnTypeRef->getPointeeType();
3857 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003858 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003859 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003860 FnType = FnTypePtr->getPointeeType();
3861 isPointer = true;
3862 }
3863 // Desugar down to a function type.
3864 FnType = QualType(FnType->getAsFunctionType(), 0);
3865 // Reconstruct the pointer/reference as appropriate.
3866 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003867 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3868 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003869
Douglas Gregorab7897a2008-11-19 22:57:39 +00003870 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003871 << FnType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003872 } else {
3873 // FIXME: We need to get the identifier in here
Mike Stump87c57ac2009-05-16 07:39:55 +00003874 // FIXME: Do we want the error message to point at the operator?
3875 // (built-ins won't have a location)
Mike Stump11289f42009-09-09 15:08:12 +00003876 QualType FnType
Douglas Gregora11693b2008-11-12 17:17:38 +00003877 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3878 Cand->BuiltinTypes.ParamTypes,
3879 Cand->Conversions.size(),
3880 false, 0);
3881
Chris Lattner1e5665e2008-11-24 06:25:27 +00003882 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003883 }
3884 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003885 }
3886}
3887
Douglas Gregorcd695e52008-11-10 20:40:00 +00003888/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3889/// an overloaded function (C++ [over.over]), where @p From is an
3890/// expression with overloaded function type and @p ToType is the type
3891/// we're trying to resolve to. For example:
3892///
3893/// @code
3894/// int f(double);
3895/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00003896///
Douglas Gregorcd695e52008-11-10 20:40:00 +00003897/// int (*pfd)(double) = f; // selects f(double)
3898/// @endcode
3899///
3900/// This routine returns the resulting FunctionDecl if it could be
3901/// resolved, and NULL otherwise. When @p Complain is true, this
3902/// routine will emit diagnostics if there is an error.
3903FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003904Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003905 bool Complain) {
3906 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003907 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003908 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00003909 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003910 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00003911 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003912 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003913 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003914 FunctionType = MemTypePtr->getPointeeType();
3915 IsMember = true;
3916 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003917
3918 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00003919 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00003920 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00003921 return 0;
3922
3923 // Find the actual overloaded function declaration.
3924 OverloadedFunctionDecl *Ovl = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003925
Douglas Gregorcd695e52008-11-10 20:40:00 +00003926 // C++ [over.over]p1:
3927 // [...] [Note: any redundant set of parentheses surrounding the
3928 // overloaded function name is ignored (5.1). ]
3929 Expr *OvlExpr = From->IgnoreParens();
3930
3931 // C++ [over.over]p1:
3932 // [...] The overloaded function name can be preceded by the &
3933 // operator.
3934 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3935 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3936 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3937 }
3938
3939 // Try to dig out the overloaded function.
Douglas Gregor9b146582009-07-08 20:55:45 +00003940 FunctionTemplateDecl *FunctionTemplate = 0;
3941 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00003942 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor9b146582009-07-08 20:55:45 +00003943 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3944 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003945
Mike Stump11289f42009-09-09 15:08:12 +00003946 // If there's no overloaded function declaration or function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00003947 // we're done.
3948 if (!Ovl && !FunctionTemplate)
Douglas Gregorcd695e52008-11-10 20:40:00 +00003949 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003950
Douglas Gregor9b146582009-07-08 20:55:45 +00003951 OverloadIterator Fun;
3952 if (Ovl)
3953 Fun = Ovl;
3954 else
3955 Fun = FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00003956
Douglas Gregorcd695e52008-11-10 20:40:00 +00003957 // Look through all of the overloaded functions, searching for one
3958 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003959 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Mike Stump11289f42009-09-09 15:08:12 +00003960
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003961 bool FoundNonTemplateFunction = false;
Douglas Gregor9b146582009-07-08 20:55:45 +00003962 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00003963 // C++ [over.over]p3:
3964 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00003965 // targets of type "pointer-to-function" or "reference-to-function."
3966 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003967 // type "pointer-to-member-function."
3968 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00003969
Mike Stump11289f42009-09-09 15:08:12 +00003970 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor9b146582009-07-08 20:55:45 +00003971 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump11289f42009-09-09 15:08:12 +00003972 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003973 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003974 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003975 // static when converting to member pointer.
3976 if (Method->isStatic() == IsMember)
3977 continue;
3978 } else if (IsMember)
3979 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003980
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003981 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003982 // If the name is a function template, template argument deduction is
3983 // done (14.8.2.2), and if the argument deduction succeeds, the
3984 // resulting template argument list is used to generate a single
3985 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003986 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00003987 FunctionDecl *Specialization = 0;
3988 TemplateDeductionInfo Info(Context);
3989 if (TemplateDeductionResult Result
3990 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3991 /*FIXME:*/0, /*FIXME:*/0,
3992 FunctionType, Specialization, Info)) {
3993 // FIXME: make a note of the failed deduction for diagnostics.
3994 (void)Result;
3995 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003996 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00003997 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003998 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003999 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004000 }
4001 }
Mike Stump11289f42009-09-09 15:08:12 +00004002
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004003 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4004 // Skip non-static functions when converting to pointer, and static
4005 // when converting to member pointer.
4006 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004007 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004008 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004009 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004010
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004011 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004012 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004013 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004014 FoundNonTemplateFunction = true;
4015 }
Mike Stump11289f42009-09-09 15:08:12 +00004016 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004017 }
4018
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004019 // If there were 0 or 1 matches, we're done.
4020 if (Matches.empty())
4021 return 0;
4022 else if (Matches.size() == 1)
4023 return *Matches.begin();
4024
4025 // C++ [over.over]p4:
4026 // If more than one function is selected, [...]
4027 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor05155d82009-08-21 23:19:43 +00004028 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004029 if (FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004030 // [...] any function template specializations in the set are
4031 // eliminated if the set also contains a non-template function, [...]
4032 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004033 if ((*M)->getPrimaryTemplate() == 0)
4034 RemainingMatches.push_back(*M);
4035 } else {
Douglas Gregor05155d82009-08-21 23:19:43 +00004036 // [...] and any given function template specialization F1 is
4037 // eliminated if the set contains a second function template
4038 // specialization whose function template is more specialized
4039 // than the function template of F1 according to the partial
4040 // ordering rules of 14.5.5.2.
4041
4042 // The algorithm specified above is quadratic. We instead use a
4043 // two-pass algorithm (similar to the one used to identify the
4044 // best viable function in an overload set) that identifies the
4045 // best function template (if it exists).
4046 MatchIter Best = Matches.begin();
4047 MatchIter M = Best, MEnd = Matches.end();
4048 // Find the most specialized function.
4049 for (++M; M != MEnd; ++M)
4050 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4051 (*Best)->getPrimaryTemplate(),
Mike Stump11289f42009-09-09 15:08:12 +00004052 false)
Douglas Gregor05155d82009-08-21 23:19:43 +00004053 == (*M)->getPrimaryTemplate())
4054 Best = M;
4055
4056 // Determine whether this function template is more specialized
4057 // that all of the others.
4058 bool Ambiguous = false;
4059 for (M = Matches.begin(); M != MEnd; ++M) {
4060 if (M != Best &&
4061 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4062 (*Best)->getPrimaryTemplate(),
4063 false)
4064 != (*Best)->getPrimaryTemplate()) {
4065 Ambiguous = true;
4066 break;
4067 }
4068 }
4069
4070 // If one function template was more specialized than all of the
4071 // others, return it.
4072 if (!Ambiguous)
4073 return *Best;
4074
4075 // We could not find a most-specialized function template, which
4076 // is equivalent to having a set of function templates with more
4077 // than one such template. So, we place all of the function
4078 // templates into the set of remaining matches and produce a
4079 // diagnostic below. FIXME: we could perform the quadratic
4080 // algorithm here, pruning the result set to limit the number of
4081 // candidates output later.
4082 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004083 }
Mike Stump11289f42009-09-09 15:08:12 +00004084
4085 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004086 // selected function.
4087 if (RemainingMatches.size() == 1)
4088 return RemainingMatches.front();
Mike Stump11289f42009-09-09 15:08:12 +00004089
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004090 // FIXME: We should probably return the same thing that BestViableFunction
4091 // returns (even if we issue the diagnostics here).
4092 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4093 << RemainingMatches[0]->getDeclName();
4094 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4095 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004096 return 0;
4097}
4098
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004099/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004100/// (which eventually refers to the declaration Func) and the call
4101/// arguments Args/NumArgs, attempt to resolve the function call down
4102/// to a specific function. If overload resolution succeeds, returns
4103/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004104/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004105/// arguments and Fn, and returns NULL.
Douglas Gregore254f902009-02-04 00:32:51 +00004106FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004107 DeclarationName UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00004108 bool HasExplicitTemplateArgs,
4109 const TemplateArgument *ExplicitTemplateArgs,
4110 unsigned NumExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004111 SourceLocation LParenLoc,
4112 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004113 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004114 SourceLocation RParenLoc,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004115 bool &ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004116 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004117
4118 // Add the functions denoted by Callee to the set of candidate
4119 // functions. While we're doing so, track whether argument-dependent
4120 // lookup still applies, per:
4121 //
4122 // C++0x [basic.lookup.argdep]p3:
4123 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4124 // and let Y be the lookup set produced by argument dependent
4125 // lookup (defined as follows). If X contains
4126 //
Mike Stump11289f42009-09-09 15:08:12 +00004127 // -- a declaration of a class member, or
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004128 //
4129 // -- a block-scope function declaration that is not a
Mike Stump11289f42009-09-09 15:08:12 +00004130 // using-declaration, or
4131 //
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004132 // -- a declaration that is neither a function or a function
4133 // template
4134 //
Mike Stump11289f42009-09-09 15:08:12 +00004135 // then Y is empty.
4136 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004137 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4138 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4139 FuncEnd = Ovl->function_end();
4140 Func != FuncEnd; ++Func) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004141 DeclContext *Ctx = 0;
4142 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregor89026b52009-06-30 23:57:56 +00004143 if (HasExplicitTemplateArgs)
4144 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004145
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004146 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4147 Ctx = FunDecl->getDeclContext();
4148 } else {
4149 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregor89026b52009-06-30 23:57:56 +00004150 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4151 ExplicitTemplateArgs,
4152 NumExplicitTemplateArgs,
4153 Args, NumArgs, CandidateSet);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004154 Ctx = FunTmpl->getDeclContext();
4155 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004156
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004157
4158 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004159 ArgumentDependentLookup = false;
4160 }
4161 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregor89026b52009-06-30 23:57:56 +00004162 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004163 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4164
4165 if (Func->getDeclContext()->isRecord() ||
4166 Func->getDeclContext()->isFunctionOrMethod())
4167 ArgumentDependentLookup = false;
Mike Stump11289f42009-09-09 15:08:12 +00004168 } else if (FunctionTemplateDecl *FuncTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004169 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregor89026b52009-06-30 23:57:56 +00004170 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4171 ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004172 NumExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004173 Args, NumArgs, CandidateSet);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004174
4175 if (FuncTemplate->getDeclContext()->isRecord())
4176 ArgumentDependentLookup = false;
4177 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004178
4179 if (Callee)
4180 UnqualifiedName = Callee->getDeclName();
4181
Douglas Gregor89026b52009-06-30 23:57:56 +00004182 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregore254f902009-02-04 00:32:51 +00004183 if (ArgumentDependentLookup)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004184 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregore254f902009-02-04 00:32:51 +00004185 CandidateSet);
4186
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004187 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004188 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004189 case OR_Success:
4190 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004191
4192 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004193 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004194 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004195 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004196 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4197 break;
4198
4199 case OR_Ambiguous:
4200 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004201 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004202 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4203 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004204
4205 case OR_Deleted:
4206 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4207 << Best->Function->isDeleted()
4208 << UnqualifiedName
4209 << Fn->getSourceRange();
4210 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4211 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004212 }
4213
4214 // Overload resolution failed. Destroy all of the subexpressions and
4215 // return NULL.
4216 Fn->Destroy(Context);
4217 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4218 Args[Arg]->Destroy(Context);
4219 return 0;
4220}
4221
Douglas Gregor084d8552009-03-13 23:49:33 +00004222/// \brief Create a unary operation that may resolve to an overloaded
4223/// operator.
4224///
4225/// \param OpLoc The location of the operator itself (e.g., '*').
4226///
4227/// \param OpcIn The UnaryOperator::Opcode that describes this
4228/// operator.
4229///
4230/// \param Functions The set of non-member functions that will be
4231/// considered by overload resolution. The caller needs to build this
4232/// set based on the context using, e.g.,
4233/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4234/// set should not contain any member functions; those will be added
4235/// by CreateOverloadedUnaryOp().
4236///
4237/// \param input The input argument.
4238Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4239 unsigned OpcIn,
4240 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004241 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004242 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4243 Expr *Input = (Expr *)input.get();
4244
4245 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4246 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4247 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4248
4249 Expr *Args[2] = { Input, 0 };
4250 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004251
Douglas Gregor084d8552009-03-13 23:49:33 +00004252 // For post-increment and post-decrement, add the implicit '0' as
4253 // the second argument, so that we know this is a post-increment or
4254 // post-decrement.
4255 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4256 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004257 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004258 SourceLocation());
4259 NumArgs = 2;
4260 }
4261
4262 if (Input->isTypeDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00004263 OverloadedFunctionDecl *Overloads
Douglas Gregor084d8552009-03-13 23:49:33 +00004264 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004265 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004266 FuncEnd = Functions.end();
4267 Func != FuncEnd; ++Func)
4268 Overloads->addOverload(*Func);
4269
4270 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4271 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004272
Douglas Gregor084d8552009-03-13 23:49:33 +00004273 input.release();
4274 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4275 &Args[0], NumArgs,
4276 Context.DependentTy,
4277 OpLoc));
4278 }
4279
4280 // Build an empty overload set.
4281 OverloadCandidateSet CandidateSet;
4282
4283 // Add the candidates from the given function set.
4284 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4285
4286 // Add operator candidates that are member functions.
4287 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4288
4289 // Add builtin operator candidates.
4290 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4291
4292 // Perform overload resolution.
4293 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004294 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004295 case OR_Success: {
4296 // We found a built-in operator or an overloaded operator.
4297 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004298
Douglas Gregor084d8552009-03-13 23:49:33 +00004299 if (FnDecl) {
4300 // We matched an overloaded operator. Build a call to that
4301 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004302
Douglas Gregor084d8552009-03-13 23:49:33 +00004303 // Convert the arguments.
4304 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4305 if (PerformObjectArgumentInitialization(Input, Method))
4306 return ExprError();
4307 } else {
4308 // Convert the arguments.
4309 if (PerformCopyInitialization(Input,
4310 FnDecl->getParamDecl(0)->getType(),
4311 "passing"))
4312 return ExprError();
4313 }
4314
4315 // Determine the result type
4316 QualType ResultTy
4317 = FnDecl->getType()->getAsFunctionType()->getResultType();
4318 ResultTy = ResultTy.getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004319
Douglas Gregor084d8552009-03-13 23:49:33 +00004320 // Build the actual expression node.
4321 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4322 SourceLocation());
4323 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004324
Douglas Gregor084d8552009-03-13 23:49:33 +00004325 input.release();
Mike Stump11289f42009-09-09 15:08:12 +00004326
4327 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004328 &Input, 1, ResultTy, OpLoc);
4329 return MaybeBindToTemporary(CE);
Douglas Gregor084d8552009-03-13 23:49:33 +00004330 } else {
4331 // We matched a built-in operator. Convert the arguments, then
4332 // break out so that we will build the appropriate built-in
4333 // operator node.
4334 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4335 Best->Conversions[0], "passing"))
4336 return ExprError();
4337
4338 break;
4339 }
4340 }
4341
4342 case OR_No_Viable_Function:
4343 // No viable function; fall through to handling this as a
4344 // built-in operator, which will produce an error message for us.
4345 break;
4346
4347 case OR_Ambiguous:
4348 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4349 << UnaryOperator::getOpcodeStr(Opc)
4350 << Input->getSourceRange();
4351 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4352 return ExprError();
4353
4354 case OR_Deleted:
4355 Diag(OpLoc, diag::err_ovl_deleted_oper)
4356 << Best->Function->isDeleted()
4357 << UnaryOperator::getOpcodeStr(Opc)
4358 << Input->getSourceRange();
4359 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4360 return ExprError();
4361 }
4362
4363 // Either we found no viable overloaded operator or we matched a
4364 // built-in operator. In either case, fall through to trying to
4365 // build a built-in operation.
4366 input.release();
4367 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4368}
4369
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004370/// \brief Create a binary operation that may resolve to an overloaded
4371/// operator.
4372///
4373/// \param OpLoc The location of the operator itself (e.g., '+').
4374///
4375/// \param OpcIn The BinaryOperator::Opcode that describes this
4376/// operator.
4377///
4378/// \param Functions The set of non-member functions that will be
4379/// considered by overload resolution. The caller needs to build this
4380/// set based on the context using, e.g.,
4381/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4382/// set should not contain any member functions; those will be added
4383/// by CreateOverloadedBinOp().
4384///
4385/// \param LHS Left-hand argument.
4386/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004387Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004388Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004389 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004390 FunctionSet &Functions,
4391 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004392 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004393 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004394
4395 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4396 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4397 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4398
4399 // If either side is type-dependent, create an appropriate dependent
4400 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004401 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004402 // .* cannot be overloaded.
4403 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004404 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004405 Context.DependentTy, OpLoc));
4406
Mike Stump11289f42009-09-09 15:08:12 +00004407 OverloadedFunctionDecl *Overloads
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004408 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004409 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004410 FuncEnd = Functions.end();
4411 Func != FuncEnd; ++Func)
4412 Overloads->addOverload(*Func);
4413
4414 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4415 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004416
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004417 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004418 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004419 Context.DependentTy,
4420 OpLoc));
4421 }
4422
4423 // If this is the .* operator, which is not overloadable, just
4424 // create a built-in binary operator.
4425 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004426 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004427
4428 // If this is one of the assignment operators, we only perform
4429 // overload resolution if the left-hand side is a class or
4430 // enumeration type (C++ [expr.ass]p3).
4431 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregore9899d92009-08-26 17:08:25 +00004432 !Args[0]->getType()->isOverloadableType())
4433 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004434
Douglas Gregor084d8552009-03-13 23:49:33 +00004435 // Build an empty overload set.
4436 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004437
4438 // Add the candidates from the given function set.
4439 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4440
4441 // Add operator candidates that are member functions.
4442 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4443
4444 // Add builtin operator candidates.
4445 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4446
4447 // Perform overload resolution.
4448 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004449 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004450 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004451 // We found a built-in operator or an overloaded operator.
4452 FunctionDecl *FnDecl = Best->Function;
4453
4454 if (FnDecl) {
4455 // We matched an overloaded operator. Build a call to that
4456 // operator.
4457
4458 // Convert the arguments.
4459 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004460 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4461 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004462 "passing"))
4463 return ExprError();
4464 } else {
4465 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004466 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004467 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004468 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004469 "passing"))
4470 return ExprError();
4471 }
4472
4473 // Determine the result type
4474 QualType ResultTy
4475 = FnDecl->getType()->getAsFunctionType()->getResultType();
4476 ResultTy = ResultTy.getNonReferenceType();
4477
4478 // Build the actual expression node.
4479 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004480 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004481 UsualUnaryConversions(FnExpr);
4482
Mike Stump11289f42009-09-09 15:08:12 +00004483 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004484 Args, 2, ResultTy, OpLoc);
4485 return MaybeBindToTemporary(CE);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004486 } else {
4487 // We matched a built-in operator. Convert the arguments, then
4488 // break out so that we will build the appropriate built-in
4489 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004490 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004491 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004492 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004493 Best->Conversions[1], "passing"))
4494 return ExprError();
4495
4496 break;
4497 }
4498 }
4499
4500 case OR_No_Viable_Function:
Sebastian Redl027de2a2009-05-21 11:50:50 +00004501 // For class as left operand for assignment or compound assigment operator
4502 // do not fall through to handling in built-in, but report that no overloaded
4503 // assignment operator found
Douglas Gregore9899d92009-08-26 17:08:25 +00004504 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004505 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4506 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004507 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl027de2a2009-05-21 11:50:50 +00004508 return ExprError();
4509 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004510 // No viable function; fall through to handling this as a
4511 // built-in operator, which will produce an error message for us.
4512 break;
4513
4514 case OR_Ambiguous:
4515 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4516 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004517 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004518 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4519 return ExprError();
4520
4521 case OR_Deleted:
4522 Diag(OpLoc, diag::err_ovl_deleted_oper)
4523 << Best->Function->isDeleted()
4524 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004525 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004526 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4527 return ExprError();
4528 }
4529
4530 // Either we found no viable overloaded operator or we matched a
4531 // built-in operator. In either case, try to build a built-in
4532 // operation.
Douglas Gregore9899d92009-08-26 17:08:25 +00004533 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004534}
4535
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004536/// BuildCallToMemberFunction - Build a call to a member
4537/// function. MemExpr is the expression that refers to the member
4538/// function (and includes the object parameter), Args/NumArgs are the
4539/// arguments to the function call (not including the object
4540/// parameter). The caller needs to validate that the member
4541/// expression refers to a member function or an overloaded member
4542/// function.
4543Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00004544Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4545 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004546 unsigned NumArgs, SourceLocation *CommaLocs,
4547 SourceLocation RParenLoc) {
4548 // Dig out the member expression. This holds both the object
4549 // argument and the member function we're referring to.
4550 MemberExpr *MemExpr = 0;
4551 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4552 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4553 else
4554 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4555 assert(MemExpr && "Building member call without member expression");
4556
4557 // Extract the object argument.
4558 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004559
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004560 CXXMethodDecl *Method = 0;
Douglas Gregor97628d62009-08-21 00:16:32 +00004561 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4562 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004563 // Add overload candidates
4564 OverloadCandidateSet CandidateSet;
Douglas Gregor97628d62009-08-21 00:16:32 +00004565 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004566
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004567 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4568 Func != FuncEnd; ++Func) {
4569 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
Mike Stump11289f42009-09-09 15:08:12 +00004570 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004571 /*SuppressUserConversions=*/false);
4572 else
Douglas Gregor84f14dd2009-09-01 00:37:14 +00004573 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4574 MemExpr->hasExplicitTemplateArgumentList(),
4575 MemExpr->getTemplateArgs(),
4576 MemExpr->getNumTemplateArgs(),
4577 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004578 CandidateSet,
4579 /*SuppressUsedConversions=*/false);
4580 }
Mike Stump11289f42009-09-09 15:08:12 +00004581
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004582 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004583 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004584 case OR_Success:
4585 Method = cast<CXXMethodDecl>(Best->Function);
4586 break;
4587
4588 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004589 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004590 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004591 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004592 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4593 // FIXME: Leaking incoming expressions!
4594 return true;
4595
4596 case OR_Ambiguous:
Mike Stump11289f42009-09-09 15:08:12 +00004597 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004598 diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004599 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004600 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4601 // FIXME: Leaking incoming expressions!
4602 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004603
4604 case OR_Deleted:
Mike Stump11289f42009-09-09 15:08:12 +00004605 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00004606 diag::err_ovl_deleted_member_call)
4607 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00004608 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004609 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4610 // FIXME: Leaking incoming expressions!
4611 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004612 }
4613
4614 FixOverloadedFunctionReference(MemExpr, Method);
4615 } else {
4616 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4617 }
4618
4619 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00004620 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004621 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00004622 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004623 Method->getResultType().getNonReferenceType(),
4624 RParenLoc));
4625
4626 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00004627 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004628 PerformObjectArgumentInitialization(ObjectArg, Method))
4629 return true;
4630 MemExpr->setBase(ObjectArg);
4631
4632 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004633 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004634 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004635 RParenLoc))
4636 return true;
4637
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004638 if (CheckFunctionCall(Method, TheCall.get()))
4639 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00004640
4641 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004642}
4643
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004644/// BuildCallToObjectOfClassType - Build a call to an object of class
4645/// type (C++ [over.call.object]), which can end up invoking an
4646/// overloaded function call operator (@c operator()) or performing a
4647/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00004648Sema::ExprResult
4649Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00004650 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004651 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004652 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004653 SourceLocation RParenLoc) {
4654 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004655 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00004656
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004657 // C++ [over.call.object]p1:
4658 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00004659 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004660 // candidate functions includes at least the function call
4661 // operators of T. The function call operators of T are obtained by
4662 // ordinary lookup of the name operator() in the context of
4663 // (E).operator().
4664 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00004665 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004666 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004667 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004668 Oper != OperEnd; ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00004669 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor55297ac2008-12-23 00:26:44 +00004670 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004671
Douglas Gregorab7897a2008-11-19 22:57:39 +00004672 // C++ [over.call.object]p2:
4673 // In addition, for each conversion function declared in T of the
4674 // form
4675 //
4676 // operator conversion-type-id () cv-qualifier;
4677 //
4678 // where cv-qualifier is the same cv-qualification as, or a
4679 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00004680 // denotes the type "pointer to function of (P1,...,Pn) returning
4681 // R", or the type "reference to pointer to function of
4682 // (P1,...,Pn) returning R", or the type "reference to function
4683 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00004684 // is also considered as a candidate function. Similarly,
4685 // surrogate call functions are added to the set of candidate
4686 // functions for each conversion function declared in an
4687 // accessible base class provided the function is not hidden
4688 // within T by another intervening declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004689
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004690 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4691 // FIXME: Look in base classes for more conversion operators!
Mike Stump11289f42009-09-09 15:08:12 +00004692 OverloadedFunctionDecl *Conversions
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004693 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00004694 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004695 Func = Conversions->function_begin(),
4696 FuncEnd = Conversions->function_end();
4697 Func != FuncEnd; ++Func) {
4698 CXXConversionDecl *Conv;
4699 FunctionTemplateDecl *ConvTemplate;
4700 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00004701
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004702 // Skip over templated conversion functions; they aren't
4703 // surrogates.
4704 if (ConvTemplate)
4705 continue;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004706
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004707 // Strip the reference type (if any) and then the pointer type (if
4708 // any) to get down to what might be a function type.
4709 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4710 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4711 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004712
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004713 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
4714 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4715 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004716 }
Mike Stump11289f42009-09-09 15:08:12 +00004717
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004718 // Perform overload resolution.
4719 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004720 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004721 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00004722 // Overload resolution succeeded; we'll build the appropriate call
4723 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004724 break;
4725
4726 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004727 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00004728 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004729 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00004730 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004731 break;
4732
4733 case OR_Ambiguous:
4734 Diag(Object->getSourceRange().getBegin(),
4735 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004736 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004737 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4738 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004739
4740 case OR_Deleted:
4741 Diag(Object->getSourceRange().getBegin(),
4742 diag::err_ovl_deleted_object_call)
4743 << Best->Function->isDeleted()
4744 << Object->getType() << Object->getSourceRange();
4745 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4746 break;
Mike Stump11289f42009-09-09 15:08:12 +00004747 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004748
Douglas Gregorab7897a2008-11-19 22:57:39 +00004749 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004750 // We had an error; delete all of the subexpressions and return
4751 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00004752 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004753 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00004754 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004755 return true;
4756 }
4757
Douglas Gregorab7897a2008-11-19 22:57:39 +00004758 if (Best->Function == 0) {
4759 // Since there is no function declaration, this is one of the
4760 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00004761 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00004762 = cast<CXXConversionDecl>(
4763 Best->Conversions[0].UserDefined.ConversionFunction);
4764
4765 // We selected one of the surrogate functions that converts the
4766 // object parameter to a function pointer. Perform the conversion
4767 // on the object argument, then let ActOnCallExpr finish the job.
4768 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004769 ImpCastExprToType(Object,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004770 Conv->getConversionType().getNonReferenceType(),
Anders Carlssona076d142009-07-31 01:23:52 +00004771 CastExpr::CK_Unknown,
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004772 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004773 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4774 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4775 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004776 }
4777
4778 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4779 // that calls this method, using Object for the implicit object
4780 // parameter and passing along the remaining arguments.
4781 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004782 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004783
4784 unsigned NumArgsInProto = Proto->getNumArgs();
4785 unsigned NumArgsToCheck = NumArgs;
4786
4787 // Build the full argument list for the method call (the
4788 // implicit object parameter is placed at the beginning of the
4789 // list).
4790 Expr **MethodArgs;
4791 if (NumArgs < NumArgsInProto) {
4792 NumArgsToCheck = NumArgsInProto;
4793 MethodArgs = new Expr*[NumArgsInProto + 1];
4794 } else {
4795 MethodArgs = new Expr*[NumArgs + 1];
4796 }
4797 MethodArgs[0] = Object;
4798 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4799 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00004800
4801 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004802 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004803 UsualUnaryConversions(NewFn);
4804
4805 // Once we've built TheCall, all of the expressions are properly
4806 // owned.
4807 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004808 ExprOwningPtr<CXXOperatorCallExpr>
4809 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004810 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00004811 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004812 delete [] MethodArgs;
4813
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004814 // We may have default arguments. If so, we need to allocate more
4815 // slots in the call for them.
4816 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00004817 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004818 else if (NumArgs > NumArgsInProto)
4819 NumArgsToCheck = NumArgsInProto;
4820
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004821 bool IsError = false;
4822
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004823 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004824 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004825 TheCall->setArg(0, Object);
4826
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004827
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004828 // Check the argument types.
4829 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004830 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004831 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004832 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00004833
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004834 // Pass the argument.
4835 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004836 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004837 } else {
Anders Carlssone8271232009-08-14 18:30:22 +00004838 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004839 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004840
4841 TheCall->setArg(i + 1, Arg);
4842 }
4843
4844 // If this is a variadic call, handle args passed through "...".
4845 if (Proto->isVariadic()) {
4846 // Promote the arguments (C99 6.5.2.2p7).
4847 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4848 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004849 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004850 TheCall->setArg(i + 1, Arg);
4851 }
4852 }
4853
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004854 if (IsError) return true;
4855
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004856 if (CheckFunctionCall(Method, TheCall.get()))
4857 return true;
4858
Anders Carlsson1c83deb2009-08-16 03:53:54 +00004859 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004860}
4861
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004862/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00004863/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004864/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00004865Sema::OwningExprResult
4866Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4867 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004868 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00004869
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004870 // C++ [over.ref]p1:
4871 //
4872 // [...] An expression x->m is interpreted as (x.operator->())->m
4873 // for a class object x of type T if T::operator->() exists and if
4874 // the operator is selected as the best match function by the
4875 // overload resolution mechanism (13.3).
4876 // FIXME: look in base classes.
4877 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4878 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004879 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00004880
Anders Carlsson78b54932009-09-10 23:18:36 +00004881 LookupResult R = LookupQualifiedName(BaseRecord->getDecl(), OpName,
4882 LookupOrdinaryName);
4883
4884 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
4885 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00004886 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004887 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004888
4889 // Perform overload resolution.
4890 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004891 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004892 case OR_Success:
4893 // Overload resolution succeeded; we'll build the call below.
4894 break;
4895
4896 case OR_No_Viable_Function:
4897 if (CandidateSet.empty())
4898 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00004899 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004900 else
4901 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00004902 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004903 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00004904 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004905
4906 case OR_Ambiguous:
4907 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00004908 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004909 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00004910 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004911
4912 case OR_Deleted:
4913 Diag(OpLoc, diag::err_ovl_deleted_oper)
4914 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00004915 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004916 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00004917 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004918 }
4919
4920 // Convert the object parameter.
4921 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00004922 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00004923 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00004924
4925 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00004926 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004927
4928 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00004929 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4930 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004931 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004932 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004933 Method->getResultType().getNonReferenceType(),
4934 OpLoc);
Douglas Gregord8061562009-08-06 03:17:00 +00004935 return Owned(Base);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004936}
4937
Douglas Gregorcd695e52008-11-10 20:40:00 +00004938/// FixOverloadedFunctionReference - E is an expression that refers to
4939/// a C++ overloaded function (possibly with some parentheses and
4940/// perhaps a '&' around it). We have resolved the overloaded function
4941/// to the function declaration Fn, so patch up the expression E to
4942/// refer (possibly indirectly) to Fn.
4943void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4944 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4945 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4946 E->setType(PE->getSubExpr()->getType());
4947 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00004948 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00004949 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004950 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4951 if (Method->isStatic()) {
4952 // Do nothing: static member functions aren't any different
4953 // from non-member functions.
Mike Stump11289f42009-09-09 15:08:12 +00004954 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004955 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4956 // We have taken the address of a pointer to member
4957 // function. Perform the computation here so that we get the
4958 // appropriate pointer to member type.
4959 DRE->setDecl(Fn);
4960 DRE->setType(Fn->getType());
4961 QualType ClassType
4962 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
Mike Stump11289f42009-09-09 15:08:12 +00004963 E->setType(Context.getMemberPointerType(Fn->getType(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004964 ClassType.getTypePtr()));
4965 return;
4966 }
4967 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004968 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00004969 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregorcd695e52008-11-10 20:40:00 +00004970 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor9b146582009-07-08 20:55:45 +00004971 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Mike Stump11289f42009-09-09 15:08:12 +00004972 isa<FunctionTemplateDecl>(DR->getDecl())) &&
Douglas Gregor9b146582009-07-08 20:55:45 +00004973 "Expected overloaded function or function template");
Douglas Gregorcd695e52008-11-10 20:40:00 +00004974 DR->setDecl(Fn);
4975 E->setType(Fn->getType());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004976 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4977 MemExpr->setMemberDecl(Fn);
4978 E->setType(Fn->getType());
Douglas Gregorcd695e52008-11-10 20:40:00 +00004979 } else {
4980 assert(false && "Invalid reference to overloaded function");
4981 }
4982}
4983
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004984} // end namespace clang