blob: 503f226fd66c079a37b58e8f6f8bc84cbebf005d [file] [log] [blame]
Douglas Gregor8e9bebd2008-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 Gregor94b1dd22008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "llvm/Support/Compiler.h"
25#include <algorithm>
26
27namespace clang {
28
29/// GetConversionCategory - Retrieve the implicit conversion
30/// category corresponding to the given implicit conversion kind.
31ImplicitConversionCategory
32GetConversionCategory(ImplicitConversionKind Kind) {
33 static const ImplicitConversionCategory
34 Category[(int)ICK_Num_Conversion_Kinds] = {
35 ICC_Identity,
36 ICC_Lvalue_Transformation,
37 ICC_Lvalue_Transformation,
38 ICC_Lvalue_Transformation,
39 ICC_Qualification_Adjustment,
40 ICC_Promotion,
41 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000042 ICC_Promotion,
43 ICC_Conversion,
44 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000045 ICC_Conversion,
46 ICC_Conversion,
47 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000050 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000051 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000052 ICC_Conversion
53 };
54 return Category[(int)Kind];
55}
56
57/// GetConversionRank - Retrieve the implicit conversion rank
58/// corresponding to the given implicit conversion kind.
59ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
60 static const ImplicitConversionRank
61 Rank[(int)ICK_Num_Conversion_Kinds] = {
62 ICR_Exact_Match,
63 ICR_Exact_Match,
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Promotion,
68 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000069 ICR_Promotion,
70 ICR_Conversion,
71 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000072 ICR_Conversion,
73 ICR_Conversion,
74 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000077 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000078 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000079 ICR_Conversion
80 };
81 return Rank[(int)Kind];
82}
83
84/// GetImplicitConversionName - Return the name of this kind of
85/// implicit conversion.
86const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
87 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
88 "No conversion",
89 "Lvalue-to-rvalue",
90 "Array-to-pointer",
91 "Function-to-pointer",
92 "Qualification",
93 "Integral promotion",
94 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +000095 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000096 "Integral conversion",
97 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +000098 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000099 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000100 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Pointer conversion",
102 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000103 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000104 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000105 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 };
107 return Name[Kind];
108}
109
Douglas Gregor60d62c22008-10-31 16:23:19 +0000110/// StandardConversionSequence - Set the standard conversion
111/// sequence to the identity conversion.
112void StandardConversionSequence::setAsIdentityConversion() {
113 First = ICK_Identity;
114 Second = ICK_Identity;
115 Third = ICK_Identity;
116 Deprecated = false;
117 ReferenceBinding = false;
118 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000119 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000120 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000121}
122
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000123/// getRank - Retrieve the rank of this standard conversion sequence
124/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
125/// implicit conversions.
126ImplicitConversionRank StandardConversionSequence::getRank() const {
127 ImplicitConversionRank Rank = ICR_Exact_Match;
128 if (GetConversionRank(First) > Rank)
129 Rank = GetConversionRank(First);
130 if (GetConversionRank(Second) > Rank)
131 Rank = GetConversionRank(Second);
132 if (GetConversionRank(Third) > Rank)
133 Rank = GetConversionRank(Third);
134 return Rank;
135}
136
137/// isPointerConversionToBool - Determines whether this conversion is
138/// a conversion of a pointer or pointer-to-member to bool. This is
139/// used as part of the ranking of standard conversion sequences
140/// (C++ 13.3.3.2p4).
141bool StandardConversionSequence::isPointerConversionToBool() const
142{
143 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
144 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
145
146 // Note that FromType has not necessarily been transformed by the
147 // array-to-pointer or function-to-pointer implicit conversions, so
148 // check for their presence as well as checking whether FromType is
149 // a pointer.
150 if (ToType->isBooleanType() &&
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000151 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000152 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
153 return true;
154
155 return false;
156}
157
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000158/// isPointerConversionToVoidPointer - Determines whether this
159/// conversion is a conversion of a pointer to a void pointer. This is
160/// used as part of the ranking of standard conversion sequences (C++
161/// 13.3.3.2p4).
162bool
163StandardConversionSequence::
164isPointerConversionToVoidPointer(ASTContext& Context) const
165{
166 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 Kremenek35366a62009-07-17 17:50:17 +0000176 if (const PointerType* ToPtrType = ToType->getAsPointerType())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor8e9bebd2008-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 Gregor225c41e2008-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 Gregor8e9bebd2008-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 Lattnerd9d22dd2008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-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
263// FunctionDecl that New cannot be overloaded with.
264//
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",
272// so IsOverload will not be used.
273//
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
286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl)
288{
289 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
290 // Is this new function an overload of every function in the
291 // overload set?
292 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
293 FuncEnd = Ovl->function_end();
294 for (; Func != FuncEnd; ++Func) {
295 if (!IsOverload(New, *Func, MatchedDecl)) {
296 MatchedDecl = Func;
297 return false;
298 }
299 }
300
301 // This function overloads every function in the overload set.
302 return true;
Douglas Gregore53060f2009-06-25 22:08:12 +0000303 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
304 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
305 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000306 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
307 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
308
309 // C++ [temp.fct]p2:
310 // A function template can be overloaded with other function templates
311 // and with normal (non-template) functions.
312 if ((OldTemplate == 0) != (NewTemplate == 0))
313 return true;
314
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000315 // Is the function New an overload of the function Old?
316 QualType OldQType = Context.getCanonicalType(Old->getType());
317 QualType NewQType = Context.getCanonicalType(New->getType());
318
319 // Compare the signatures (C++ 1.3.10) of the two functions to
320 // determine whether they are overloads. If we find any mismatch
321 // in the signature, they are overloads.
322
323 // If either of these functions is a K&R-style function (no
324 // prototype), then we consider them to have matching signatures.
Douglas Gregor72564e72009-02-26 23:50:07 +0000325 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
326 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000327 return false;
328
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000329 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
330 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000331
332 // The signature of a function includes the types of its
333 // parameters (C++ 1.3.10), which includes the presence or absence
334 // of the ellipsis; see C++ DR 357).
335 if (OldQType != NewQType &&
336 (OldType->getNumArgs() != NewType->getNumArgs() ||
337 OldType->isVariadic() != NewType->isVariadic() ||
338 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
339 NewType->arg_type_begin())))
340 return true;
341
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000342 // C++ [temp.over.link]p4:
343 // The signature of a function template consists of its function
344 // signature, its return type and its template parameter list. The names
345 // of the template parameters are significant only for establishing the
346 // relationship between the template parameters and the rest of the
347 // signature.
348 //
349 // We check the return type and template parameter lists for function
350 // templates first; the remaining checks follow.
351 if (NewTemplate &&
352 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
353 OldTemplate->getTemplateParameters(),
354 false, false, SourceLocation()) ||
355 OldType->getResultType() != NewType->getResultType()))
356 return true;
357
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000358 // If the function is a class member, its signature includes the
359 // cv-qualifiers (if any) on the function itself.
360 //
361 // As part of this, also check whether one of the member functions
362 // is static, in which case they are not overloads (C++
363 // 13.1p2). While not part of the definition of the signature,
364 // this check is important to determine whether these functions
365 // can be overloaded.
366 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
367 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
368 if (OldMethod && NewMethod &&
369 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor1ca50c32008-11-21 15:36:28 +0000370 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000371 return true;
372
373 // The signatures match; this is not an overload.
374 return false;
375 } else {
376 // (C++ 13p1):
377 // Only function declarations can be overloaded; object and type
378 // declarations cannot be overloaded.
379 return false;
380 }
381}
382
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000383/// TryImplicitConversion - Attempt to perform an implicit conversion
384/// from the given expression (Expr) to the given type (ToType). This
385/// function returns an implicit conversion sequence that can be used
386/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000387///
388/// void f(float f);
389/// void g(int i) { f(i); }
390///
391/// this routine would produce an implicit conversion sequence to
392/// describe the initialization of f from i, which will be a standard
393/// conversion sequence containing an lvalue-to-rvalue conversion (C++
394/// 4.1) followed by a floating-integral conversion (C++ 4.9).
395//
396/// Note that this routine only determines how the conversion can be
397/// performed; it does not actually perform the conversion. As such,
398/// it will not produce any diagnostics if no conversion is available,
399/// but will instead return an implicit conversion sequence of kind
400/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000401///
402/// If @p SuppressUserConversions, then user-defined conversions are
403/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000404/// If @p AllowExplicit, then explicit user-defined conversions are
405/// permitted.
Sebastian Redle2b68332009-04-12 17:16:29 +0000406/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
407/// no matter its actual lvalueness.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000408ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +0000409Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000410 bool SuppressUserConversions,
Sebastian Redle2b68332009-04-12 17:16:29 +0000411 bool AllowExplicit, bool ForceRValue)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000412{
413 ImplicitConversionSequence ICS;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000414 if (IsStandardConversion(From, ToType, ICS.Standard))
415 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000416 else if (getLangOptions().CPlusPlus &&
417 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Sebastian Redle2b68332009-04-12 17:16:29 +0000418 !SuppressUserConversions, AllowExplicit,
419 ForceRValue)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000420 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000421 // C++ [over.ics.user]p4:
422 // A conversion of an expression of class type to the same class
423 // type is given Exact Match rank, and a conversion of an
424 // expression of class type to a base class of that type is
425 // given Conversion rank, in spite of the fact that a copy
426 // constructor (i.e., a user-defined conversion function) is
427 // called for those cases.
428 if (CXXConstructorDecl *Constructor
429 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000430 QualType FromCanon
431 = Context.getCanonicalType(From->getType().getUnqualifiedType());
432 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
433 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000434 // Turn this into a "standard" conversion sequence, so that it
435 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000436 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
437 ICS.Standard.setAsIdentityConversion();
438 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
439 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000440 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000441 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000442 ICS.Standard.Second = ICK_Derived_To_Base;
443 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000444 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000445
446 // C++ [over.best.ics]p4:
447 // However, when considering the argument of a user-defined
448 // conversion function that is a candidate by 13.3.1.3 when
449 // invoked for the copying of the temporary in the second step
450 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
451 // 13.3.1.6 in all cases, only standard conversion sequences and
452 // ellipsis conversion sequences are allowed.
453 if (SuppressUserConversions &&
454 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
455 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000456 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000457 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000458
459 return ICS;
460}
461
462/// IsStandardConversion - Determines whether there is a standard
463/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
464/// expression From to the type ToType. Standard conversion sequences
465/// only consider non-class types; for conversions that involve class
466/// types, use TryImplicitConversion. If a conversion exists, SCS will
467/// contain the standard conversion sequence required to perform this
468/// conversion and this routine will return true. Otherwise, this
469/// routine will return false and the value of SCS is unspecified.
470bool
471Sema::IsStandardConversion(Expr* From, QualType ToType,
472 StandardConversionSequence &SCS)
473{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474 QualType FromType = From->getType();
475
Douglas Gregor60d62c22008-10-31 16:23:19 +0000476 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000477 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000478 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000479 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000480 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000481 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000482
Douglas Gregorf9201e02009-02-11 23:02:49 +0000483 // There are no standard conversions for class types in C++, so
484 // abort early. When overloading in C, however, we do permit
485 if (FromType->isRecordType() || ToType->isRecordType()) {
486 if (getLangOptions().CPlusPlus)
487 return false;
488
489 // When we're overloading in C, we allow, as standard conversions,
490 }
491
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000492 // The first conversion can be an lvalue-to-rvalue conversion,
493 // array-to-pointer conversion, or function-to-pointer conversion
494 // (C++ 4p1).
495
496 // Lvalue-to-rvalue conversion (C++ 4.1):
497 // An lvalue (3.10) of a non-function, non-array type T can be
498 // converted to an rvalue.
499 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
500 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000501 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000502 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000503 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000504
505 // If T is a non-class type, the type of the rvalue is the
506 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000507 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
508 // just strip the qualifiers because they don't matter.
509
510 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor60d62c22008-10-31 16:23:19 +0000511 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000512 }
513 // Array-to-pointer conversion (C++ 4.2)
514 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000515 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000516
517 // An lvalue or rvalue of type "array of N T" or "array of unknown
518 // bound of T" can be converted to an rvalue of type "pointer to
519 // T" (C++ 4.2p1).
520 FromType = Context.getArrayDecayedType(FromType);
521
522 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
523 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000524 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000525
526 // For the purpose of ranking in overload resolution
527 // (13.3.3.1.1), this conversion is considered an
528 // array-to-pointer conversion followed by a qualification
529 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000530 SCS.Second = ICK_Identity;
531 SCS.Third = ICK_Qualification;
532 SCS.ToTypePtr = ToType.getAsOpaquePtr();
533 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000534 }
535 }
536 // Function-to-pointer conversion (C++ 4.3).
537 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000538 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000539
540 // An lvalue of function type T can be converted to an rvalue of
541 // type "pointer to T." The result is a pointer to the
542 // function. (C++ 4.3p1).
543 FromType = Context.getPointerType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000544 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000545 // Address of overloaded function (C++ [over.over]).
546 else if (FunctionDecl *Fn
547 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
548 SCS.First = ICK_Function_To_Pointer;
549
550 // We were able to resolve the address of the overloaded function,
551 // so we can convert to the type of that function.
552 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000553 if (ToType->isLValueReferenceType())
554 FromType = Context.getLValueReferenceType(FromType);
555 else if (ToType->isRValueReferenceType())
556 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000557 else if (ToType->isMemberPointerType()) {
558 // Resolve address only succeeds if both sides are member pointers,
559 // but it doesn't have to be the same class. See DR 247.
560 // Note that this means that the type of &Derived::fn can be
561 // Ret (Base::*)(Args) if the fn overload actually found is from the
562 // base class, even if it was brought into the derived class via a
563 // using declaration. The standard isn't clear on this issue at all.
564 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
565 FromType = Context.getMemberPointerType(FromType,
566 Context.getTypeDeclType(M->getParent()).getTypePtr());
567 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000568 FromType = Context.getPointerType(FromType);
569 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000570 // We don't require any conversions for the first step.
571 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000572 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000573 }
574
575 // The second conversion can be an integral promotion, floating
576 // point promotion, integral conversion, floating point conversion,
577 // floating-integral conversion, pointer conversion,
578 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000579 // For overloading in C, this can also be a "compatible-type"
580 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000581 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000582 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000583 // The unqualified versions of the types are the same: there's no
584 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000585 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000586 }
587 // Integral promotion (C++ 4.5).
588 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000589 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000590 FromType = ToType.getUnqualifiedType();
591 }
592 // Floating point promotion (C++ 4.6).
593 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000594 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000595 FromType = ToType.getUnqualifiedType();
596 }
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000597 // Complex promotion (Clang extension)
598 else if (IsComplexPromotion(FromType, ToType)) {
599 SCS.Second = ICK_Complex_Promotion;
600 FromType = ToType.getUnqualifiedType();
601 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000602 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000603 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000604 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000605 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000606 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000607 FromType = ToType.getUnqualifiedType();
608 }
609 // Floating point conversions (C++ 4.8).
610 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000611 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000612 FromType = ToType.getUnqualifiedType();
613 }
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000614 // Complex conversions (C99 6.3.1.6)
615 else if (FromType->isComplexType() && ToType->isComplexType()) {
616 SCS.Second = ICK_Complex_Conversion;
617 FromType = ToType.getUnqualifiedType();
618 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000619 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000620 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000621 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000622 ToType->isIntegralType() && !ToType->isBooleanType() &&
623 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000624 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
625 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000626 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000627 FromType = ToType.getUnqualifiedType();
628 }
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000629 // Complex-real conversions (C99 6.3.1.7)
630 else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
631 (ToType->isComplexType() && FromType->isArithmeticType())) {
632 SCS.Second = ICK_Complex_Real;
633 FromType = ToType.getUnqualifiedType();
634 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000635 // Pointer conversions (C++ 4.10).
Douglas Gregor45920e82008-12-19 17:40:08 +0000636 else if (IsPointerConversion(From, FromType, ToType, FromType,
637 IncompatibleObjC)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000638 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000639 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl07779722008-10-31 14:43:28 +0000640 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000641 // Pointer to member conversions (4.11).
642 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
643 SCS.Second = ICK_Pointer_Member;
644 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000645 // Boolean conversions (C++ 4.12).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000646 else if (ToType->isBooleanType() &&
647 (FromType->isArithmeticType() ||
648 FromType->isEnumeralType() ||
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000649 FromType->isPointerType() ||
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000650 FromType->isBlockPointerType() ||
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000651 FromType->isMemberPointerType() ||
652 FromType->isNullPtrType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000653 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000654 FromType = Context.BoolTy;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000655 }
656 // Compatible conversions (Clang extension for C function overloading)
657 else if (!getLangOptions().CPlusPlus &&
658 Context.typesAreCompatible(ToType, FromType)) {
659 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000660 } else {
661 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000662 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000663 }
664
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000665 QualType CanonFrom;
666 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000667 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000668 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000669 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000670 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000671 CanonFrom = Context.getCanonicalType(FromType);
672 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000673 } else {
674 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000675 SCS.Third = ICK_Identity;
676
677 // C++ [over.best.ics]p6:
678 // [...] Any difference in top-level cv-qualification is
679 // subsumed by the initialization itself and does not constitute
680 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000681 CanonFrom = Context.getCanonicalType(FromType);
682 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000683 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000684 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
685 FromType = ToType;
686 CanonFrom = CanonTo;
687 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000688 }
689
690 // If we have not converted the argument type to the parameter type,
691 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000692 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000693 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000694
Douglas Gregor60d62c22008-10-31 16:23:19 +0000695 SCS.ToTypePtr = FromType.getAsOpaquePtr();
696 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000697}
698
699/// IsIntegralPromotion - Determines whether the conversion from the
700/// expression From (whose potentially-adjusted type is FromType) to
701/// ToType is an integral promotion (C++ 4.5). If so, returns true and
702/// sets PromotedType to the promoted type.
703bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
704{
705 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000706 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000707 if (!To) {
708 return false;
709 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000710
711 // An rvalue of type char, signed char, unsigned char, short int, or
712 // unsigned short int can be converted to an rvalue of type int if
713 // int can represent all the values of the source type; otherwise,
714 // the source rvalue can be converted to an rvalue of type unsigned
715 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000716 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000717 if (// We can promote any signed, promotable integer type to an int
718 (FromType->isSignedIntegerType() ||
719 // We can promote any unsigned integer type whose size is
720 // less than int to an int.
721 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000722 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000723 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000724 }
725
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000726 return To->getKind() == BuiltinType::UInt;
727 }
728
729 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
730 // can be converted to an rvalue of the first of the following types
731 // that can represent all the values of its underlying type: int,
732 // unsigned int, long, or unsigned long (C++ 4.5p2).
733 if ((FromType->isEnumeralType() || FromType->isWideCharType())
734 && ToType->isIntegerType()) {
735 // Determine whether the type we're converting from is signed or
736 // unsigned.
737 bool FromIsSigned;
738 uint64_t FromSize = Context.getTypeSize(FromType);
739 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
740 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
741 FromIsSigned = UnderlyingType->isSignedIntegerType();
742 } else {
743 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
744 FromIsSigned = true;
745 }
746
747 // The types we'll try to promote to, in the appropriate
748 // order. Try each of these types.
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000749 QualType PromoteTypes[6] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000750 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000751 Context.LongTy, Context.UnsignedLongTy ,
752 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000753 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000754 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000755 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
756 if (FromSize < ToSize ||
757 (FromSize == ToSize &&
758 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
759 // We found the type that we can promote to. If this is the
760 // type we wanted, we have a promotion. Otherwise, no
761 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000762 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000763 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
764 }
765 }
766 }
767
768 // An rvalue for an integral bit-field (9.6) can be converted to an
769 // rvalue of type int if int can represent all the values of the
770 // bit-field; otherwise, it can be converted to unsigned int if
771 // unsigned int can represent all the values of the bit-field. If
772 // the bit-field is larger yet, no integral promotion applies to
773 // it. If the bit-field has an enumerated type, it is treated as any
774 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000775 // FIXME: We should delay checking of bit-fields until we actually perform the
776 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000777 using llvm::APSInt;
778 if (From)
779 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000780 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000781 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
782 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
783 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
784 ToSize = Context.getTypeSize(ToType);
Douglas Gregor86f19402008-12-20 23:49:58 +0000785
786 // Are we promoting to an int from a bitfield that fits in an int?
787 if (BitWidth < ToSize ||
788 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
789 return To->getKind() == BuiltinType::Int;
790 }
791
792 // Are we promoting to an unsigned int from an unsigned bitfield
793 // that fits into an unsigned int?
794 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
795 return To->getKind() == BuiltinType::UInt;
796 }
797
798 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000799 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000800 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000801
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000802 // An rvalue of type bool can be converted to an rvalue of type int,
803 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000804 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000805 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000806 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000807
808 return false;
809}
810
811/// IsFloatingPointPromotion - Determines whether the conversion from
812/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
813/// returns true and sets PromotedType to the promoted type.
814bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
815{
816 /// An rvalue of type float can be converted to an rvalue of type
817 /// double. (C++ 4.6p1).
818 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000819 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000820 if (FromBuiltin->getKind() == BuiltinType::Float &&
821 ToBuiltin->getKind() == BuiltinType::Double)
822 return true;
823
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000824 // C99 6.3.1.5p1:
825 // When a float is promoted to double or long double, or a
826 // double is promoted to long double [...].
827 if (!getLangOptions().CPlusPlus &&
828 (FromBuiltin->getKind() == BuiltinType::Float ||
829 FromBuiltin->getKind() == BuiltinType::Double) &&
830 (ToBuiltin->getKind() == BuiltinType::LongDouble))
831 return true;
832 }
833
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000834 return false;
835}
836
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000837/// \brief Determine if a conversion is a complex promotion.
838///
839/// A complex promotion is defined as a complex -> complex conversion
840/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000841/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000842bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
843 const ComplexType *FromComplex = FromType->getAsComplexType();
844 if (!FromComplex)
845 return false;
846
847 const ComplexType *ToComplex = ToType->getAsComplexType();
848 if (!ToComplex)
849 return false;
850
851 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000852 ToComplex->getElementType()) ||
853 IsIntegralPromotion(0, FromComplex->getElementType(),
854 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000855}
856
Douglas Gregorcb7de522008-11-26 23:31:11 +0000857/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
858/// the pointer type FromPtr to a pointer to type ToPointee, with the
859/// same type qualifiers as FromPtr has on its pointee type. ToType,
860/// if non-empty, will be a pointer to ToType that may or may not have
861/// the right set of qualifiers on its pointee.
862static QualType
863BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
864 QualType ToPointee, QualType ToType,
865 ASTContext &Context) {
866 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
867 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
868 unsigned Quals = CanonFromPointee.getCVRQualifiers();
869
870 // Exact qualifier match -> return the pointer type we're converting to.
871 if (CanonToPointee.getCVRQualifiers() == Quals) {
872 // ToType is exactly what we need. Return it.
873 if (ToType.getTypePtr())
874 return ToType;
875
876 // Build a pointer to ToPointee. It has the right qualifiers
877 // already.
878 return Context.getPointerType(ToPointee);
879 }
880
881 // Just build a canonical type that has the right qualifiers.
882 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
883}
884
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000885/// IsPointerConversion - Determines whether the conversion of the
886/// expression From, which has the (possibly adjusted) type FromType,
887/// can be converted to the type ToType via a pointer conversion (C++
888/// 4.10). If so, returns true and places the converted type (that
889/// might differ from ToType in its cv-qualifiers at some level) into
890/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000891///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000892/// This routine also supports conversions to and from block pointers
893/// and conversions with Objective-C's 'id', 'id<protocols...>', and
894/// pointers to interfaces. FIXME: Once we've determined the
895/// appropriate overloading rules for Objective-C, we may want to
896/// split the Objective-C checks into a different routine; however,
897/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000898/// conversions, so for now they live here. IncompatibleObjC will be
899/// set if the conversion is an allowed Objective-C conversion that
900/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000901bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000902 QualType& ConvertedType,
903 bool &IncompatibleObjC)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000904{
Douglas Gregor45920e82008-12-19 17:40:08 +0000905 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000906 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
907 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000908
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000909 // Conversion from a null pointer constant to any Objective-C pointer type.
Steve Narofff4954562009-07-16 15:41:00 +0000910 if (ToType->isObjCObjectPointerType() &&
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000911 From->isNullPointerConstant(Context)) {
912 ConvertedType = ToType;
913 return true;
914 }
915
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000916 // Blocks: Block pointers can be converted to void*.
917 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek35366a62009-07-17 17:50:17 +0000918 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000919 ConvertedType = ToType;
920 return true;
921 }
922 // Blocks: A null pointer constant can be converted to a block
923 // pointer type.
924 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
925 ConvertedType = ToType;
926 return true;
927 }
928
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000929 // If the left-hand-side is nullptr_t, the right side can be a null
930 // pointer constant.
931 if (ToType->isNullPtrType() && From->isNullPointerConstant(Context)) {
932 ConvertedType = ToType;
933 return true;
934 }
935
Ted Kremenek35366a62009-07-17 17:50:17 +0000936 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000937 if (!ToTypePtr)
938 return false;
939
940 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
941 if (From->isNullPointerConstant(Context)) {
942 ConvertedType = ToType;
943 return true;
944 }
Sebastian Redl07779722008-10-31 14:43:28 +0000945
Douglas Gregorcb7de522008-11-26 23:31:11 +0000946 // Beyond this point, both types need to be pointers.
Ted Kremenek35366a62009-07-17 17:50:17 +0000947 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregorcb7de522008-11-26 23:31:11 +0000948 if (!FromTypePtr)
949 return false;
950
951 QualType FromPointeeType = FromTypePtr->getPointeeType();
952 QualType ToPointeeType = ToTypePtr->getPointeeType();
953
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000954 // An rvalue of type "pointer to cv T," where T is an object type,
955 // can be converted to an rvalue of type "pointer to cv void" (C++
956 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +0000957 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000958 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
959 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000960 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000961 return true;
962 }
963
Douglas Gregorf9201e02009-02-11 23:02:49 +0000964 // When we're overloading in C, we allow a special kind of pointer
965 // conversion for compatible-but-not-identical pointee types.
966 if (!getLangOptions().CPlusPlus &&
967 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
968 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
969 ToPointeeType,
970 ToType, Context);
971 return true;
972 }
973
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000974 // C++ [conv.ptr]p3:
975 //
976 // An rvalue of type "pointer to cv D," where D is a class type,
977 // can be converted to an rvalue of type "pointer to cv B," where
978 // B is a base class (clause 10) of D. If B is an inaccessible
979 // (clause 11) or ambiguous (10.2) base class of D, a program that
980 // necessitates this conversion is ill-formed. The result of the
981 // conversion is a pointer to the base class sub-object of the
982 // derived class object. The null pointer value is converted to
983 // the null pointer value of the destination type.
984 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000985 // Note that we do not check for ambiguity or inaccessibility
986 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +0000987 if (getLangOptions().CPlusPlus &&
988 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorcb7de522008-11-26 23:31:11 +0000989 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000990 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
991 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000992 ToType, Context);
993 return true;
994 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000995
Douglas Gregorc7887512008-12-19 19:13:09 +0000996 return false;
997}
998
999/// isObjCPointerConversion - Determines whether this is an
1000/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1001/// with the same arguments and return values.
1002bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1003 QualType& ConvertedType,
1004 bool &IncompatibleObjC) {
1005 if (!getLangOptions().ObjC1)
1006 return false;
1007
Steve Naroff14108da2009-07-10 23:34:53 +00001008 // First, we handle all conversions on ObjC object pointer types.
1009 const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
1010 const ObjCObjectPointerType *FromObjCPtr =
1011 FromType->getAsObjCObjectPointerType();
Douglas Gregorc7887512008-12-19 19:13:09 +00001012
Steve Naroff14108da2009-07-10 23:34:53 +00001013 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001014 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001015 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001016 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001017 ConvertedType = ToType;
1018 return true;
1019 }
1020 // Conversions with Objective-C's id<...>.
1021 if ((FromObjCPtr->isObjCQualifiedIdType() ||
1022 ToObjCPtr->isObjCQualifiedIdType()) &&
1023 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
1024 ConvertedType = ToType;
1025 return true;
1026 }
1027 // Objective C++: We're able to convert from a pointer to an
1028 // interface to a pointer to a different interface.
1029 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1030 ConvertedType = ToType;
1031 return true;
1032 }
1033
1034 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1035 // Okay: this is some kind of implicit downcast of Objective-C
1036 // interfaces, which is permitted. However, we're going to
1037 // complain about it.
1038 IncompatibleObjC = true;
1039 ConvertedType = FromType;
1040 return true;
1041 }
1042 }
1043 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001044 QualType ToPointeeType;
Ted Kremenek35366a62009-07-17 17:50:17 +00001045 if (const PointerType *ToCPtr = ToType->getAsPointerType())
Steve Naroff14108da2009-07-10 23:34:53 +00001046 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenek35366a62009-07-17 17:50:17 +00001047 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001048 ToPointeeType = ToBlockPtr->getPointeeType();
1049 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001050 return false;
1051
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001052 QualType FromPointeeType;
Ted Kremenek35366a62009-07-17 17:50:17 +00001053 if (const PointerType *FromCPtr = FromType->getAsPointerType())
Steve Naroff14108da2009-07-10 23:34:53 +00001054 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek35366a62009-07-17 17:50:17 +00001055 else if (const BlockPointerType *FromBlockPtr = FromType->getAsBlockPointerType())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001056 FromPointeeType = FromBlockPtr->getPointeeType();
1057 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001058 return false;
1059
Douglas Gregorc7887512008-12-19 19:13:09 +00001060 // If we have pointers to pointers, recursively check whether this
1061 // is an Objective-C conversion.
1062 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1063 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1064 IncompatibleObjC)) {
1065 // We always complain about this conversion.
1066 IncompatibleObjC = true;
1067 ConvertedType = ToType;
1068 return true;
1069 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001070 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001071 // differences in the argument and result types are in Objective-C
1072 // pointer conversions. If so, we permit the conversion (but
1073 // complain about it).
Douglas Gregor72564e72009-02-26 23:50:07 +00001074 const FunctionProtoType *FromFunctionType
1075 = FromPointeeType->getAsFunctionProtoType();
1076 const FunctionProtoType *ToFunctionType
1077 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregorc7887512008-12-19 19:13:09 +00001078 if (FromFunctionType && ToFunctionType) {
1079 // If the function types are exactly the same, this isn't an
1080 // Objective-C pointer conversion.
1081 if (Context.getCanonicalType(FromPointeeType)
1082 == Context.getCanonicalType(ToPointeeType))
1083 return false;
1084
1085 // Perform the quick checks that will tell us whether these
1086 // function types are obviously different.
1087 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1088 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1089 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1090 return false;
1091
1092 bool HasObjCConversion = false;
1093 if (Context.getCanonicalType(FromFunctionType->getResultType())
1094 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1095 // Okay, the types match exactly. Nothing to do.
1096 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1097 ToFunctionType->getResultType(),
1098 ConvertedType, IncompatibleObjC)) {
1099 // Okay, we have an Objective-C pointer conversion.
1100 HasObjCConversion = true;
1101 } else {
1102 // Function types are too different. Abort.
1103 return false;
1104 }
1105
1106 // Check argument types.
1107 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1108 ArgIdx != NumArgs; ++ArgIdx) {
1109 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1110 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1111 if (Context.getCanonicalType(FromArgType)
1112 == Context.getCanonicalType(ToArgType)) {
1113 // Okay, the types match exactly. Nothing to do.
1114 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1115 ConvertedType, IncompatibleObjC)) {
1116 // Okay, we have an Objective-C pointer conversion.
1117 HasObjCConversion = true;
1118 } else {
1119 // Argument types are too different. Abort.
1120 return false;
1121 }
1122 }
1123
1124 if (HasObjCConversion) {
1125 // We had an Objective-C conversion. Allow this pointer
1126 // conversion, but complain about it.
1127 ConvertedType = ToType;
1128 IncompatibleObjC = true;
1129 return true;
1130 }
1131 }
1132
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001133 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001134}
1135
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001136/// CheckPointerConversion - Check the pointer conversion from the
1137/// expression From to the type ToType. This routine checks for
1138/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1139/// conversions for which IsPointerConversion has already returned
1140/// true. It returns true and produces a diagnostic if there was an
1141/// error, or returns false otherwise.
1142bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1143 QualType FromType = From->getType();
1144
Ted Kremenek35366a62009-07-17 17:50:17 +00001145 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1146 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001147 QualType FromPointeeType = FromPtrType->getPointeeType(),
1148 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001149
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001150 if (FromPointeeType->isRecordType() &&
1151 ToPointeeType->isRecordType()) {
1152 // We must have a derived-to-base conversion. Check an
1153 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +00001154 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1155 From->getExprLoc(),
1156 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001157 }
1158 }
Steve Naroff14108da2009-07-10 23:34:53 +00001159 if (const ObjCObjectPointerType *FromPtrType =
1160 FromType->getAsObjCObjectPointerType())
1161 if (const ObjCObjectPointerType *ToPtrType =
1162 ToType->getAsObjCObjectPointerType()) {
1163 // Objective-C++ conversions are always okay.
1164 // FIXME: We should have a different class of conversions for the
1165 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001166 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001167 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001168
Steve Naroff14108da2009-07-10 23:34:53 +00001169 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001170 return false;
1171}
1172
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001173/// IsMemberPointerConversion - Determines whether the conversion of the
1174/// expression From, which has the (possibly adjusted) type FromType, can be
1175/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1176/// If so, returns true and places the converted type (that might differ from
1177/// ToType in its cv-qualifiers at some level) into ConvertedType.
1178bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1179 QualType ToType, QualType &ConvertedType)
1180{
Ted Kremenek35366a62009-07-17 17:50:17 +00001181 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001182 if (!ToTypePtr)
1183 return false;
1184
1185 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1186 if (From->isNullPointerConstant(Context)) {
1187 ConvertedType = ToType;
1188 return true;
1189 }
1190
1191 // Otherwise, both types have to be member pointers.
Ted Kremenek35366a62009-07-17 17:50:17 +00001192 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001193 if (!FromTypePtr)
1194 return false;
1195
1196 // A pointer to member of B can be converted to a pointer to member of D,
1197 // where D is derived from B (C++ 4.11p2).
1198 QualType FromClass(FromTypePtr->getClass(), 0);
1199 QualType ToClass(ToTypePtr->getClass(), 0);
1200 // FIXME: What happens when these are dependent? Is this function even called?
1201
1202 if (IsDerivedFrom(ToClass, FromClass)) {
1203 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1204 ToClass.getTypePtr());
1205 return true;
1206 }
1207
1208 return false;
1209}
1210
1211/// CheckMemberPointerConversion - Check the member pointer conversion from the
1212/// expression From to the type ToType. This routine checks for ambiguous or
1213/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1214/// for which IsMemberPointerConversion has already returned true. It returns
1215/// true and produces a diagnostic if there was an error, or returns false
1216/// otherwise.
1217bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1218 QualType FromType = From->getType();
Ted Kremenek35366a62009-07-17 17:50:17 +00001219 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001220 if (!FromPtrType)
1221 return false;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001222
Ted Kremenek35366a62009-07-17 17:50:17 +00001223 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001224 assert(ToPtrType && "No member pointer cast has a target type "
1225 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001226
Sebastian Redl21593ac2009-01-28 18:33:18 +00001227 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1228 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001229
Sebastian Redl21593ac2009-01-28 18:33:18 +00001230 // FIXME: What about dependent types?
1231 assert(FromClass->isRecordType() && "Pointer into non-class.");
1232 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001233
Sebastian Redl21593ac2009-01-28 18:33:18 +00001234 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1235 /*DetectVirtual=*/true);
1236 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1237 assert(DerivationOkay &&
1238 "Should not have been called if derivation isn't OK.");
1239 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001240
Sebastian Redl21593ac2009-01-28 18:33:18 +00001241 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1242 getUnqualifiedType())) {
1243 // Derivation is ambiguous. Redo the check to find the exact paths.
1244 Paths.clear();
1245 Paths.setRecordingPaths(true);
1246 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1247 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1248 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001249
Sebastian Redl21593ac2009-01-28 18:33:18 +00001250 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1251 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1252 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1253 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001254 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001255
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001256 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001257 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1258 << FromClass << ToClass << QualType(VBase, 0)
1259 << From->getSourceRange();
1260 return true;
1261 }
1262
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001263 return false;
1264}
1265
Douglas Gregor98cd5992008-10-21 23:43:52 +00001266/// IsQualificationConversion - Determines whether the conversion from
1267/// an rvalue of type FromType to ToType is a qualification conversion
1268/// (C++ 4.4).
1269bool
1270Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1271{
1272 FromType = Context.getCanonicalType(FromType);
1273 ToType = Context.getCanonicalType(ToType);
1274
1275 // If FromType and ToType are the same type, this is not a
1276 // qualification conversion.
1277 if (FromType == ToType)
1278 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001279
Douglas Gregor98cd5992008-10-21 23:43:52 +00001280 // (C++ 4.4p4):
1281 // A conversion can add cv-qualifiers at levels other than the first
1282 // in multi-level pointers, subject to the following rules: [...]
1283 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001284 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001285 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001286 // Within each iteration of the loop, we check the qualifiers to
1287 // determine if this still looks like a qualification
1288 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001289 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001290 // until there are no more pointers or pointers-to-members left to
1291 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001292 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001293
1294 // -- for every j > 0, if const is in cv 1,j then const is in cv
1295 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001296 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001297 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001298
Douglas Gregor98cd5992008-10-21 23:43:52 +00001299 // -- if the cv 1,j and cv 2,j are different, then const is in
1300 // every cv for 0 < k < j.
1301 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001302 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001303 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001304
Douglas Gregor98cd5992008-10-21 23:43:52 +00001305 // Keep track of whether all prior cv-qualifiers in the "to" type
1306 // include const.
1307 PreviousToQualsIncludeConst
1308 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001309 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001310
1311 // We are left with FromType and ToType being the pointee types
1312 // after unwrapping the original FromType and ToType the same number
1313 // of types. If we unwrapped any pointers, and if FromType and
1314 // ToType have the same unqualified type (since we checked
1315 // qualifiers above), then this is a qualification conversion.
1316 return UnwrappedAnyPointer &&
1317 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1318}
1319
Douglas Gregor734d9862009-01-30 23:27:23 +00001320/// Determines whether there is a user-defined conversion sequence
1321/// (C++ [over.ics.user]) that converts expression From to the type
1322/// ToType. If such a conversion exists, User will contain the
1323/// user-defined conversion sequence that performs such a conversion
1324/// and this routine will return true. Otherwise, this routine returns
1325/// false and User is unspecified.
1326///
1327/// \param AllowConversionFunctions true if the conversion should
1328/// consider conversion functions at all. If false, only constructors
1329/// will be considered.
1330///
1331/// \param AllowExplicit true if the conversion should consider C++0x
1332/// "explicit" conversion functions as well as non-explicit conversion
1333/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001334///
1335/// \param ForceRValue true if the expression should be treated as an rvalue
1336/// for overload resolution.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001337bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001338 UserDefinedConversionSequence& User,
Douglas Gregor734d9862009-01-30 23:27:23 +00001339 bool AllowConversionFunctions,
Sebastian Redle2b68332009-04-12 17:16:29 +00001340 bool AllowExplicit, bool ForceRValue)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001341{
1342 OverloadCandidateSet CandidateSet;
Ted Kremenek35366a62009-07-17 17:50:17 +00001343 if (const RecordType *ToRecordType = ToType->getAsRecordType()) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001344 if (CXXRecordDecl *ToRecordDecl
1345 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1346 // C++ [over.match.ctor]p1:
1347 // When objects of class type are direct-initialized (8.5), or
1348 // copy-initialized from an expression of the same or a
1349 // derived class type (8.5), overload resolution selects the
1350 // constructor. [...] For copy-initialization, the candidate
1351 // functions are all the converting constructors (12.3.1) of
1352 // that class. The argument list is the expression-list within
1353 // the parentheses of the initializer.
1354 DeclarationName ConstructorName
1355 = Context.DeclarationNames.getCXXConstructorName(
1356 Context.getCanonicalType(ToType).getUnqualifiedType());
1357 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001358 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001359 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001360 Con != ConEnd; ++Con) {
1361 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1362 if (Constructor->isConvertingConstructor())
1363 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00001364 /*SuppressUserConversions=*/true, ForceRValue);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001365 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001366 }
1367 }
1368
Douglas Gregor734d9862009-01-30 23:27:23 +00001369 if (!AllowConversionFunctions) {
1370 // Don't allow any conversion functions to enter the overload set.
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001371 } else if (const RecordType *FromRecordType
Ted Kremenek35366a62009-07-17 17:50:17 +00001372 = From->getType()->getAsRecordType()) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001373 if (CXXRecordDecl *FromRecordDecl
1374 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1375 // Add all of the conversion functions as candidates.
1376 // FIXME: Look for conversions in base classes!
1377 OverloadedFunctionDecl *Conversions
1378 = FromRecordDecl->getConversionFunctions();
1379 for (OverloadedFunctionDecl::function_iterator Func
1380 = Conversions->function_begin();
1381 Func != Conversions->function_end(); ++Func) {
1382 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1383 if (AllowExplicit || !Conv->isExplicit())
1384 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1385 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001386 }
1387 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001388
1389 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001390 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001391 case OR_Success:
1392 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001393 if (CXXConstructorDecl *Constructor
1394 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1395 // C++ [over.ics.user]p1:
1396 // If the user-defined conversion is specified by a
1397 // constructor (12.3.1), the initial standard conversion
1398 // sequence converts the source type to the type required by
1399 // the argument of the constructor.
1400 //
1401 // FIXME: What about ellipsis conversions?
1402 QualType ThisType = Constructor->getThisType(Context);
1403 User.Before = Best->Conversions[0].Standard;
1404 User.ConversionFunction = Constructor;
1405 User.After.setAsIdentityConversion();
1406 User.After.FromTypePtr
Ted Kremenek35366a62009-07-17 17:50:17 +00001407 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
Douglas Gregor60d62c22008-10-31 16:23:19 +00001408 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1409 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001410 } else if (CXXConversionDecl *Conversion
1411 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1412 // C++ [over.ics.user]p1:
1413 //
1414 // [...] If the user-defined conversion is specified by a
1415 // conversion function (12.3.2), the initial standard
1416 // conversion sequence converts the source type to the
1417 // implicit object parameter of the conversion function.
1418 User.Before = Best->Conversions[0].Standard;
1419 User.ConversionFunction = Conversion;
1420
1421 // C++ [over.ics.user]p2:
1422 // The second standard conversion sequence converts the
1423 // result of the user-defined conversion to the target type
1424 // for the sequence. Since an implicit conversion sequence
1425 // is an initialization, the special rules for
1426 // initialization by user-defined conversion apply when
1427 // selecting the best user-defined conversion for a
1428 // user-defined conversion sequence (see 13.3.3 and
1429 // 13.3.3.1).
1430 User.After = Best->FinalConversion;
1431 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001432 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001433 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001434 return false;
1435 }
1436
1437 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001438 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001439 // No conversion here! We're done.
1440 return false;
1441
1442 case OR_Ambiguous:
1443 // FIXME: See C++ [over.best.ics]p10 for the handling of
1444 // ambiguous conversion sequences.
1445 return false;
1446 }
1447
1448 return false;
1449}
1450
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001451/// CompareImplicitConversionSequences - Compare two implicit
1452/// conversion sequences to determine whether one is better than the
1453/// other or if they are indistinguishable (C++ 13.3.3.2).
1454ImplicitConversionSequence::CompareKind
1455Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1456 const ImplicitConversionSequence& ICS2)
1457{
1458 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1459 // conversion sequences (as defined in 13.3.3.1)
1460 // -- a standard conversion sequence (13.3.3.1.1) is a better
1461 // conversion sequence than a user-defined conversion sequence or
1462 // an ellipsis conversion sequence, and
1463 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1464 // conversion sequence than an ellipsis conversion sequence
1465 // (13.3.3.1.3).
1466 //
1467 if (ICS1.ConversionKind < ICS2.ConversionKind)
1468 return ImplicitConversionSequence::Better;
1469 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1470 return ImplicitConversionSequence::Worse;
1471
1472 // Two implicit conversion sequences of the same form are
1473 // indistinguishable conversion sequences unless one of the
1474 // following rules apply: (C++ 13.3.3.2p3):
1475 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1476 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1477 else if (ICS1.ConversionKind ==
1478 ImplicitConversionSequence::UserDefinedConversion) {
1479 // User-defined conversion sequence U1 is a better conversion
1480 // sequence than another user-defined conversion sequence U2 if
1481 // they contain the same user-defined conversion function or
1482 // constructor and if the second standard conversion sequence of
1483 // U1 is better than the second standard conversion sequence of
1484 // U2 (C++ 13.3.3.2p3).
1485 if (ICS1.UserDefined.ConversionFunction ==
1486 ICS2.UserDefined.ConversionFunction)
1487 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1488 ICS2.UserDefined.After);
1489 }
1490
1491 return ImplicitConversionSequence::Indistinguishable;
1492}
1493
1494/// CompareStandardConversionSequences - Compare two standard
1495/// conversion sequences to determine whether one is better than the
1496/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1497ImplicitConversionSequence::CompareKind
1498Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1499 const StandardConversionSequence& SCS2)
1500{
1501 // Standard conversion sequence S1 is a better conversion sequence
1502 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1503
1504 // -- S1 is a proper subsequence of S2 (comparing the conversion
1505 // sequences in the canonical form defined by 13.3.3.1.1,
1506 // excluding any Lvalue Transformation; the identity conversion
1507 // sequence is considered to be a subsequence of any
1508 // non-identity conversion sequence) or, if not that,
1509 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1510 // Neither is a proper subsequence of the other. Do nothing.
1511 ;
1512 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1513 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1514 (SCS1.Second == ICK_Identity &&
1515 SCS1.Third == ICK_Identity))
1516 // SCS1 is a proper subsequence of SCS2.
1517 return ImplicitConversionSequence::Better;
1518 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1519 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1520 (SCS2.Second == ICK_Identity &&
1521 SCS2.Third == ICK_Identity))
1522 // SCS2 is a proper subsequence of SCS1.
1523 return ImplicitConversionSequence::Worse;
1524
1525 // -- the rank of S1 is better than the rank of S2 (by the rules
1526 // defined below), or, if not that,
1527 ImplicitConversionRank Rank1 = SCS1.getRank();
1528 ImplicitConversionRank Rank2 = SCS2.getRank();
1529 if (Rank1 < Rank2)
1530 return ImplicitConversionSequence::Better;
1531 else if (Rank2 < Rank1)
1532 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001533
Douglas Gregor57373262008-10-22 14:17:15 +00001534 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1535 // are indistinguishable unless one of the following rules
1536 // applies:
1537
1538 // A conversion that is not a conversion of a pointer, or
1539 // pointer to member, to bool is better than another conversion
1540 // that is such a conversion.
1541 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1542 return SCS2.isPointerConversionToBool()
1543 ? ImplicitConversionSequence::Better
1544 : ImplicitConversionSequence::Worse;
1545
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001546 // C++ [over.ics.rank]p4b2:
1547 //
1548 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001549 // conversion of B* to A* is better than conversion of B* to
1550 // void*, and conversion of A* to void* is better than conversion
1551 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001552 bool SCS1ConvertsToVoid
1553 = SCS1.isPointerConversionToVoidPointer(Context);
1554 bool SCS2ConvertsToVoid
1555 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001556 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1557 // Exactly one of the conversion sequences is a conversion to
1558 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001559 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1560 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001561 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1562 // Neither conversion sequence converts to a void pointer; compare
1563 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001564 if (ImplicitConversionSequence::CompareKind DerivedCK
1565 = CompareDerivedToBaseConversions(SCS1, SCS2))
1566 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001567 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1568 // Both conversion sequences are conversions to void
1569 // pointers. Compare the source types to determine if there's an
1570 // inheritance relationship in their sources.
1571 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1572 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1573
1574 // Adjust the types we're converting from via the array-to-pointer
1575 // conversion, if we need to.
1576 if (SCS1.First == ICK_Array_To_Pointer)
1577 FromType1 = Context.getArrayDecayedType(FromType1);
1578 if (SCS2.First == ICK_Array_To_Pointer)
1579 FromType2 = Context.getArrayDecayedType(FromType2);
1580
1581 QualType FromPointee1
Ted Kremenek35366a62009-07-17 17:50:17 +00001582 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001583 QualType FromPointee2
Ted Kremenek35366a62009-07-17 17:50:17 +00001584 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001585
1586 if (IsDerivedFrom(FromPointee2, FromPointee1))
1587 return ImplicitConversionSequence::Better;
1588 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1589 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001590
1591 // Objective-C++: If one interface is more specific than the
1592 // other, it is the better one.
1593 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1594 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1595 if (FromIface1 && FromIface1) {
1596 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1597 return ImplicitConversionSequence::Better;
1598 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1599 return ImplicitConversionSequence::Worse;
1600 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001601 }
Douglas Gregor57373262008-10-22 14:17:15 +00001602
1603 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1604 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001605 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001606 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001607 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001608
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001609 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001610 // C++0x [over.ics.rank]p3b4:
1611 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1612 // implicit object parameter of a non-static member function declared
1613 // without a ref-qualifier, and S1 binds an rvalue reference to an
1614 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001615 // FIXME: We don't know if we're dealing with the implicit object parameter,
1616 // or if the member function in this case has a ref qualifier.
1617 // (Of course, we don't have ref qualifiers yet.)
1618 if (SCS1.RRefBinding != SCS2.RRefBinding)
1619 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1620 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001621
1622 // C++ [over.ics.rank]p3b4:
1623 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1624 // which the references refer are the same type except for
1625 // top-level cv-qualifiers, and the type to which the reference
1626 // initialized by S2 refers is more cv-qualified than the type
1627 // to which the reference initialized by S1 refers.
Sebastian Redla9845802009-03-29 15:27:50 +00001628 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1629 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001630 T1 = Context.getCanonicalType(T1);
1631 T2 = Context.getCanonicalType(T2);
1632 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1633 if (T2.isMoreQualifiedThan(T1))
1634 return ImplicitConversionSequence::Better;
1635 else if (T1.isMoreQualifiedThan(T2))
1636 return ImplicitConversionSequence::Worse;
1637 }
1638 }
Douglas Gregor57373262008-10-22 14:17:15 +00001639
1640 return ImplicitConversionSequence::Indistinguishable;
1641}
1642
1643/// CompareQualificationConversions - Compares two standard conversion
1644/// sequences to determine whether they can be ranked based on their
1645/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1646ImplicitConversionSequence::CompareKind
1647Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1648 const StandardConversionSequence& SCS2)
1649{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001650 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001651 // -- S1 and S2 differ only in their qualification conversion and
1652 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1653 // cv-qualification signature of type T1 is a proper subset of
1654 // the cv-qualification signature of type T2, and S1 is not the
1655 // deprecated string literal array-to-pointer conversion (4.2).
1656 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1657 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1658 return ImplicitConversionSequence::Indistinguishable;
1659
1660 // FIXME: the example in the standard doesn't use a qualification
1661 // conversion (!)
1662 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1663 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1664 T1 = Context.getCanonicalType(T1);
1665 T2 = Context.getCanonicalType(T2);
1666
1667 // If the types are the same, we won't learn anything by unwrapped
1668 // them.
1669 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1670 return ImplicitConversionSequence::Indistinguishable;
1671
1672 ImplicitConversionSequence::CompareKind Result
1673 = ImplicitConversionSequence::Indistinguishable;
1674 while (UnwrapSimilarPointerTypes(T1, T2)) {
1675 // Within each iteration of the loop, we check the qualifiers to
1676 // determine if this still looks like a qualification
1677 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001678 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001679 // until there are no more pointers or pointers-to-members left
1680 // to unwrap. This essentially mimics what
1681 // IsQualificationConversion does, but here we're checking for a
1682 // strict subset of qualifiers.
1683 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1684 // The qualifiers are the same, so this doesn't tell us anything
1685 // about how the sequences rank.
1686 ;
1687 else if (T2.isMoreQualifiedThan(T1)) {
1688 // T1 has fewer qualifiers, so it could be the better sequence.
1689 if (Result == ImplicitConversionSequence::Worse)
1690 // Neither has qualifiers that are a subset of the other's
1691 // qualifiers.
1692 return ImplicitConversionSequence::Indistinguishable;
1693
1694 Result = ImplicitConversionSequence::Better;
1695 } else if (T1.isMoreQualifiedThan(T2)) {
1696 // T2 has fewer qualifiers, so it could be the better sequence.
1697 if (Result == ImplicitConversionSequence::Better)
1698 // Neither has qualifiers that are a subset of the other's
1699 // qualifiers.
1700 return ImplicitConversionSequence::Indistinguishable;
1701
1702 Result = ImplicitConversionSequence::Worse;
1703 } else {
1704 // Qualifiers are disjoint.
1705 return ImplicitConversionSequence::Indistinguishable;
1706 }
1707
1708 // If the types after this point are equivalent, we're done.
1709 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1710 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001711 }
1712
Douglas Gregor57373262008-10-22 14:17:15 +00001713 // Check that the winning standard conversion sequence isn't using
1714 // the deprecated string literal array to pointer conversion.
1715 switch (Result) {
1716 case ImplicitConversionSequence::Better:
1717 if (SCS1.Deprecated)
1718 Result = ImplicitConversionSequence::Indistinguishable;
1719 break;
1720
1721 case ImplicitConversionSequence::Indistinguishable:
1722 break;
1723
1724 case ImplicitConversionSequence::Worse:
1725 if (SCS2.Deprecated)
1726 Result = ImplicitConversionSequence::Indistinguishable;
1727 break;
1728 }
1729
1730 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001731}
1732
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001733/// CompareDerivedToBaseConversions - Compares two standard conversion
1734/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001735/// various kinds of derived-to-base conversions (C++
1736/// [over.ics.rank]p4b3). As part of these checks, we also look at
1737/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001738ImplicitConversionSequence::CompareKind
1739Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1740 const StandardConversionSequence& SCS2) {
1741 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1742 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1743 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1744 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1745
1746 // Adjust the types we're converting from via the array-to-pointer
1747 // conversion, if we need to.
1748 if (SCS1.First == ICK_Array_To_Pointer)
1749 FromType1 = Context.getArrayDecayedType(FromType1);
1750 if (SCS2.First == ICK_Array_To_Pointer)
1751 FromType2 = Context.getArrayDecayedType(FromType2);
1752
1753 // Canonicalize all of the types.
1754 FromType1 = Context.getCanonicalType(FromType1);
1755 ToType1 = Context.getCanonicalType(ToType1);
1756 FromType2 = Context.getCanonicalType(FromType2);
1757 ToType2 = Context.getCanonicalType(ToType2);
1758
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001759 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001760 //
1761 // If class B is derived directly or indirectly from class A and
1762 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001763 //
1764 // For Objective-C, we let A, B, and C also be Objective-C
1765 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001766
1767 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001768 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001769 SCS2.Second == ICK_Pointer_Conversion &&
1770 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1771 FromType1->isPointerType() && FromType2->isPointerType() &&
1772 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001773 QualType FromPointee1
Ted Kremenek35366a62009-07-17 17:50:17 +00001774 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001775 QualType ToPointee1
Ted Kremenek35366a62009-07-17 17:50:17 +00001776 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001777 QualType FromPointee2
Ted Kremenek35366a62009-07-17 17:50:17 +00001778 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001779 QualType ToPointee2
Ted Kremenek35366a62009-07-17 17:50:17 +00001780 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001781
1782 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1783 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1784 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1785 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1786
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001787 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001788 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1789 if (IsDerivedFrom(ToPointee1, ToPointee2))
1790 return ImplicitConversionSequence::Better;
1791 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1792 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001793
1794 if (ToIface1 && ToIface2) {
1795 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1796 return ImplicitConversionSequence::Better;
1797 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1798 return ImplicitConversionSequence::Worse;
1799 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001800 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001801
1802 // -- conversion of B* to A* is better than conversion of C* to A*,
1803 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1804 if (IsDerivedFrom(FromPointee2, FromPointee1))
1805 return ImplicitConversionSequence::Better;
1806 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1807 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001808
1809 if (FromIface1 && FromIface2) {
1810 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1811 return ImplicitConversionSequence::Better;
1812 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1813 return ImplicitConversionSequence::Worse;
1814 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001815 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001816 }
1817
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001818 // Compare based on reference bindings.
1819 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1820 SCS1.Second == ICK_Derived_To_Base) {
1821 // -- binding of an expression of type C to a reference of type
1822 // B& is better than binding an expression of type C to a
1823 // reference of type A&,
1824 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1825 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1826 if (IsDerivedFrom(ToType1, ToType2))
1827 return ImplicitConversionSequence::Better;
1828 else if (IsDerivedFrom(ToType2, ToType1))
1829 return ImplicitConversionSequence::Worse;
1830 }
1831
Douglas Gregor225c41e2008-11-03 19:09:14 +00001832 // -- binding of an expression of type B to a reference of type
1833 // A& is better than binding an expression of type C to a
1834 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001835 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1836 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1837 if (IsDerivedFrom(FromType2, FromType1))
1838 return ImplicitConversionSequence::Better;
1839 else if (IsDerivedFrom(FromType1, FromType2))
1840 return ImplicitConversionSequence::Worse;
1841 }
1842 }
1843
1844
1845 // FIXME: conversion of A::* to B::* is better than conversion of
1846 // A::* to C::*,
1847
1848 // FIXME: conversion of B::* to C::* is better than conversion of
1849 // A::* to C::*, and
1850
Douglas Gregor225c41e2008-11-03 19:09:14 +00001851 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1852 SCS1.Second == ICK_Derived_To_Base) {
1853 // -- conversion of C to B is better than conversion of C to A,
1854 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1855 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1856 if (IsDerivedFrom(ToType1, ToType2))
1857 return ImplicitConversionSequence::Better;
1858 else if (IsDerivedFrom(ToType2, ToType1))
1859 return ImplicitConversionSequence::Worse;
1860 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001861
Douglas Gregor225c41e2008-11-03 19:09:14 +00001862 // -- conversion of B to A is better than conversion of C to A.
1863 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1864 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1865 if (IsDerivedFrom(FromType2, FromType1))
1866 return ImplicitConversionSequence::Better;
1867 else if (IsDerivedFrom(FromType1, FromType2))
1868 return ImplicitConversionSequence::Worse;
1869 }
1870 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001871
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001872 return ImplicitConversionSequence::Indistinguishable;
1873}
1874
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001875/// TryCopyInitialization - Try to copy-initialize a value of type
1876/// ToType from the expression From. Return the implicit conversion
1877/// sequence required to pass this argument, which may be a bad
1878/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001879/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00001880/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1881/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001882ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001883Sema::TryCopyInitialization(Expr *From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001884 bool SuppressUserConversions, bool ForceRValue) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001885 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001886 ImplicitConversionSequence ICS;
Sebastian Redle2b68332009-04-12 17:16:29 +00001887 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions,
1888 /*AllowExplicit=*/false, ForceRValue);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001889 return ICS;
1890 } else {
Sebastian Redle2b68332009-04-12 17:16:29 +00001891 return TryImplicitConversion(From, ToType, SuppressUserConversions,
1892 ForceRValue);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001893 }
1894}
1895
Sebastian Redle2b68332009-04-12 17:16:29 +00001896/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1897/// the expression @p From. Returns true (and emits a diagnostic) if there was
1898/// an error, returns false if the initialization succeeded. Elidable should
1899/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1900/// differently in C++0x for this case.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001901bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001902 const char* Flavor, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001903 if (!getLangOptions().CPlusPlus) {
1904 // In C, argument passing is the same as performing an assignment.
1905 QualType FromType = From->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00001906
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001907 AssignConvertType ConvTy =
1908 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00001909 if (ConvTy != Compatible &&
1910 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1911 ConvTy = Compatible;
1912
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001913 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1914 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001915 }
Sebastian Redle2b68332009-04-12 17:16:29 +00001916
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001917 if (ToType->isReferenceType())
1918 return CheckReferenceInit(From, ToType);
1919
Sebastian Redle2b68332009-04-12 17:16:29 +00001920 if (!PerformImplicitConversion(From, ToType, Flavor,
1921 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001922 return false;
Sebastian Redle2b68332009-04-12 17:16:29 +00001923
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001924 return Diag(From->getSourceRange().getBegin(),
1925 diag::err_typecheck_convert_incompatible)
1926 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001927}
1928
Douglas Gregor96176b32008-11-18 23:14:02 +00001929/// TryObjectArgumentInitialization - Try to initialize the object
1930/// parameter of the given member function (@c Method) from the
1931/// expression @p From.
1932ImplicitConversionSequence
1933Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1934 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1935 unsigned MethodQuals = Method->getTypeQualifiers();
1936 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1937
1938 // Set up the conversion sequence as a "bad" conversion, to allow us
1939 // to exit early.
1940 ImplicitConversionSequence ICS;
1941 ICS.Standard.setAsIdentityConversion();
1942 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1943
1944 // We need to have an object of class type.
1945 QualType FromType = From->getType();
Ted Kremenek35366a62009-07-17 17:50:17 +00001946 if (const PointerType *PT = FromType->getAsPointerType())
Anders Carlssona552f7c2009-05-01 18:34:30 +00001947 FromType = PT->getPointeeType();
1948
1949 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00001950
1951 // The implicit object parmeter is has the type "reference to cv X",
1952 // where X is the class of which the function is a member
1953 // (C++ [over.match.funcs]p4). However, when finding an implicit
1954 // conversion sequence for the argument, we are not allowed to
1955 // create temporaries or perform user-defined conversions
1956 // (C++ [over.match.funcs]p5). We perform a simplified version of
1957 // reference binding here, that allows class rvalues to bind to
1958 // non-constant references.
1959
1960 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1961 // with the implicit object parameter (C++ [over.match.funcs]p5).
1962 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1963 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1964 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1965 return ICS;
1966
1967 // Check that we have either the same type or a derived type. It
1968 // affects the conversion rank.
1969 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1970 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1971 ICS.Standard.Second = ICK_Identity;
1972 else if (IsDerivedFrom(FromType, ClassType))
1973 ICS.Standard.Second = ICK_Derived_To_Base;
1974 else
1975 return ICS;
1976
1977 // Success. Mark this as a reference binding.
1978 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1979 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1980 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1981 ICS.Standard.ReferenceBinding = true;
1982 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00001983 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001984 return ICS;
1985}
1986
1987/// PerformObjectArgumentInitialization - Perform initialization of
1988/// the implicit object parameter for the given Method with the given
1989/// expression.
1990bool
1991Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00001992 QualType FromRecordType, DestType;
1993 QualType ImplicitParamRecordType =
Ted Kremenek35366a62009-07-17 17:50:17 +00001994 Method->getThisType(Context)->getAsPointerType()->getPointeeType();
Anders Carlssona552f7c2009-05-01 18:34:30 +00001995
Ted Kremenek35366a62009-07-17 17:50:17 +00001996 if (const PointerType *PT = From->getType()->getAsPointerType()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00001997 FromRecordType = PT->getPointeeType();
1998 DestType = Method->getThisType(Context);
1999 } else {
2000 FromRecordType = From->getType();
2001 DestType = ImplicitParamRecordType;
2002 }
2003
Douglas Gregor96176b32008-11-18 23:14:02 +00002004 ImplicitConversionSequence ICS
2005 = TryObjectArgumentInitialization(From, Method);
2006 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2007 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002008 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002009 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2010
Douglas Gregor96176b32008-11-18 23:14:02 +00002011 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssona552f7c2009-05-01 18:34:30 +00002012 CheckDerivedToBaseConversion(FromRecordType,
2013 ImplicitParamRecordType,
Douglas Gregor96176b32008-11-18 23:14:02 +00002014 From->getSourceRange().getBegin(),
2015 From->getSourceRange()))
2016 return true;
2017
Anders Carlssona552f7c2009-05-01 18:34:30 +00002018 ImpCastExprToType(From, DestType, /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002019 return false;
2020}
2021
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002022/// TryContextuallyConvertToBool - Attempt to contextually convert the
2023/// expression From to bool (C++0x [conv]p3).
2024ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2025 return TryImplicitConversion(From, Context.BoolTy, false, true);
2026}
2027
2028/// PerformContextuallyConvertToBool - Perform a contextual conversion
2029/// of the expression From to bool (C++0x [conv]p3).
2030bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2031 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2032 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2033 return false;
2034
2035 return Diag(From->getSourceRange().getBegin(),
2036 diag::err_typecheck_bool_condition)
2037 << From->getType() << From->getSourceRange();
2038}
2039
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002040/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002041/// candidate functions, using the given function call arguments. If
2042/// @p SuppressUserConversions, then don't allow user-defined
2043/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002044/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2045/// hacky way to implement the overloading rules for elidable copy
2046/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002047void
2048Sema::AddOverloadCandidate(FunctionDecl *Function,
2049 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002050 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002051 bool SuppressUserConversions,
2052 bool ForceRValue)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002053{
Douglas Gregor72564e72009-02-26 23:50:07 +00002054 const FunctionProtoType* Proto
2055 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002056 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002057 assert(!isa<CXXConversionDecl>(Function) &&
2058 "Use AddConversionCandidate for conversion functions");
Douglas Gregore53060f2009-06-25 22:08:12 +00002059 assert(!Function->getDescribedFunctionTemplate() &&
2060 "Use AddTemplateOverloadCandidate for function templates");
2061
Douglas Gregor88a35142008-12-22 05:46:06 +00002062 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002063 if (!isa<CXXConstructorDecl>(Method)) {
2064 // If we get here, it's because we're calling a member function
2065 // that is named without a member access expression (e.g.,
2066 // "this->f") that was either written explicitly or created
2067 // implicitly. This can happen with a qualified call to a member
2068 // function, e.g., X::f(). We use a NULL object as the implied
2069 // object argument (C++ [over.call.func]p3).
2070 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2071 SuppressUserConversions, ForceRValue);
2072 return;
2073 }
2074 // We treat a constructor like a non-member function, since its object
2075 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002076 }
2077
2078
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002079 // Add this candidate
2080 CandidateSet.push_back(OverloadCandidate());
2081 OverloadCandidate& Candidate = CandidateSet.back();
2082 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002083 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002084 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002085 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002086
2087 unsigned NumArgsInProto = Proto->getNumArgs();
2088
2089 // (C++ 13.3.2p2): A candidate function having fewer than m
2090 // parameters is viable only if it has an ellipsis in its parameter
2091 // list (8.3.5).
2092 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2093 Candidate.Viable = false;
2094 return;
2095 }
2096
2097 // (C++ 13.3.2p2): A candidate function having more than m parameters
2098 // is viable only if the (m+1)st parameter has a default argument
2099 // (8.3.6). For the purposes of overload resolution, the
2100 // parameter list is truncated on the right, so that there are
2101 // exactly m parameters.
2102 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2103 if (NumArgs < MinRequiredArgs) {
2104 // Not enough arguments.
2105 Candidate.Viable = false;
2106 return;
2107 }
2108
2109 // Determine the implicit conversion sequences for each of the
2110 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002111 Candidate.Conversions.resize(NumArgs);
2112 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2113 if (ArgIdx < NumArgsInProto) {
2114 // (C++ 13.3.2p3): for F to be a viable function, there shall
2115 // exist for each argument an implicit conversion sequence
2116 // (13.3.3.1) that converts that argument to the corresponding
2117 // parameter of F.
2118 QualType ParamType = Proto->getArgType(ArgIdx);
2119 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00002120 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redle2b68332009-04-12 17:16:29 +00002121 SuppressUserConversions, ForceRValue);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002122 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002123 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002124 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002125 break;
2126 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002127 } else {
2128 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2129 // argument for which there is no corresponding parameter is
2130 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2131 Candidate.Conversions[ArgIdx].ConversionKind
2132 = ImplicitConversionSequence::EllipsisConversion;
2133 }
2134 }
2135}
2136
Douglas Gregor063daf62009-03-13 18:40:31 +00002137/// \brief Add all of the function declarations in the given function set to
2138/// the overload canddiate set.
2139void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2140 Expr **Args, unsigned NumArgs,
2141 OverloadCandidateSet& CandidateSet,
2142 bool SuppressUserConversions) {
2143 for (FunctionSet::const_iterator F = Functions.begin(),
2144 FEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00002145 F != FEnd; ++F) {
2146 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
2147 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2148 SuppressUserConversions);
2149 else
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002150 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2151 /*FIXME: explicit args */false, 0, 0,
2152 Args, NumArgs, CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002153 SuppressUserConversions);
2154 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002155}
2156
Douglas Gregor96176b32008-11-18 23:14:02 +00002157/// AddMethodCandidate - Adds the given C++ member function to the set
2158/// of candidate functions, using the given function call arguments
2159/// and the object argument (@c Object). For example, in a call
2160/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2161/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2162/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002163/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2164/// a slightly hacky way to implement the overloading rules for elidable copy
2165/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor96176b32008-11-18 23:14:02 +00002166void
2167Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2168 Expr **Args, unsigned NumArgs,
2169 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002170 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor96176b32008-11-18 23:14:02 +00002171{
Douglas Gregor72564e72009-02-26 23:50:07 +00002172 const FunctionProtoType* Proto
2173 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002174 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002175 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor96176b32008-11-18 23:14:02 +00002176 "Use AddConversionCandidate for conversion functions");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002177 assert(!isa<CXXConstructorDecl>(Method) &&
2178 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002179
2180 // Add this candidate
2181 CandidateSet.push_back(OverloadCandidate());
2182 OverloadCandidate& Candidate = CandidateSet.back();
2183 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002184 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002185 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002186
2187 unsigned NumArgsInProto = Proto->getNumArgs();
2188
2189 // (C++ 13.3.2p2): A candidate function having fewer than m
2190 // parameters is viable only if it has an ellipsis in its parameter
2191 // list (8.3.5).
2192 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2193 Candidate.Viable = false;
2194 return;
2195 }
2196
2197 // (C++ 13.3.2p2): A candidate function having more than m parameters
2198 // is viable only if the (m+1)st parameter has a default argument
2199 // (8.3.6). For the purposes of overload resolution, the
2200 // parameter list is truncated on the right, so that there are
2201 // exactly m parameters.
2202 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2203 if (NumArgs < MinRequiredArgs) {
2204 // Not enough arguments.
2205 Candidate.Viable = false;
2206 return;
2207 }
2208
2209 Candidate.Viable = true;
2210 Candidate.Conversions.resize(NumArgs + 1);
2211
Douglas Gregor88a35142008-12-22 05:46:06 +00002212 if (Method->isStatic() || !Object)
2213 // The implicit object argument is ignored.
2214 Candidate.IgnoreObjectArgument = true;
2215 else {
2216 // Determine the implicit conversion sequence for the object
2217 // parameter.
2218 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2219 if (Candidate.Conversions[0].ConversionKind
2220 == ImplicitConversionSequence::BadConversion) {
2221 Candidate.Viable = false;
2222 return;
2223 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002224 }
2225
2226 // Determine the implicit conversion sequences for each of the
2227 // arguments.
2228 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2229 if (ArgIdx < NumArgsInProto) {
2230 // (C++ 13.3.2p3): for F to be a viable function, there shall
2231 // exist for each argument an implicit conversion sequence
2232 // (13.3.3.1) that converts that argument to the corresponding
2233 // parameter of F.
2234 QualType ParamType = Proto->getArgType(ArgIdx);
2235 Candidate.Conversions[ArgIdx + 1]
2236 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redle2b68332009-04-12 17:16:29 +00002237 SuppressUserConversions, ForceRValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00002238 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2239 == ImplicitConversionSequence::BadConversion) {
2240 Candidate.Viable = false;
2241 break;
2242 }
2243 } else {
2244 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2245 // argument for which there is no corresponding parameter is
2246 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2247 Candidate.Conversions[ArgIdx + 1].ConversionKind
2248 = ImplicitConversionSequence::EllipsisConversion;
2249 }
2250 }
2251}
2252
Douglas Gregore53060f2009-06-25 22:08:12 +00002253/// \brief Add a C++ function template as a candidate in the candidate set,
2254/// using template argument deduction to produce an appropriate function
2255/// template specialization.
2256void
2257Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002258 bool HasExplicitTemplateArgs,
2259 const TemplateArgument *ExplicitTemplateArgs,
2260 unsigned NumExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002261 Expr **Args, unsigned NumArgs,
2262 OverloadCandidateSet& CandidateSet,
2263 bool SuppressUserConversions,
2264 bool ForceRValue) {
2265 // C++ [over.match.funcs]p7:
2266 // In each case where a candidate is a function template, candidate
2267 // function template specializations are generated using template argument
2268 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2269 // candidate functions in the usual way.113) A given name can refer to one
2270 // or more function templates and also to a set of overloaded non-template
2271 // functions. In such a case, the candidate functions generated from each
2272 // function template are combined with the set of non-template candidate
2273 // functions.
2274 TemplateDeductionInfo Info(Context);
2275 FunctionDecl *Specialization = 0;
2276 if (TemplateDeductionResult Result
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002277 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2278 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2279 Args, NumArgs, Specialization, Info)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002280 // FIXME: Record what happened with template argument deduction, so
2281 // that we can give the user a beautiful diagnostic.
2282 (void)Result;
2283 return;
2284 }
2285
2286 // Add the function template specialization produced by template argument
2287 // deduction as a candidate.
2288 assert(Specialization && "Missing function template specialization?");
2289 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2290 SuppressUserConversions, ForceRValue);
2291}
2292
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002293/// AddConversionCandidate - Add a C++ conversion function as a
2294/// candidate in the candidate set (C++ [over.match.conv],
2295/// C++ [over.match.copy]). From is the expression we're converting from,
2296/// and ToType is the type that we're eventually trying to convert to
2297/// (which may or may not be the same type as the type that the
2298/// conversion function produces).
2299void
2300Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2301 Expr *From, QualType ToType,
2302 OverloadCandidateSet& CandidateSet) {
2303 // Add this candidate
2304 CandidateSet.push_back(OverloadCandidate());
2305 OverloadCandidate& Candidate = CandidateSet.back();
2306 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002307 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002308 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002309 Candidate.FinalConversion.setAsIdentityConversion();
2310 Candidate.FinalConversion.FromTypePtr
2311 = Conversion->getConversionType().getAsOpaquePtr();
2312 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2313
Douglas Gregor96176b32008-11-18 23:14:02 +00002314 // Determine the implicit conversion sequence for the implicit
2315 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002316 Candidate.Viable = true;
2317 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00002318 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002319
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002320 if (Candidate.Conversions[0].ConversionKind
2321 == ImplicitConversionSequence::BadConversion) {
2322 Candidate.Viable = false;
2323 return;
2324 }
2325
2326 // To determine what the conversion from the result of calling the
2327 // conversion function to the type we're eventually trying to
2328 // convert to (ToType), we need to synthesize a call to the
2329 // conversion function and attempt copy initialization from it. This
2330 // makes sure that we get the right semantics with respect to
2331 // lvalues/rvalues and the type. Fortunately, we can allocate this
2332 // call on the stack and we don't need its arguments to be
2333 // well-formed.
2334 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2335 SourceLocation());
2336 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002337 &ConversionRef, false);
Ted Kremenek668bf912009-02-09 20:51:47 +00002338
2339 // Note that it is safe to allocate CallExpr on the stack here because
2340 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2341 // allocator).
2342 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002343 Conversion->getConversionType().getNonReferenceType(),
2344 SourceLocation());
2345 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2346 switch (ICS.ConversionKind) {
2347 case ImplicitConversionSequence::StandardConversion:
2348 Candidate.FinalConversion = ICS.Standard;
2349 break;
2350
2351 case ImplicitConversionSequence::BadConversion:
2352 Candidate.Viable = false;
2353 break;
2354
2355 default:
2356 assert(false &&
2357 "Can only end up with a standard conversion sequence or failure");
2358 }
2359}
2360
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002361/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2362/// converts the given @c Object to a function pointer via the
2363/// conversion function @c Conversion, and then attempts to call it
2364/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2365/// the type of function that we'll eventually be calling.
2366void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor72564e72009-02-26 23:50:07 +00002367 const FunctionProtoType *Proto,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002368 Expr *Object, Expr **Args, unsigned NumArgs,
2369 OverloadCandidateSet& CandidateSet) {
2370 CandidateSet.push_back(OverloadCandidate());
2371 OverloadCandidate& Candidate = CandidateSet.back();
2372 Candidate.Function = 0;
2373 Candidate.Surrogate = Conversion;
2374 Candidate.Viable = true;
2375 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002376 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002377 Candidate.Conversions.resize(NumArgs + 1);
2378
2379 // Determine the implicit conversion sequence for the implicit
2380 // object parameter.
2381 ImplicitConversionSequence ObjectInit
2382 = TryObjectArgumentInitialization(Object, Conversion);
2383 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2384 Candidate.Viable = false;
2385 return;
2386 }
2387
2388 // The first conversion is actually a user-defined conversion whose
2389 // first conversion is ObjectInit's standard conversion (which is
2390 // effectively a reference binding). Record it as such.
2391 Candidate.Conversions[0].ConversionKind
2392 = ImplicitConversionSequence::UserDefinedConversion;
2393 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2394 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2395 Candidate.Conversions[0].UserDefined.After
2396 = Candidate.Conversions[0].UserDefined.Before;
2397 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2398
2399 // Find the
2400 unsigned NumArgsInProto = Proto->getNumArgs();
2401
2402 // (C++ 13.3.2p2): A candidate function having fewer than m
2403 // parameters is viable only if it has an ellipsis in its parameter
2404 // list (8.3.5).
2405 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2406 Candidate.Viable = false;
2407 return;
2408 }
2409
2410 // Function types don't have any default arguments, so just check if
2411 // we have enough arguments.
2412 if (NumArgs < NumArgsInProto) {
2413 // Not enough arguments.
2414 Candidate.Viable = false;
2415 return;
2416 }
2417
2418 // Determine the implicit conversion sequences for each of the
2419 // arguments.
2420 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2421 if (ArgIdx < NumArgsInProto) {
2422 // (C++ 13.3.2p3): for F to be a viable function, there shall
2423 // exist for each argument an implicit conversion sequence
2424 // (13.3.3.1) that converts that argument to the corresponding
2425 // parameter of F.
2426 QualType ParamType = Proto->getArgType(ArgIdx);
2427 Candidate.Conversions[ArgIdx + 1]
2428 = TryCopyInitialization(Args[ArgIdx], ParamType,
2429 /*SuppressUserConversions=*/false);
2430 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2431 == ImplicitConversionSequence::BadConversion) {
2432 Candidate.Viable = false;
2433 break;
2434 }
2435 } else {
2436 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2437 // argument for which there is no corresponding parameter is
2438 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2439 Candidate.Conversions[ArgIdx + 1].ConversionKind
2440 = ImplicitConversionSequence::EllipsisConversion;
2441 }
2442 }
2443}
2444
Mike Stump390b4cc2009-05-16 07:39:55 +00002445// FIXME: This will eventually be removed, once we've migrated all of the
2446// operator overloading logic over to the scheme used by binary operators, which
2447// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002448void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002449 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002450 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002451 OverloadCandidateSet& CandidateSet,
2452 SourceRange OpRange) {
Douglas Gregor063daf62009-03-13 18:40:31 +00002453
2454 FunctionSet Functions;
2455
2456 QualType T1 = Args[0]->getType();
2457 QualType T2;
2458 if (NumArgs > 1)
2459 T2 = Args[1]->getType();
2460
2461 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002462 if (S)
2463 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00002464 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2465 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2466 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2467 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2468}
2469
2470/// \brief Add overload candidates for overloaded operators that are
2471/// member functions.
2472///
2473/// Add the overloaded operator candidates that are member functions
2474/// for the operator Op that was used in an operator expression such
2475/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2476/// CandidateSet will store the added overload candidates. (C++
2477/// [over.match.oper]).
2478void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2479 SourceLocation OpLoc,
2480 Expr **Args, unsigned NumArgs,
2481 OverloadCandidateSet& CandidateSet,
2482 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002483 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2484
2485 // C++ [over.match.oper]p3:
2486 // For a unary operator @ with an operand of a type whose
2487 // cv-unqualified version is T1, and for a binary operator @ with
2488 // a left operand of a type whose cv-unqualified version is T1 and
2489 // a right operand of a type whose cv-unqualified version is T2,
2490 // three sets of candidate functions, designated member
2491 // candidates, non-member candidates and built-in candidates, are
2492 // constructed as follows:
2493 QualType T1 = Args[0]->getType();
2494 QualType T2;
2495 if (NumArgs > 1)
2496 T2 = Args[1]->getType();
2497
2498 // -- If T1 is a class type, the set of member candidates is the
2499 // result of the qualified lookup of T1::operator@
2500 // (13.3.1.1.1); otherwise, the set of member candidates is
2501 // empty.
Douglas Gregor063daf62009-03-13 18:40:31 +00002502 // FIXME: Lookup in base classes, too!
Ted Kremenek35366a62009-07-17 17:50:17 +00002503 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002504 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002505 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002506 Oper != OperEnd; ++Oper)
2507 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2508 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor96176b32008-11-18 23:14:02 +00002509 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002510 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002511}
2512
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002513/// AddBuiltinCandidate - Add a candidate for a built-in
2514/// operator. ResultTy and ParamTys are the result and parameter types
2515/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002516/// arguments being passed to the candidate. IsAssignmentOperator
2517/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002518/// operator. NumContextualBoolArguments is the number of arguments
2519/// (at the beginning of the argument list) that will be contextually
2520/// converted to bool.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002521void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2522 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002523 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002524 bool IsAssignmentOperator,
2525 unsigned NumContextualBoolArguments) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002526 // Add this candidate
2527 CandidateSet.push_back(OverloadCandidate());
2528 OverloadCandidate& Candidate = CandidateSet.back();
2529 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002530 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002531 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002532 Candidate.BuiltinTypes.ResultTy = ResultTy;
2533 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2534 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2535
2536 // Determine the implicit conversion sequences for each of the
2537 // arguments.
2538 Candidate.Viable = true;
2539 Candidate.Conversions.resize(NumArgs);
2540 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002541 // C++ [over.match.oper]p4:
2542 // For the built-in assignment operators, conversions of the
2543 // left operand are restricted as follows:
2544 // -- no temporaries are introduced to hold the left operand, and
2545 // -- no user-defined conversions are applied to the left
2546 // operand to achieve a type match with the left-most
2547 // parameter of a built-in candidate.
2548 //
2549 // We block these conversions by turning off user-defined
2550 // conversions, since that is the only way that initialization of
2551 // a reference to a non-class type can occur from something that
2552 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002553 if (ArgIdx < NumContextualBoolArguments) {
2554 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2555 "Contextual conversion to bool requires bool type");
2556 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2557 } else {
2558 Candidate.Conversions[ArgIdx]
2559 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2560 ArgIdx == 0 && IsAssignmentOperator);
2561 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002562 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002563 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002564 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002565 break;
2566 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002567 }
2568}
2569
2570/// BuiltinCandidateTypeSet - A set of types that will be used for the
2571/// candidate operator functions for built-in operators (C++
2572/// [over.built]). The types are separated into pointer types and
2573/// enumeration types.
2574class BuiltinCandidateTypeSet {
2575 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002576 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002577
2578 /// PointerTypes - The set of pointer types that will be used in the
2579 /// built-in candidates.
2580 TypeSet PointerTypes;
2581
Sebastian Redl78eb8742009-04-19 21:53:20 +00002582 /// MemberPointerTypes - The set of member pointer types that will be
2583 /// used in the built-in candidates.
2584 TypeSet MemberPointerTypes;
2585
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002586 /// EnumerationTypes - The set of enumeration types that will be
2587 /// used in the built-in candidates.
2588 TypeSet EnumerationTypes;
2589
2590 /// Context - The AST context in which we will build the type sets.
2591 ASTContext &Context;
2592
Sebastian Redl78eb8742009-04-19 21:53:20 +00002593 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2594 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002595
2596public:
2597 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002598 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002599
2600 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2601
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002602 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2603 bool AllowExplicitConversions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002604
2605 /// pointer_begin - First pointer type found;
2606 iterator pointer_begin() { return PointerTypes.begin(); }
2607
Sebastian Redl78eb8742009-04-19 21:53:20 +00002608 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002609 iterator pointer_end() { return PointerTypes.end(); }
2610
Sebastian Redl78eb8742009-04-19 21:53:20 +00002611 /// member_pointer_begin - First member pointer type found;
2612 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2613
2614 /// member_pointer_end - Past the last member pointer type found;
2615 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2616
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002617 /// enumeration_begin - First enumeration type found;
2618 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2619
Sebastian Redl78eb8742009-04-19 21:53:20 +00002620 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002621 iterator enumeration_end() { return EnumerationTypes.end(); }
2622};
2623
Sebastian Redl78eb8742009-04-19 21:53:20 +00002624/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002625/// the set of pointer types along with any more-qualified variants of
2626/// that type. For example, if @p Ty is "int const *", this routine
2627/// will add "int const *", "int const volatile *", "int const
2628/// restrict *", and "int const volatile restrict *" to the set of
2629/// pointer types. Returns true if the add of @p Ty itself succeeded,
2630/// false otherwise.
Sebastian Redl78eb8742009-04-19 21:53:20 +00002631bool
2632BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002633 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002634 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002635 return false;
2636
Ted Kremenek35366a62009-07-17 17:50:17 +00002637 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002638 QualType PointeeTy = PointerTy->getPointeeType();
2639 // FIXME: Optimize this so that we don't keep trying to add the same types.
2640
Mike Stump390b4cc2009-05-16 07:39:55 +00002641 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2642 // pointer conversions that don't cast away constness?
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002643 if (!PointeeTy.isConstQualified())
Sebastian Redl78eb8742009-04-19 21:53:20 +00002644 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002645 (Context.getPointerType(PointeeTy.withConst()));
2646 if (!PointeeTy.isVolatileQualified())
Sebastian Redl78eb8742009-04-19 21:53:20 +00002647 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002648 (Context.getPointerType(PointeeTy.withVolatile()));
2649 if (!PointeeTy.isRestrictQualified())
Sebastian Redl78eb8742009-04-19 21:53:20 +00002650 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002651 (Context.getPointerType(PointeeTy.withRestrict()));
2652 }
2653
2654 return true;
2655}
2656
Sebastian Redl78eb8742009-04-19 21:53:20 +00002657/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2658/// to the set of pointer types along with any more-qualified variants of
2659/// that type. For example, if @p Ty is "int const *", this routine
2660/// will add "int const *", "int const volatile *", "int const
2661/// restrict *", and "int const volatile restrict *" to the set of
2662/// pointer types. Returns true if the add of @p Ty itself succeeded,
2663/// false otherwise.
2664bool
2665BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2666 QualType Ty) {
2667 // Insert this type.
2668 if (!MemberPointerTypes.insert(Ty))
2669 return false;
2670
Ted Kremenek35366a62009-07-17 17:50:17 +00002671 if (const MemberPointerType *PointerTy = Ty->getAsMemberPointerType()) {
Sebastian Redl78eb8742009-04-19 21:53:20 +00002672 QualType PointeeTy = PointerTy->getPointeeType();
2673 const Type *ClassTy = PointerTy->getClass();
2674 // FIXME: Optimize this so that we don't keep trying to add the same types.
2675
2676 if (!PointeeTy.isConstQualified())
2677 AddMemberPointerWithMoreQualifiedTypeVariants
2678 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2679 if (!PointeeTy.isVolatileQualified())
2680 AddMemberPointerWithMoreQualifiedTypeVariants
2681 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2682 if (!PointeeTy.isRestrictQualified())
2683 AddMemberPointerWithMoreQualifiedTypeVariants
2684 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2685 }
2686
2687 return true;
2688}
2689
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002690/// AddTypesConvertedFrom - Add each of the types to which the type @p
2691/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00002692/// primarily interested in pointer types and enumeration types. We also
2693/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002694/// AllowUserConversions is true if we should look at the conversion
2695/// functions of a class type, and AllowExplicitConversions if we
2696/// should also include the explicit conversion functions of a class
2697/// type.
2698void
2699BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2700 bool AllowUserConversions,
2701 bool AllowExplicitConversions) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002702 // Only deal with canonical types.
2703 Ty = Context.getCanonicalType(Ty);
2704
2705 // Look through reference types; they aren't part of the type of an
2706 // expression for the purposes of conversions.
Ted Kremenek35366a62009-07-17 17:50:17 +00002707 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002708 Ty = RefTy->getPointeeType();
2709
2710 // We don't care about qualifiers on the type.
2711 Ty = Ty.getUnqualifiedType();
2712
Ted Kremenek35366a62009-07-17 17:50:17 +00002713 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002714 QualType PointeeTy = PointerTy->getPointeeType();
2715
2716 // Insert our type, and its more-qualified variants, into the set
2717 // of types.
Sebastian Redl78eb8742009-04-19 21:53:20 +00002718 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002719 return;
2720
2721 // Add 'cv void*' to our set of types.
2722 if (!Ty->isVoidType()) {
2723 QualType QualVoid
2724 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl78eb8742009-04-19 21:53:20 +00002725 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002726 }
2727
2728 // If this is a pointer to a class type, add pointers to its bases
2729 // (with the same level of cv-qualification as the original
2730 // derived class, of course).
Ted Kremenek35366a62009-07-17 17:50:17 +00002731 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002732 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2733 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2734 Base != ClassDecl->bases_end(); ++Base) {
2735 QualType BaseTy = Context.getCanonicalType(Base->getType());
2736 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2737
2738 // Add the pointer type, recursively, so that we get all of
2739 // the indirect base classes, too.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002740 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002741 }
2742 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00002743 } else if (Ty->isMemberPointerType()) {
2744 // Member pointers are far easier, since the pointee can't be converted.
2745 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2746 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002747 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00002748 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002749 } else if (AllowUserConversions) {
Ted Kremenek35366a62009-07-17 17:50:17 +00002750 if (const RecordType *TyRec = Ty->getAsRecordType()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002751 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2752 // FIXME: Visit conversion functions in the base classes, too.
2753 OverloadedFunctionDecl *Conversions
2754 = ClassDecl->getConversionFunctions();
2755 for (OverloadedFunctionDecl::function_iterator Func
2756 = Conversions->function_begin();
2757 Func != Conversions->function_end(); ++Func) {
2758 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002759 if (AllowExplicitConversions || !Conv->isExplicit())
2760 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002761 }
2762 }
2763 }
2764}
2765
Douglas Gregor74253732008-11-19 15:42:04 +00002766/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2767/// operator overloads to the candidate set (C++ [over.built]), based
2768/// on the operator @p Op and the arguments given. For example, if the
2769/// operator is a binary '+', this routine might add "int
2770/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002771void
Douglas Gregor74253732008-11-19 15:42:04 +00002772Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2773 Expr **Args, unsigned NumArgs,
2774 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002775 // The set of "promoted arithmetic types", which are the arithmetic
2776 // types are that preserved by promotion (C++ [over.built]p2). Note
2777 // that the first few of these types are the promoted integral
2778 // types; these types need to be first.
2779 // FIXME: What about complex?
2780 const unsigned FirstIntegralType = 0;
2781 const unsigned LastIntegralType = 13;
2782 const unsigned FirstPromotedIntegralType = 7,
2783 LastPromotedIntegralType = 13;
2784 const unsigned FirstPromotedArithmeticType = 7,
2785 LastPromotedArithmeticType = 16;
2786 const unsigned NumArithmeticTypes = 16;
2787 QualType ArithmeticTypes[NumArithmeticTypes] = {
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002788 Context.BoolTy, Context.CharTy, Context.WCharTy,
2789// Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002790 Context.SignedCharTy, Context.ShortTy,
2791 Context.UnsignedCharTy, Context.UnsignedShortTy,
2792 Context.IntTy, Context.LongTy, Context.LongLongTy,
2793 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2794 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2795 };
2796
2797 // Find all of the types that the arguments can convert to, but only
2798 // if the operator we're looking at has built-in operator candidates
2799 // that make use of these types.
2800 BuiltinCandidateTypeSet CandidateTypes(Context);
2801 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2802 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002803 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002804 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002805 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002806 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00002807 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002808 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2809 true,
2810 (Op == OO_Exclaim ||
2811 Op == OO_AmpAmp ||
2812 Op == OO_PipePipe));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002813 }
2814
2815 bool isComparison = false;
2816 switch (Op) {
2817 case OO_None:
2818 case NUM_OVERLOADED_OPERATORS:
2819 assert(false && "Expected an overloaded operator");
2820 break;
2821
Douglas Gregor74253732008-11-19 15:42:04 +00002822 case OO_Star: // '*' is either unary or binary
2823 if (NumArgs == 1)
2824 goto UnaryStar;
2825 else
2826 goto BinaryStar;
2827 break;
2828
2829 case OO_Plus: // '+' is either unary or binary
2830 if (NumArgs == 1)
2831 goto UnaryPlus;
2832 else
2833 goto BinaryPlus;
2834 break;
2835
2836 case OO_Minus: // '-' is either unary or binary
2837 if (NumArgs == 1)
2838 goto UnaryMinus;
2839 else
2840 goto BinaryMinus;
2841 break;
2842
2843 case OO_Amp: // '&' is either unary or binary
2844 if (NumArgs == 1)
2845 goto UnaryAmp;
2846 else
2847 goto BinaryAmp;
2848
2849 case OO_PlusPlus:
2850 case OO_MinusMinus:
2851 // C++ [over.built]p3:
2852 //
2853 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2854 // is either volatile or empty, there exist candidate operator
2855 // functions of the form
2856 //
2857 // VQ T& operator++(VQ T&);
2858 // T operator++(VQ T&, int);
2859 //
2860 // C++ [over.built]p4:
2861 //
2862 // For every pair (T, VQ), where T is an arithmetic type other
2863 // than bool, and VQ is either volatile or empty, there exist
2864 // candidate operator functions of the form
2865 //
2866 // VQ T& operator--(VQ T&);
2867 // T operator--(VQ T&, int);
2868 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2869 Arith < NumArithmeticTypes; ++Arith) {
2870 QualType ArithTy = ArithmeticTypes[Arith];
2871 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002872 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00002873
2874 // Non-volatile version.
2875 if (NumArgs == 1)
2876 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2877 else
2878 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2879
2880 // Volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002881 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00002882 if (NumArgs == 1)
2883 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2884 else
2885 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2886 }
2887
2888 // C++ [over.built]p5:
2889 //
2890 // For every pair (T, VQ), where T is a cv-qualified or
2891 // cv-unqualified object type, and VQ is either volatile or
2892 // empty, there exist candidate operator functions of the form
2893 //
2894 // T*VQ& operator++(T*VQ&);
2895 // T*VQ& operator--(T*VQ&);
2896 // T* operator++(T*VQ&, int);
2897 // T* operator--(T*VQ&, int);
2898 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2899 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2900 // Skip pointer types that aren't pointers to object types.
Ted Kremenek35366a62009-07-17 17:50:17 +00002901 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00002902 continue;
2903
2904 QualType ParamTypes[2] = {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002905 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00002906 };
2907
2908 // Without volatile
2909 if (NumArgs == 1)
2910 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2911 else
2912 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2913
2914 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2915 // With volatile
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002916 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00002917 if (NumArgs == 1)
2918 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2919 else
2920 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2921 }
2922 }
2923 break;
2924
2925 UnaryStar:
2926 // C++ [over.built]p6:
2927 // For every cv-qualified or cv-unqualified object type T, there
2928 // exist candidate operator functions of the form
2929 //
2930 // T& operator*(T*);
2931 //
2932 // C++ [over.built]p7:
2933 // For every function type T, there exist candidate operator
2934 // functions of the form
2935 // T& operator*(T*);
2936 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2937 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2938 QualType ParamTy = *Ptr;
Ted Kremenek35366a62009-07-17 17:50:17 +00002939 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002940 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00002941 &ParamTy, Args, 1, CandidateSet);
2942 }
2943 break;
2944
2945 UnaryPlus:
2946 // C++ [over.built]p8:
2947 // For every type T, there exist candidate operator functions of
2948 // the form
2949 //
2950 // T* operator+(T*);
2951 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2952 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2953 QualType ParamTy = *Ptr;
2954 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2955 }
2956
2957 // Fall through
2958
2959 UnaryMinus:
2960 // C++ [over.built]p9:
2961 // For every promoted arithmetic type T, there exist candidate
2962 // operator functions of the form
2963 //
2964 // T operator+(T);
2965 // T operator-(T);
2966 for (unsigned Arith = FirstPromotedArithmeticType;
2967 Arith < LastPromotedArithmeticType; ++Arith) {
2968 QualType ArithTy = ArithmeticTypes[Arith];
2969 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2970 }
2971 break;
2972
2973 case OO_Tilde:
2974 // C++ [over.built]p10:
2975 // For every promoted integral type T, there exist candidate
2976 // operator functions of the form
2977 //
2978 // T operator~(T);
2979 for (unsigned Int = FirstPromotedIntegralType;
2980 Int < LastPromotedIntegralType; ++Int) {
2981 QualType IntTy = ArithmeticTypes[Int];
2982 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2983 }
2984 break;
2985
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002986 case OO_New:
2987 case OO_Delete:
2988 case OO_Array_New:
2989 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002990 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002991 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002992 break;
2993
2994 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002995 UnaryAmp:
2996 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002997 // C++ [over.match.oper]p3:
2998 // -- For the operator ',', the unary operator '&', or the
2999 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003000 break;
3001
3002 case OO_Less:
3003 case OO_Greater:
3004 case OO_LessEqual:
3005 case OO_GreaterEqual:
3006 case OO_EqualEqual:
3007 case OO_ExclaimEqual:
3008 // C++ [over.built]p15:
3009 //
3010 // For every pointer or enumeration type T, there exist
3011 // candidate operator functions of the form
3012 //
3013 // bool operator<(T, T);
3014 // bool operator>(T, T);
3015 // bool operator<=(T, T);
3016 // bool operator>=(T, T);
3017 // bool operator==(T, T);
3018 // bool operator!=(T, T);
3019 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3020 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3021 QualType ParamTypes[2] = { *Ptr, *Ptr };
3022 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3023 }
3024 for (BuiltinCandidateTypeSet::iterator Enum
3025 = CandidateTypes.enumeration_begin();
3026 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3027 QualType ParamTypes[2] = { *Enum, *Enum };
3028 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3029 }
3030
3031 // Fall through.
3032 isComparison = true;
3033
Douglas Gregor74253732008-11-19 15:42:04 +00003034 BinaryPlus:
3035 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003036 if (!isComparison) {
3037 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3038
3039 // C++ [over.built]p13:
3040 //
3041 // For every cv-qualified or cv-unqualified object type T
3042 // there exist candidate operator functions of the form
3043 //
3044 // T* operator+(T*, ptrdiff_t);
3045 // T& operator[](T*, ptrdiff_t); [BELOW]
3046 // T* operator-(T*, ptrdiff_t);
3047 // T* operator+(ptrdiff_t, T*);
3048 // T& operator[](ptrdiff_t, T*); [BELOW]
3049 //
3050 // C++ [over.built]p14:
3051 //
3052 // For every T, where T is a pointer to object type, there
3053 // exist candidate operator functions of the form
3054 //
3055 // ptrdiff_t operator-(T, T);
3056 for (BuiltinCandidateTypeSet::iterator Ptr
3057 = CandidateTypes.pointer_begin();
3058 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3059 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3060
3061 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3062 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3063
3064 if (Op == OO_Plus) {
3065 // T* operator+(ptrdiff_t, T*);
3066 ParamTypes[0] = ParamTypes[1];
3067 ParamTypes[1] = *Ptr;
3068 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3069 } else {
3070 // ptrdiff_t operator-(T, T);
3071 ParamTypes[1] = *Ptr;
3072 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3073 Args, 2, CandidateSet);
3074 }
3075 }
3076 }
3077 // Fall through
3078
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003079 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003080 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003081 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003082 // C++ [over.built]p12:
3083 //
3084 // For every pair of promoted arithmetic types L and R, there
3085 // exist candidate operator functions of the form
3086 //
3087 // LR operator*(L, R);
3088 // LR operator/(L, R);
3089 // LR operator+(L, R);
3090 // LR operator-(L, R);
3091 // bool operator<(L, R);
3092 // bool operator>(L, R);
3093 // bool operator<=(L, R);
3094 // bool operator>=(L, R);
3095 // bool operator==(L, R);
3096 // bool operator!=(L, R);
3097 //
3098 // where LR is the result of the usual arithmetic conversions
3099 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003100 //
3101 // C++ [over.built]p24:
3102 //
3103 // For every pair of promoted arithmetic types L and R, there exist
3104 // candidate operator functions of the form
3105 //
3106 // LR operator?(bool, L, R);
3107 //
3108 // where LR is the result of the usual arithmetic conversions
3109 // between types L and R.
3110 // Our candidates ignore the first parameter.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003111 for (unsigned Left = FirstPromotedArithmeticType;
3112 Left < LastPromotedArithmeticType; ++Left) {
3113 for (unsigned Right = FirstPromotedArithmeticType;
3114 Right < LastPromotedArithmeticType; ++Right) {
3115 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3116 QualType Result
3117 = isComparison? Context.BoolTy
3118 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3119 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3120 }
3121 }
3122 break;
3123
3124 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003125 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003126 case OO_Caret:
3127 case OO_Pipe:
3128 case OO_LessLess:
3129 case OO_GreaterGreater:
3130 // C++ [over.built]p17:
3131 //
3132 // For every pair of promoted integral types L and R, there
3133 // exist candidate operator functions of the form
3134 //
3135 // LR operator%(L, R);
3136 // LR operator&(L, R);
3137 // LR operator^(L, R);
3138 // LR operator|(L, R);
3139 // L operator<<(L, R);
3140 // L operator>>(L, R);
3141 //
3142 // where LR is the result of the usual arithmetic conversions
3143 // between types L and R.
3144 for (unsigned Left = FirstPromotedIntegralType;
3145 Left < LastPromotedIntegralType; ++Left) {
3146 for (unsigned Right = FirstPromotedIntegralType;
3147 Right < LastPromotedIntegralType; ++Right) {
3148 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3149 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3150 ? LandR[0]
3151 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3152 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3153 }
3154 }
3155 break;
3156
3157 case OO_Equal:
3158 // C++ [over.built]p20:
3159 //
3160 // For every pair (T, VQ), where T is an enumeration or
3161 // (FIXME:) pointer to member type and VQ is either volatile or
3162 // empty, there exist candidate operator functions of the form
3163 //
3164 // VQ T& operator=(VQ T&, T);
3165 for (BuiltinCandidateTypeSet::iterator Enum
3166 = CandidateTypes.enumeration_begin();
3167 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3168 QualType ParamTypes[2];
3169
3170 // T& operator=(T&, T)
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003171 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003172 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003173 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003174 /*IsAssignmentOperator=*/false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003175
Douglas Gregor74253732008-11-19 15:42:04 +00003176 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3177 // volatile T& operator=(volatile T&, T)
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003178 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00003179 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003180 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003181 /*IsAssignmentOperator=*/false);
Douglas Gregor74253732008-11-19 15:42:04 +00003182 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003183 }
3184 // Fall through.
3185
3186 case OO_PlusEqual:
3187 case OO_MinusEqual:
3188 // C++ [over.built]p19:
3189 //
3190 // For every pair (T, VQ), where T is any type and VQ is either
3191 // volatile or empty, there exist candidate operator functions
3192 // of the form
3193 //
3194 // T*VQ& operator=(T*VQ&, T*);
3195 //
3196 // C++ [over.built]p21:
3197 //
3198 // For every pair (T, VQ), where T is a cv-qualified or
3199 // cv-unqualified object type and VQ is either volatile or
3200 // empty, there exist candidate operator functions of the form
3201 //
3202 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3203 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3204 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3205 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3206 QualType ParamTypes[2];
3207 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3208
3209 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003210 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003211 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3212 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003213
Douglas Gregor74253732008-11-19 15:42:04 +00003214 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3215 // volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003216 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003217 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3218 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003219 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003220 }
3221 // Fall through.
3222
3223 case OO_StarEqual:
3224 case OO_SlashEqual:
3225 // C++ [over.built]p18:
3226 //
3227 // For every triple (L, VQ, R), where L is an arithmetic type,
3228 // VQ is either volatile or empty, and R is a promoted
3229 // arithmetic type, there exist candidate operator functions of
3230 // the form
3231 //
3232 // VQ L& operator=(VQ L&, R);
3233 // VQ L& operator*=(VQ L&, R);
3234 // VQ L& operator/=(VQ L&, R);
3235 // VQ L& operator+=(VQ L&, R);
3236 // VQ L& operator-=(VQ L&, R);
3237 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3238 for (unsigned Right = FirstPromotedArithmeticType;
3239 Right < LastPromotedArithmeticType; ++Right) {
3240 QualType ParamTypes[2];
3241 ParamTypes[1] = ArithmeticTypes[Right];
3242
3243 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003244 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003245 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3246 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003247
3248 // Add this built-in operator as a candidate (VQ is 'volatile').
3249 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003250 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003251 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3252 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003253 }
3254 }
3255 break;
3256
3257 case OO_PercentEqual:
3258 case OO_LessLessEqual:
3259 case OO_GreaterGreaterEqual:
3260 case OO_AmpEqual:
3261 case OO_CaretEqual:
3262 case OO_PipeEqual:
3263 // C++ [over.built]p22:
3264 //
3265 // For every triple (L, VQ, R), where L is an integral type, VQ
3266 // is either volatile or empty, and R is a promoted integral
3267 // type, there exist candidate operator functions of the form
3268 //
3269 // VQ L& operator%=(VQ L&, R);
3270 // VQ L& operator<<=(VQ L&, R);
3271 // VQ L& operator>>=(VQ L&, R);
3272 // VQ L& operator&=(VQ L&, R);
3273 // VQ L& operator^=(VQ L&, R);
3274 // VQ L& operator|=(VQ L&, R);
3275 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3276 for (unsigned Right = FirstPromotedIntegralType;
3277 Right < LastPromotedIntegralType; ++Right) {
3278 QualType ParamTypes[2];
3279 ParamTypes[1] = ArithmeticTypes[Right];
3280
3281 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003282 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003283 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3284
3285 // Add this built-in operator as a candidate (VQ is 'volatile').
3286 ParamTypes[0] = ArithmeticTypes[Left];
3287 ParamTypes[0].addVolatile();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003288 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003289 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3290 }
3291 }
3292 break;
3293
Douglas Gregor74253732008-11-19 15:42:04 +00003294 case OO_Exclaim: {
3295 // C++ [over.operator]p23:
3296 //
3297 // There also exist candidate operator functions of the form
3298 //
3299 // bool operator!(bool);
3300 // bool operator&&(bool, bool); [BELOW]
3301 // bool operator||(bool, bool); [BELOW]
3302 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003303 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3304 /*IsAssignmentOperator=*/false,
3305 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003306 break;
3307 }
3308
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003309 case OO_AmpAmp:
3310 case OO_PipePipe: {
3311 // C++ [over.operator]p23:
3312 //
3313 // There also exist candidate operator functions of the form
3314 //
Douglas Gregor74253732008-11-19 15:42:04 +00003315 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003316 // bool operator&&(bool, bool);
3317 // bool operator||(bool, bool);
3318 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003319 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3320 /*IsAssignmentOperator=*/false,
3321 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003322 break;
3323 }
3324
3325 case OO_Subscript:
3326 // C++ [over.built]p13:
3327 //
3328 // For every cv-qualified or cv-unqualified object type T there
3329 // exist candidate operator functions of the form
3330 //
3331 // T* operator+(T*, ptrdiff_t); [ABOVE]
3332 // T& operator[](T*, ptrdiff_t);
3333 // T* operator-(T*, ptrdiff_t); [ABOVE]
3334 // T* operator+(ptrdiff_t, T*); [ABOVE]
3335 // T& operator[](ptrdiff_t, T*);
3336 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3337 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3338 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek35366a62009-07-17 17:50:17 +00003339 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003340 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003341
3342 // T& operator[](T*, ptrdiff_t)
3343 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3344
3345 // T& operator[](ptrdiff_t, T*);
3346 ParamTypes[0] = ParamTypes[1];
3347 ParamTypes[1] = *Ptr;
3348 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3349 }
3350 break;
3351
3352 case OO_ArrowStar:
3353 // FIXME: No support for pointer-to-members yet.
3354 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003355
3356 case OO_Conditional:
3357 // Note that we don't consider the first argument, since it has been
3358 // contextually converted to bool long ago. The candidates below are
3359 // therefore added as binary.
3360 //
3361 // C++ [over.built]p24:
3362 // For every type T, where T is a pointer or pointer-to-member type,
3363 // there exist candidate operator functions of the form
3364 //
3365 // T operator?(bool, T, T);
3366 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003367 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3368 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3369 QualType ParamTypes[2] = { *Ptr, *Ptr };
3370 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3371 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00003372 for (BuiltinCandidateTypeSet::iterator Ptr =
3373 CandidateTypes.member_pointer_begin(),
3374 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3375 QualType ParamTypes[2] = { *Ptr, *Ptr };
3376 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3377 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003378 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003379 }
3380}
3381
Douglas Gregorfa047642009-02-04 00:32:51 +00003382/// \brief Add function candidates found via argument-dependent lookup
3383/// to the set of overloading candidates.
3384///
3385/// This routine performs argument-dependent name lookup based on the
3386/// given function name (which may also be an operator name) and adds
3387/// all of the overload candidates found by ADL to the overload
3388/// candidate set (C++ [basic.lookup.argdep]).
3389void
3390Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3391 Expr **Args, unsigned NumArgs,
3392 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003393 FunctionSet Functions;
Douglas Gregorfa047642009-02-04 00:32:51 +00003394
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003395 // Record all of the function candidates that we've already
3396 // added to the overload set, so that we don't add those same
3397 // candidates a second time.
3398 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3399 CandEnd = CandidateSet.end();
3400 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00003401 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003402 Functions.insert(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003403 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3404 Functions.insert(FunTmpl);
3405 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003406
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003407 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregorfa047642009-02-04 00:32:51 +00003408
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003409 // Erase all of the candidates we already knew about.
3410 // FIXME: This is suboptimal. Is there a better way?
3411 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3412 CandEnd = CandidateSet.end();
3413 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00003414 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003415 Functions.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003416 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3417 Functions.erase(FunTmpl);
3418 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003419
3420 // For each of the ADL candidates we found, add it to the overload
3421 // set.
3422 for (FunctionSet::iterator Func = Functions.begin(),
3423 FuncEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00003424 Func != FuncEnd; ++Func) {
3425 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3426 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3427 else
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003428 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3429 /*FIXME: explicit args */false, 0, 0,
3430 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00003431 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003432}
3433
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003434/// isBetterOverloadCandidate - Determines whether the first overload
3435/// candidate is a better candidate than the second (C++ 13.3.3p1).
3436bool
3437Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3438 const OverloadCandidate& Cand2)
3439{
3440 // Define viable functions to be better candidates than non-viable
3441 // functions.
3442 if (!Cand2.Viable)
3443 return Cand1.Viable;
3444 else if (!Cand1.Viable)
3445 return false;
3446
Douglas Gregor88a35142008-12-22 05:46:06 +00003447 // C++ [over.match.best]p1:
3448 //
3449 // -- if F is a static member function, ICS1(F) is defined such
3450 // that ICS1(F) is neither better nor worse than ICS1(G) for
3451 // any function G, and, symmetrically, ICS1(G) is neither
3452 // better nor worse than ICS1(F).
3453 unsigned StartArg = 0;
3454 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3455 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003456
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003457 // C++ [over.match.best]p1:
3458 // A viable function F1 is defined to be a better function than another
3459 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
3460 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003461 unsigned NumArgs = Cand1.Conversions.size();
3462 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3463 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003464 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003465 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3466 Cand2.Conversions[ArgIdx])) {
3467 case ImplicitConversionSequence::Better:
3468 // Cand1 has a better conversion sequence.
3469 HasBetterConversion = true;
3470 break;
3471
3472 case ImplicitConversionSequence::Worse:
3473 // Cand1 can't be better than Cand2.
3474 return false;
3475
3476 case ImplicitConversionSequence::Indistinguishable:
3477 // Do nothing.
3478 break;
3479 }
3480 }
3481
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003482 // -- for some argument j, ICSj(F1) is a better conversion sequence than
3483 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003484 if (HasBetterConversion)
3485 return true;
3486
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003487 // - F1 is a non-template function and F2 is a function template
3488 // specialization, or, if not that,
3489 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3490 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3491 return true;
3492
3493 // -- F1 and F2 are function template specializations, and the function
3494 // template for F1 is more specialized than the template for F2
3495 // according to the partial ordering rules described in 14.5.5.2, or,
3496 // if not that,
3497
3498 // FIXME: Implement partial ordering of function templates.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003499
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003500 // -- the context is an initialization by user-defined conversion
3501 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3502 // from the return type of F1 to the destination type (i.e.,
3503 // the type of the entity being initialized) is a better
3504 // conversion sequence than the standard conversion sequence
3505 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00003506 if (Cand1.Function && Cand2.Function &&
3507 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003508 isa<CXXConversionDecl>(Cand2.Function)) {
3509 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3510 Cand2.FinalConversion)) {
3511 case ImplicitConversionSequence::Better:
3512 // Cand1 has a better conversion sequence.
3513 return true;
3514
3515 case ImplicitConversionSequence::Worse:
3516 // Cand1 can't be better than Cand2.
3517 return false;
3518
3519 case ImplicitConversionSequence::Indistinguishable:
3520 // Do nothing
3521 break;
3522 }
3523 }
3524
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003525 return false;
3526}
3527
Douglas Gregore0762c92009-06-19 23:52:42 +00003528/// \brief Computes the best viable function (C++ 13.3.3)
3529/// within an overload candidate set.
3530///
3531/// \param CandidateSet the set of candidate functions.
3532///
3533/// \param Loc the location of the function name (or operator symbol) for
3534/// which overload resolution occurs.
3535///
3536/// \param Best f overload resolution was successful or found a deleted
3537/// function, Best points to the candidate function found.
3538///
3539/// \returns The result of overload resolution.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003540Sema::OverloadingResult
3541Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregore0762c92009-06-19 23:52:42 +00003542 SourceLocation Loc,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003543 OverloadCandidateSet::iterator& Best)
3544{
3545 // Find the best viable function.
3546 Best = CandidateSet.end();
3547 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3548 Cand != CandidateSet.end(); ++Cand) {
3549 if (Cand->Viable) {
3550 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3551 Best = Cand;
3552 }
3553 }
3554
3555 // If we didn't find any viable functions, abort.
3556 if (Best == CandidateSet.end())
3557 return OR_No_Viable_Function;
3558
3559 // Make sure that this function is better than every other viable
3560 // function. If not, we have an ambiguity.
3561 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3562 Cand != CandidateSet.end(); ++Cand) {
3563 if (Cand->Viable &&
3564 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003565 !isBetterOverloadCandidate(*Best, *Cand)) {
3566 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003567 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003568 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003569 }
3570
3571 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003572 if (Best->Function &&
3573 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003574 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003575 return OR_Deleted;
3576
Douglas Gregore0762c92009-06-19 23:52:42 +00003577 // C++ [basic.def.odr]p2:
3578 // An overloaded function is used if it is selected by overload resolution
3579 // when referred to from a potentially-evaluated expression. [Note: this
3580 // covers calls to named functions (5.2.2), operator overloading
3581 // (clause 13), user-defined conversions (12.3.2), allocation function for
3582 // placement new (5.3.4), as well as non-default initialization (8.5).
3583 if (Best->Function)
3584 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003585 return OR_Success;
3586}
3587
3588/// PrintOverloadCandidates - When overload resolution fails, prints
3589/// diagnostic messages containing the candidates in the candidate
3590/// set. If OnlyViable is true, only viable candidates will be printed.
3591void
3592Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3593 bool OnlyViable)
3594{
3595 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3596 LastCand = CandidateSet.end();
3597 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003598 if (Cand->Viable || !OnlyViable) {
3599 if (Cand->Function) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003600 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003601 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003602 // Deleted or "unavailable" function.
3603 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3604 << Cand->Function->isDeleted();
3605 } else {
3606 // Normal function
3607 // FIXME: Give a better reason!
3608 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3609 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003610 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003611 // Desugar the type of the surrogate down to a function type,
3612 // retaining as many typedefs as possible while still showing
3613 // the function type (and, therefore, its parameter types).
3614 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003615 bool isLValueReference = false;
3616 bool isRValueReference = false;
Douglas Gregor621b3932008-11-21 02:54:28 +00003617 bool isPointer = false;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003618 if (const LValueReferenceType *FnTypeRef =
Ted Kremenek35366a62009-07-17 17:50:17 +00003619 FnType->getAsLValueReferenceType()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003620 FnType = FnTypeRef->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003621 isLValueReference = true;
3622 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenek35366a62009-07-17 17:50:17 +00003623 FnType->getAsRValueReferenceType()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003624 FnType = FnTypeRef->getPointeeType();
3625 isRValueReference = true;
Douglas Gregor621b3932008-11-21 02:54:28 +00003626 }
Ted Kremenek35366a62009-07-17 17:50:17 +00003627 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003628 FnType = FnTypePtr->getPointeeType();
3629 isPointer = true;
3630 }
3631 // Desugar down to a function type.
3632 FnType = QualType(FnType->getAsFunctionType(), 0);
3633 // Reconstruct the pointer/reference as appropriate.
3634 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003635 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3636 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor621b3932008-11-21 02:54:28 +00003637
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003638 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003639 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003640 } else {
3641 // FIXME: We need to get the identifier in here
Mike Stump390b4cc2009-05-16 07:39:55 +00003642 // FIXME: Do we want the error message to point at the operator?
3643 // (built-ins won't have a location)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003644 QualType FnType
3645 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3646 Cand->BuiltinTypes.ParamTypes,
3647 Cand->Conversions.size(),
3648 false, 0);
3649
Chris Lattnerd1625842008-11-24 06:25:27 +00003650 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003651 }
3652 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003653 }
3654}
3655
Douglas Gregor904eed32008-11-10 20:40:00 +00003656/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3657/// an overloaded function (C++ [over.over]), where @p From is an
3658/// expression with overloaded function type and @p ToType is the type
3659/// we're trying to resolve to. For example:
3660///
3661/// @code
3662/// int f(double);
3663/// int f(int);
3664///
3665/// int (*pfd)(double) = f; // selects f(double)
3666/// @endcode
3667///
3668/// This routine returns the resulting FunctionDecl if it could be
3669/// resolved, and NULL otherwise. When @p Complain is true, this
3670/// routine will emit diagnostics if there is an error.
3671FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00003672Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003673 bool Complain) {
3674 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00003675 bool IsMember = false;
Ted Kremenek35366a62009-07-17 17:50:17 +00003676 if (const PointerType *ToTypePtr = ToType->getAsPointerType())
Douglas Gregor904eed32008-11-10 20:40:00 +00003677 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek35366a62009-07-17 17:50:17 +00003678 else if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType())
Daniel Dunbarbb710012009-02-26 19:13:44 +00003679 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00003680 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek35366a62009-07-17 17:50:17 +00003681 ToType->getAsMemberPointerType()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00003682 FunctionType = MemTypePtr->getPointeeType();
3683 IsMember = true;
3684 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003685
3686 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00003687 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00003688 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00003689 return 0;
3690
3691 // Find the actual overloaded function declaration.
3692 OverloadedFunctionDecl *Ovl = 0;
3693
3694 // C++ [over.over]p1:
3695 // [...] [Note: any redundant set of parentheses surrounding the
3696 // overloaded function name is ignored (5.1). ]
3697 Expr *OvlExpr = From->IgnoreParens();
3698
3699 // C++ [over.over]p1:
3700 // [...] The overloaded function name can be preceded by the &
3701 // operator.
3702 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3703 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3704 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3705 }
3706
3707 // Try to dig out the overloaded function.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003708 FunctionTemplateDecl *FunctionTemplate = 0;
3709 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003710 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor83314aa2009-07-08 20:55:45 +00003711 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3712 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003713
Douglas Gregor83314aa2009-07-08 20:55:45 +00003714 // If there's no overloaded function declaration or function template,
3715 // we're done.
3716 if (!Ovl && !FunctionTemplate)
Douglas Gregor904eed32008-11-10 20:40:00 +00003717 return 0;
3718
Douglas Gregor83314aa2009-07-08 20:55:45 +00003719 OverloadIterator Fun;
3720 if (Ovl)
3721 Fun = Ovl;
3722 else
3723 Fun = FunctionTemplate;
3724
Douglas Gregor904eed32008-11-10 20:40:00 +00003725 // Look through all of the overloaded functions, searching for one
3726 // whose type matches exactly.
Douglas Gregor00aeb522009-07-08 23:33:52 +00003727 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
3728
3729 bool FoundNonTemplateFunction = false;
Douglas Gregor83314aa2009-07-08 20:55:45 +00003730 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003731 // C++ [over.over]p3:
3732 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00003733 // targets of type "pointer-to-function" or "reference-to-function."
3734 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00003735 // type "pointer-to-member-function."
3736 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003737
3738 if (FunctionTemplateDecl *FunctionTemplate
3739 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Douglas Gregor00aeb522009-07-08 23:33:52 +00003740 if (CXXMethodDecl *Method
3741 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
3742 // Skip non-static function templates when converting to pointer, and
3743 // static when converting to member pointer.
3744 if (Method->isStatic() == IsMember)
3745 continue;
3746 } else if (IsMember)
3747 continue;
3748
3749 // C++ [over.over]p2:
3750 // If the name is a function template, template argument deduction is
3751 // done (14.8.2.2), and if the argument deduction succeeds, the
3752 // resulting template argument list is used to generate a single
3753 // function template specialization, which is added to the set of
3754 // overloaded functions considered.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003755 FunctionDecl *Specialization = 0;
3756 TemplateDeductionInfo Info(Context);
3757 if (TemplateDeductionResult Result
3758 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3759 /*FIXME:*/0, /*FIXME:*/0,
3760 FunctionType, Specialization, Info)) {
3761 // FIXME: make a note of the failed deduction for diagnostics.
3762 (void)Result;
3763 } else {
3764 assert(FunctionType
3765 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00003766 Matches.insert(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003767 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor83314aa2009-07-08 20:55:45 +00003768 }
3769 }
3770
Sebastian Redl33b399a2009-02-04 21:23:32 +00003771 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3772 // Skip non-static functions when converting to pointer, and static
3773 // when converting to member pointer.
3774 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00003775 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00003776 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00003777 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00003778
Douglas Gregore53060f2009-06-25 22:08:12 +00003779 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregor00aeb522009-07-08 23:33:52 +00003780 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003781 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00003782 FoundNonTemplateFunction = true;
3783 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00003784 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003785 }
3786
Douglas Gregor00aeb522009-07-08 23:33:52 +00003787 // If there were 0 or 1 matches, we're done.
3788 if (Matches.empty())
3789 return 0;
3790 else if (Matches.size() == 1)
3791 return *Matches.begin();
3792
3793 // C++ [over.over]p4:
3794 // If more than one function is selected, [...]
3795 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
3796 if (FoundNonTemplateFunction) {
3797 // [...] any function template specializations in the set are eliminated
3798 // if the set also contains a non-template function, [...]
3799 for (llvm::SmallPtrSet<FunctionDecl *, 4>::iterator M = Matches.begin(),
3800 MEnd = Matches.end();
3801 M != MEnd; ++M)
3802 if ((*M)->getPrimaryTemplate() == 0)
3803 RemainingMatches.push_back(*M);
3804 } else {
3805 // [...] and any given function template specialization F1 is eliminated
3806 // if the set contains a second function template specialization whose
3807 // function template is more specialized than the function template of F1
3808 // according to the partial ordering rules of 14.5.5.2.
3809 // FIXME: Implement this!
3810 RemainingMatches.append(Matches.begin(), Matches.end());
3811 }
3812
3813 // [...] After such eliminations, if any, there shall remain exactly one
3814 // selected function.
3815 if (RemainingMatches.size() == 1)
3816 return RemainingMatches.front();
3817
3818 // FIXME: We should probably return the same thing that BestViableFunction
3819 // returns (even if we issue the diagnostics here).
3820 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
3821 << RemainingMatches[0]->getDeclName();
3822 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
3823 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor904eed32008-11-10 20:40:00 +00003824 return 0;
3825}
3826
Douglas Gregorf6b89692008-11-26 05:54:23 +00003827/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00003828/// (which eventually refers to the declaration Func) and the call
3829/// arguments Args/NumArgs, attempt to resolve the function call down
3830/// to a specific function. If overload resolution succeeds, returns
3831/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00003832/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00003833/// arguments and Fn, and returns NULL.
Douglas Gregorfa047642009-02-04 00:32:51 +00003834FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor17330012009-02-04 15:01:18 +00003835 DeclarationName UnqualifiedName,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003836 bool HasExplicitTemplateArgs,
3837 const TemplateArgument *ExplicitTemplateArgs,
3838 unsigned NumExplicitTemplateArgs,
Douglas Gregor0a396682008-11-26 06:01:48 +00003839 SourceLocation LParenLoc,
3840 Expr **Args, unsigned NumArgs,
3841 SourceLocation *CommaLocs,
Douglas Gregorfa047642009-02-04 00:32:51 +00003842 SourceLocation RParenLoc,
Douglas Gregor17330012009-02-04 15:01:18 +00003843 bool &ArgumentDependentLookup) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00003844 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00003845
3846 // Add the functions denoted by Callee to the set of candidate
3847 // functions. While we're doing so, track whether argument-dependent
3848 // lookup still applies, per:
3849 //
3850 // C++0x [basic.lookup.argdep]p3:
3851 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3852 // and let Y be the lookup set produced by argument dependent
3853 // lookup (defined as follows). If X contains
3854 //
3855 // -- a declaration of a class member, or
3856 //
3857 // -- a block-scope function declaration that is not a
3858 // using-declaration, or
3859 //
3860 // -- a declaration that is neither a function or a function
3861 // template
3862 //
3863 // then Y is empty.
Douglas Gregorfa047642009-02-04 00:32:51 +00003864 if (OverloadedFunctionDecl *Ovl
Douglas Gregor17330012009-02-04 15:01:18 +00003865 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3866 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3867 FuncEnd = Ovl->function_end();
3868 Func != FuncEnd; ++Func) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003869 DeclContext *Ctx = 0;
3870 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003871 if (HasExplicitTemplateArgs)
3872 continue;
3873
Douglas Gregore53060f2009-06-25 22:08:12 +00003874 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
3875 Ctx = FunDecl->getDeclContext();
3876 } else {
3877 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003878 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
3879 ExplicitTemplateArgs,
3880 NumExplicitTemplateArgs,
3881 Args, NumArgs, CandidateSet);
Douglas Gregore53060f2009-06-25 22:08:12 +00003882 Ctx = FunTmpl->getDeclContext();
3883 }
Douglas Gregor17330012009-02-04 15:01:18 +00003884
Douglas Gregore53060f2009-06-25 22:08:12 +00003885
3886 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor17330012009-02-04 15:01:18 +00003887 ArgumentDependentLookup = false;
3888 }
3889 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003890 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor17330012009-02-04 15:01:18 +00003891 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3892
3893 if (Func->getDeclContext()->isRecord() ||
3894 Func->getDeclContext()->isFunctionOrMethod())
3895 ArgumentDependentLookup = false;
Douglas Gregore53060f2009-06-25 22:08:12 +00003896 } else if (FunctionTemplateDecl *FuncTemplate
3897 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003898 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
3899 ExplicitTemplateArgs,
3900 NumExplicitTemplateArgs,
3901 Args, NumArgs, CandidateSet);
Douglas Gregore53060f2009-06-25 22:08:12 +00003902
3903 if (FuncTemplate->getDeclContext()->isRecord())
3904 ArgumentDependentLookup = false;
3905 }
Douglas Gregor17330012009-02-04 15:01:18 +00003906
3907 if (Callee)
3908 UnqualifiedName = Callee->getDeclName();
3909
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003910 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregorfa047642009-02-04 00:32:51 +00003911 if (ArgumentDependentLookup)
Douglas Gregor17330012009-02-04 15:01:18 +00003912 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregorfa047642009-02-04 00:32:51 +00003913 CandidateSet);
3914
Douglas Gregorf6b89692008-11-26 05:54:23 +00003915 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003916 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00003917 case OR_Success:
3918 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003919
3920 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00003921 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00003922 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00003923 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00003924 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3925 break;
3926
3927 case OR_Ambiguous:
3928 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor17330012009-02-04 15:01:18 +00003929 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00003930 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3931 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003932
3933 case OR_Deleted:
3934 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
3935 << Best->Function->isDeleted()
3936 << UnqualifiedName
3937 << Fn->getSourceRange();
3938 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3939 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003940 }
3941
3942 // Overload resolution failed. Destroy all of the subexpressions and
3943 // return NULL.
3944 Fn->Destroy(Context);
3945 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3946 Args[Arg]->Destroy(Context);
3947 return 0;
3948}
3949
Douglas Gregorbc736fc2009-03-13 23:49:33 +00003950/// \brief Create a unary operation that may resolve to an overloaded
3951/// operator.
3952///
3953/// \param OpLoc The location of the operator itself (e.g., '*').
3954///
3955/// \param OpcIn The UnaryOperator::Opcode that describes this
3956/// operator.
3957///
3958/// \param Functions The set of non-member functions that will be
3959/// considered by overload resolution. The caller needs to build this
3960/// set based on the context using, e.g.,
3961/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3962/// set should not contain any member functions; those will be added
3963/// by CreateOverloadedUnaryOp().
3964///
3965/// \param input The input argument.
3966Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
3967 unsigned OpcIn,
3968 FunctionSet &Functions,
3969 ExprArg input) {
3970 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
3971 Expr *Input = (Expr *)input.get();
3972
3973 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
3974 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
3975 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3976
3977 Expr *Args[2] = { Input, 0 };
3978 unsigned NumArgs = 1;
3979
3980 // For post-increment and post-decrement, add the implicit '0' as
3981 // the second argument, so that we know this is a post-increment or
3982 // post-decrement.
3983 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
3984 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
3985 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
3986 SourceLocation());
3987 NumArgs = 2;
3988 }
3989
3990 if (Input->isTypeDependent()) {
3991 OverloadedFunctionDecl *Overloads
3992 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3993 for (FunctionSet::iterator Func = Functions.begin(),
3994 FuncEnd = Functions.end();
3995 Func != FuncEnd; ++Func)
3996 Overloads->addOverload(*Func);
3997
3998 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3999 OpLoc, false, false);
4000
4001 input.release();
4002 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4003 &Args[0], NumArgs,
4004 Context.DependentTy,
4005 OpLoc));
4006 }
4007
4008 // Build an empty overload set.
4009 OverloadCandidateSet CandidateSet;
4010
4011 // Add the candidates from the given function set.
4012 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4013
4014 // Add operator candidates that are member functions.
4015 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4016
4017 // Add builtin operator candidates.
4018 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4019
4020 // Perform overload resolution.
4021 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004022 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004023 case OR_Success: {
4024 // We found a built-in operator or an overloaded operator.
4025 FunctionDecl *FnDecl = Best->Function;
4026
4027 if (FnDecl) {
4028 // We matched an overloaded operator. Build a call to that
4029 // operator.
4030
4031 // Convert the arguments.
4032 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4033 if (PerformObjectArgumentInitialization(Input, Method))
4034 return ExprError();
4035 } else {
4036 // Convert the arguments.
4037 if (PerformCopyInitialization(Input,
4038 FnDecl->getParamDecl(0)->getType(),
4039 "passing"))
4040 return ExprError();
4041 }
4042
4043 // Determine the result type
4044 QualType ResultTy
4045 = FnDecl->getType()->getAsFunctionType()->getResultType();
4046 ResultTy = ResultTy.getNonReferenceType();
4047
4048 // Build the actual expression node.
4049 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4050 SourceLocation());
4051 UsualUnaryConversions(FnExpr);
4052
4053 input.release();
4054 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4055 &Input, 1, ResultTy,
4056 OpLoc));
4057 } else {
4058 // We matched a built-in operator. Convert the arguments, then
4059 // break out so that we will build the appropriate built-in
4060 // operator node.
4061 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4062 Best->Conversions[0], "passing"))
4063 return ExprError();
4064
4065 break;
4066 }
4067 }
4068
4069 case OR_No_Viable_Function:
4070 // No viable function; fall through to handling this as a
4071 // built-in operator, which will produce an error message for us.
4072 break;
4073
4074 case OR_Ambiguous:
4075 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4076 << UnaryOperator::getOpcodeStr(Opc)
4077 << Input->getSourceRange();
4078 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4079 return ExprError();
4080
4081 case OR_Deleted:
4082 Diag(OpLoc, diag::err_ovl_deleted_oper)
4083 << Best->Function->isDeleted()
4084 << UnaryOperator::getOpcodeStr(Opc)
4085 << Input->getSourceRange();
4086 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4087 return ExprError();
4088 }
4089
4090 // Either we found no viable overloaded operator or we matched a
4091 // built-in operator. In either case, fall through to trying to
4092 // build a built-in operation.
4093 input.release();
4094 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4095}
4096
Douglas Gregor063daf62009-03-13 18:40:31 +00004097/// \brief Create a binary operation that may resolve to an overloaded
4098/// operator.
4099///
4100/// \param OpLoc The location of the operator itself (e.g., '+').
4101///
4102/// \param OpcIn The BinaryOperator::Opcode that describes this
4103/// operator.
4104///
4105/// \param Functions The set of non-member functions that will be
4106/// considered by overload resolution. The caller needs to build this
4107/// set based on the context using, e.g.,
4108/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4109/// set should not contain any member functions; those will be added
4110/// by CreateOverloadedBinOp().
4111///
4112/// \param LHS Left-hand argument.
4113/// \param RHS Right-hand argument.
4114Sema::OwningExprResult
4115Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4116 unsigned OpcIn,
4117 FunctionSet &Functions,
4118 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004119 Expr *Args[2] = { LHS, RHS };
4120
4121 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4122 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4123 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4124
4125 // If either side is type-dependent, create an appropriate dependent
4126 // expression.
4127 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
4128 // .* cannot be overloaded.
4129 if (Opc == BinaryOperator::PtrMemD)
4130 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
4131 Context.DependentTy, OpLoc));
4132
4133 OverloadedFunctionDecl *Overloads
4134 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4135 for (FunctionSet::iterator Func = Functions.begin(),
4136 FuncEnd = Functions.end();
4137 Func != FuncEnd; ++Func)
4138 Overloads->addOverload(*Func);
4139
4140 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4141 OpLoc, false, false);
4142
4143 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4144 Args, 2,
4145 Context.DependentTy,
4146 OpLoc));
4147 }
4148
4149 // If this is the .* operator, which is not overloadable, just
4150 // create a built-in binary operator.
4151 if (Opc == BinaryOperator::PtrMemD)
4152 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4153
4154 // If this is one of the assignment operators, we only perform
4155 // overload resolution if the left-hand side is a class or
4156 // enumeration type (C++ [expr.ass]p3).
4157 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
4158 !LHS->getType()->isOverloadableType())
4159 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4160
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004161 // Build an empty overload set.
4162 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00004163
4164 // Add the candidates from the given function set.
4165 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4166
4167 // Add operator candidates that are member functions.
4168 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4169
4170 // Add builtin operator candidates.
4171 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4172
4173 // Perform overload resolution.
4174 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004175 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004176 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00004177 // We found a built-in operator or an overloaded operator.
4178 FunctionDecl *FnDecl = Best->Function;
4179
4180 if (FnDecl) {
4181 // We matched an overloaded operator. Build a call to that
4182 // operator.
4183
4184 // Convert the arguments.
4185 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4186 if (PerformObjectArgumentInitialization(LHS, Method) ||
4187 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
4188 "passing"))
4189 return ExprError();
4190 } else {
4191 // Convert the arguments.
4192 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
4193 "passing") ||
4194 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
4195 "passing"))
4196 return ExprError();
4197 }
4198
4199 // Determine the result type
4200 QualType ResultTy
4201 = FnDecl->getType()->getAsFunctionType()->getResultType();
4202 ResultTy = ResultTy.getNonReferenceType();
4203
4204 // Build the actual expression node.
4205 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00004206 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00004207 UsualUnaryConversions(FnExpr);
4208
4209 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4210 Args, 2, ResultTy,
4211 OpLoc));
4212 } else {
4213 // We matched a built-in operator. Convert the arguments, then
4214 // break out so that we will build the appropriate built-in
4215 // operator node.
4216 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
4217 Best->Conversions[0], "passing") ||
4218 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
4219 Best->Conversions[1], "passing"))
4220 return ExprError();
4221
4222 break;
4223 }
4224 }
4225
4226 case OR_No_Viable_Function:
Sebastian Redl8593c782009-05-21 11:50:50 +00004227 // For class as left operand for assignment or compound assigment operator
4228 // do not fall through to handling in built-in, but report that no overloaded
4229 // assignment operator found
4230 if (LHS->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4231 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4232 << BinaryOperator::getOpcodeStr(Opc)
4233 << LHS->getSourceRange() << RHS->getSourceRange();
4234 return ExprError();
4235 }
Douglas Gregor063daf62009-03-13 18:40:31 +00004236 // No viable function; fall through to handling this as a
4237 // built-in operator, which will produce an error message for us.
4238 break;
4239
4240 case OR_Ambiguous:
4241 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4242 << BinaryOperator::getOpcodeStr(Opc)
4243 << LHS->getSourceRange() << RHS->getSourceRange();
4244 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4245 return ExprError();
4246
4247 case OR_Deleted:
4248 Diag(OpLoc, diag::err_ovl_deleted_oper)
4249 << Best->Function->isDeleted()
4250 << BinaryOperator::getOpcodeStr(Opc)
4251 << LHS->getSourceRange() << RHS->getSourceRange();
4252 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4253 return ExprError();
4254 }
4255
4256 // Either we found no viable overloaded operator or we matched a
4257 // built-in operator. In either case, try to build a built-in
4258 // operation.
4259 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4260}
4261
Douglas Gregor88a35142008-12-22 05:46:06 +00004262/// BuildCallToMemberFunction - Build a call to a member
4263/// function. MemExpr is the expression that refers to the member
4264/// function (and includes the object parameter), Args/NumArgs are the
4265/// arguments to the function call (not including the object
4266/// parameter). The caller needs to validate that the member
4267/// expression refers to a member function or an overloaded member
4268/// function.
4269Sema::ExprResult
4270Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4271 SourceLocation LParenLoc, Expr **Args,
4272 unsigned NumArgs, SourceLocation *CommaLocs,
4273 SourceLocation RParenLoc) {
4274 // Dig out the member expression. This holds both the object
4275 // argument and the member function we're referring to.
4276 MemberExpr *MemExpr = 0;
4277 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4278 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4279 else
4280 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4281 assert(MemExpr && "Building member call without member expression");
4282
4283 // Extract the object argument.
4284 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004285
Douglas Gregor88a35142008-12-22 05:46:06 +00004286 CXXMethodDecl *Method = 0;
4287 if (OverloadedFunctionDecl *Ovl
4288 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
4289 // Add overload candidates
4290 OverloadCandidateSet CandidateSet;
4291 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4292 FuncEnd = Ovl->function_end();
4293 Func != FuncEnd; ++Func) {
4294 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
4295 Method = cast<CXXMethodDecl>(*Func);
4296 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4297 /*SuppressUserConversions=*/false);
4298 }
4299
4300 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004301 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004302 case OR_Success:
4303 Method = cast<CXXMethodDecl>(Best->Function);
4304 break;
4305
4306 case OR_No_Viable_Function:
4307 Diag(MemExpr->getSourceRange().getBegin(),
4308 diag::err_ovl_no_viable_member_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004309 << Ovl->getDeclName() << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00004310 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4311 // FIXME: Leaking incoming expressions!
4312 return true;
4313
4314 case OR_Ambiguous:
4315 Diag(MemExpr->getSourceRange().getBegin(),
4316 diag::err_ovl_ambiguous_member_call)
4317 << Ovl->getDeclName() << MemExprE->getSourceRange();
4318 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4319 // FIXME: Leaking incoming expressions!
4320 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004321
4322 case OR_Deleted:
4323 Diag(MemExpr->getSourceRange().getBegin(),
4324 diag::err_ovl_deleted_member_call)
4325 << Best->Function->isDeleted()
4326 << Ovl->getDeclName() << MemExprE->getSourceRange();
4327 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4328 // FIXME: Leaking incoming expressions!
4329 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004330 }
4331
4332 FixOverloadedFunctionReference(MemExpr, Method);
4333 } else {
4334 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4335 }
4336
4337 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek8189cde2009-02-07 01:47:29 +00004338 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek668bf912009-02-09 20:51:47 +00004339 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4340 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004341 Method->getResultType().getNonReferenceType(),
4342 RParenLoc));
4343
4344 // Convert the object argument (for a non-static member function call).
4345 if (!Method->isStatic() &&
4346 PerformObjectArgumentInitialization(ObjectArg, Method))
4347 return true;
4348 MemExpr->setBase(ObjectArg);
4349
4350 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00004351 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00004352 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4353 RParenLoc))
4354 return true;
4355
Sebastian Redl0eb23302009-01-19 00:08:26 +00004356 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor88a35142008-12-22 05:46:06 +00004357}
4358
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004359/// BuildCallToObjectOfClassType - Build a call to an object of class
4360/// type (C++ [over.call.object]), which can end up invoking an
4361/// overloaded function call operator (@c operator()) or performing a
4362/// user-defined conversion on the object argument.
Douglas Gregor88a35142008-12-22 05:46:06 +00004363Sema::ExprResult
Douglas Gregor5c37de72008-12-06 00:22:45 +00004364Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4365 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004366 Expr **Args, unsigned NumArgs,
4367 SourceLocation *CommaLocs,
4368 SourceLocation RParenLoc) {
4369 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek35366a62009-07-17 17:50:17 +00004370 const RecordType *Record = Object->getType()->getAsRecordType();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004371
4372 // C++ [over.call.object]p1:
4373 // If the primary-expression E in the function call syntax
4374 // evaluates to a class object of type “cv T”, then the set of
4375 // candidate functions includes at least the function call
4376 // operators of T. The function call operators of T are obtained by
4377 // ordinary lookup of the name operator() in the context of
4378 // (E).operator().
4379 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00004380 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004381 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004382 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004383 Oper != OperEnd; ++Oper)
4384 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4385 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004386
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004387 // C++ [over.call.object]p2:
4388 // In addition, for each conversion function declared in T of the
4389 // form
4390 //
4391 // operator conversion-type-id () cv-qualifier;
4392 //
4393 // where cv-qualifier is the same cv-qualification as, or a
4394 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00004395 // denotes the type "pointer to function of (P1,...,Pn) returning
4396 // R", or the type "reference to pointer to function of
4397 // (P1,...,Pn) returning R", or the type "reference to function
4398 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004399 // is also considered as a candidate function. Similarly,
4400 // surrogate call functions are added to the set of candidate
4401 // functions for each conversion function declared in an
4402 // accessible base class provided the function is not hidden
4403 // within T by another intervening declaration.
4404 //
4405 // FIXME: Look in base classes for more conversion operators!
4406 OverloadedFunctionDecl *Conversions
4407 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00004408 for (OverloadedFunctionDecl::function_iterator
4409 Func = Conversions->function_begin(),
4410 FuncEnd = Conversions->function_end();
4411 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004412 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
4413
4414 // Strip the reference type (if any) and then the pointer type (if
4415 // any) to get down to what might be a function type.
4416 QualType ConvType = Conv->getConversionType().getNonReferenceType();
Ted Kremenek35366a62009-07-17 17:50:17 +00004417 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004418 ConvType = ConvPtrType->getPointeeType();
4419
Douglas Gregor72564e72009-02-26 23:50:07 +00004420 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004421 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4422 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004423
4424 // Perform overload resolution.
4425 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004426 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004427 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004428 // Overload resolution succeeded; we'll build the appropriate call
4429 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004430 break;
4431
4432 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00004433 Diag(Object->getSourceRange().getBegin(),
4434 diag::err_ovl_no_viable_object_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004435 << Object->getType() << Object->getSourceRange();
Sebastian Redle4c452c2008-11-22 13:44:36 +00004436 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004437 break;
4438
4439 case OR_Ambiguous:
4440 Diag(Object->getSourceRange().getBegin(),
4441 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00004442 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004443 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4444 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004445
4446 case OR_Deleted:
4447 Diag(Object->getSourceRange().getBegin(),
4448 diag::err_ovl_deleted_object_call)
4449 << Best->Function->isDeleted()
4450 << Object->getType() << Object->getSourceRange();
4451 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4452 break;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004453 }
4454
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004455 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004456 // We had an error; delete all of the subexpressions and return
4457 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004458 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004459 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004460 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004461 return true;
4462 }
4463
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004464 if (Best->Function == 0) {
4465 // Since there is no function declaration, this is one of the
4466 // surrogate candidates. Dig out the conversion function.
4467 CXXConversionDecl *Conv
4468 = cast<CXXConversionDecl>(
4469 Best->Conversions[0].UserDefined.ConversionFunction);
4470
4471 // We selected one of the surrogate functions that converts the
4472 // object parameter to a function pointer. Perform the conversion
4473 // on the object argument, then let ActOnCallExpr finish the job.
4474 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl0eb23302009-01-19 00:08:26 +00004475 ImpCastExprToType(Object,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004476 Conv->getConversionType().getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004477 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00004478 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4479 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4480 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004481 }
4482
4483 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4484 // that calls this method, using Object for the implicit object
4485 // parameter and passing along the remaining arguments.
4486 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor72564e72009-02-26 23:50:07 +00004487 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004488
4489 unsigned NumArgsInProto = Proto->getNumArgs();
4490 unsigned NumArgsToCheck = NumArgs;
4491
4492 // Build the full argument list for the method call (the
4493 // implicit object parameter is placed at the beginning of the
4494 // list).
4495 Expr **MethodArgs;
4496 if (NumArgs < NumArgsInProto) {
4497 NumArgsToCheck = NumArgsInProto;
4498 MethodArgs = new Expr*[NumArgsInProto + 1];
4499 } else {
4500 MethodArgs = new Expr*[NumArgs + 1];
4501 }
4502 MethodArgs[0] = Object;
4503 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4504 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4505
Ted Kremenek8189cde2009-02-07 01:47:29 +00004506 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4507 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004508 UsualUnaryConversions(NewFn);
4509
4510 // Once we've built TheCall, all of the expressions are properly
4511 // owned.
4512 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004513 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor063daf62009-03-13 18:40:31 +00004514 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4515 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004516 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004517 delete [] MethodArgs;
4518
Douglas Gregor518fda12009-01-13 05:10:00 +00004519 // We may have default arguments. If so, we need to allocate more
4520 // slots in the call for them.
4521 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004522 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00004523 else if (NumArgs > NumArgsInProto)
4524 NumArgsToCheck = NumArgsInProto;
4525
Chris Lattner312531a2009-04-12 08:11:20 +00004526 bool IsError = false;
4527
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004528 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00004529 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004530 TheCall->setArg(0, Object);
4531
Chris Lattner312531a2009-04-12 08:11:20 +00004532
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004533 // Check the argument types.
4534 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004535 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00004536 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004537 Arg = Args[i];
Douglas Gregor518fda12009-01-13 05:10:00 +00004538
4539 // Pass the argument.
4540 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner312531a2009-04-12 08:11:20 +00004541 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor518fda12009-01-13 05:10:00 +00004542 } else {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004543 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregor518fda12009-01-13 05:10:00 +00004544 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004545
4546 TheCall->setArg(i + 1, Arg);
4547 }
4548
4549 // If this is a variadic call, handle args passed through "...".
4550 if (Proto->isVariadic()) {
4551 // Promote the arguments (C99 6.5.2.2p7).
4552 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4553 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00004554 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004555 TheCall->setArg(i + 1, Arg);
4556 }
4557 }
4558
Chris Lattner312531a2009-04-12 08:11:20 +00004559 if (IsError) return true;
4560
Sebastian Redl0eb23302009-01-19 00:08:26 +00004561 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004562}
4563
Douglas Gregor8ba10742008-11-20 16:27:02 +00004564/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4565/// (if one exists), where @c Base is an expression of class type and
4566/// @c Member is the name of the member we're trying to find.
4567Action::ExprResult
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004568Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004569 SourceLocation MemberLoc,
4570 IdentifierInfo &Member) {
4571 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4572
4573 // C++ [over.ref]p1:
4574 //
4575 // [...] An expression x->m is interpreted as (x.operator->())->m
4576 // for a class object x of type T if T::operator->() exists and if
4577 // the operator is selected as the best match function by the
4578 // overload resolution mechanism (13.3).
4579 // FIXME: look in base classes.
4580 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4581 OverloadCandidateSet CandidateSet;
Ted Kremenek35366a62009-07-17 17:50:17 +00004582 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004583
4584 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004585 for (llvm::tie(Oper, OperEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004586 = BaseRecord->getDecl()->lookup(OpName); Oper != OperEnd; ++Oper)
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004587 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004588 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004589
Ted Kremenek8189cde2009-02-07 01:47:29 +00004590 ExprOwningPtr<Expr> BasePtr(this, Base);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004591
Douglas Gregor8ba10742008-11-20 16:27:02 +00004592 // Perform overload resolution.
4593 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004594 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00004595 case OR_Success:
4596 // Overload resolution succeeded; we'll build the call below.
4597 break;
4598
4599 case OR_No_Viable_Function:
4600 if (CandidateSet.empty())
4601 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00004602 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004603 else
4604 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Chris Lattner4330d652009-02-17 07:29:20 +00004605 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004606 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004607 return true;
4608
4609 case OR_Ambiguous:
4610 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00004611 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004612 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004613 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004614
4615 case OR_Deleted:
4616 Diag(OpLoc, diag::err_ovl_deleted_oper)
4617 << Best->Function->isDeleted()
4618 << "operator->" << BasePtr->getSourceRange();
4619 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4620 return true;
Douglas Gregor8ba10742008-11-20 16:27:02 +00004621 }
4622
4623 // Convert the object parameter.
4624 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004625 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00004626 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004627
4628 // No concerns about early exits now.
4629 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004630
4631 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004632 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4633 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00004634 UsualUnaryConversions(FnExpr);
Douglas Gregor063daf62009-03-13 18:40:31 +00004635 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004636 Method->getResultType().getNonReferenceType(),
4637 OpLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004638 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004639 MemberLoc, Member, DeclPtrTy()).release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004640}
4641
Douglas Gregor904eed32008-11-10 20:40:00 +00004642/// FixOverloadedFunctionReference - E is an expression that refers to
4643/// a C++ overloaded function (possibly with some parentheses and
4644/// perhaps a '&' around it). We have resolved the overloaded function
4645/// to the function declaration Fn, so patch up the expression E to
4646/// refer (possibly indirectly) to Fn.
4647void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4648 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4649 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4650 E->setType(PE->getSubExpr()->getType());
4651 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4652 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4653 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00004654 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4655 if (Method->isStatic()) {
4656 // Do nothing: static member functions aren't any different
4657 // from non-member functions.
4658 }
4659 else if (QualifiedDeclRefExpr *DRE
4660 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4661 // We have taken the address of a pointer to member
4662 // function. Perform the computation here so that we get the
4663 // appropriate pointer to member type.
4664 DRE->setDecl(Fn);
4665 DRE->setType(Fn->getType());
4666 QualType ClassType
4667 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4668 E->setType(Context.getMemberPointerType(Fn->getType(),
4669 ClassType.getTypePtr()));
4670 return;
4671 }
4672 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004673 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00004674 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor904eed32008-11-10 20:40:00 +00004675 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00004676 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
4677 isa<FunctionTemplateDecl>(DR->getDecl())) &&
4678 "Expected overloaded function or function template");
Douglas Gregor904eed32008-11-10 20:40:00 +00004679 DR->setDecl(Fn);
4680 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00004681 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4682 MemExpr->setMemberDecl(Fn);
4683 E->setType(Fn->getType());
Douglas Gregor904eed32008-11-10 20:40:00 +00004684 } else {
4685 assert(false && "Invalid reference to overloaded function");
4686 }
4687}
4688
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004689} // end namespace clang