blob: b4f25812ba2d9953f8e408624f50a6e5d2c1fb70 [file] [log] [blame]
Douglas Gregord2baafd2008-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 Gregorbb461502008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregor10f3c502008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Anders Carlssona21e7872009-08-26 23:45:07 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor3d4492e2008-11-13 20:12:29 +000023#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000025#include "llvm/Support/Compiler.h"
26#include <algorithm>
Edwin Török0fbc71c2009-08-24 13:25:12 +000027#include <cstdio>
Douglas Gregord2baafd2008-10-21 16:13:35 +000028
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
33ImplicitConversionCategory
34GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
41 ICC_Qualification_Adjustment,
42 ICC_Promotion,
43 ICC_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000044 ICC_Promotion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000047 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000052 ICC_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000053 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000054 ICC_Conversion
55 };
56 return Category[(int)Kind];
57}
58
59/// GetConversionRank - Retrieve the implicit conversion rank
60/// corresponding to the given implicit conversion kind.
61ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
62 static const ImplicitConversionRank
63 Rank[(int)ICK_Num_Conversion_Kinds] = {
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Promotion,
70 ICR_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000071 ICR_Promotion,
72 ICR_Conversion,
73 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000074 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000079 ICR_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000080 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000081 ICR_Conversion
82 };
83 return Rank[(int)Kind];
84}
85
86/// GetImplicitConversionName - Return the name of this kind of
87/// implicit conversion.
88const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
89 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
90 "No conversion",
91 "Lvalue-to-rvalue",
92 "Array-to-pointer",
93 "Function-to-pointer",
94 "Qualification",
95 "Integral promotion",
96 "Floating point promotion",
Douglas Gregore819caf2009-02-12 00:15:05 +000097 "Complex promotion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000098 "Integral conversion",
99 "Floating conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000100 "Complex conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000101 "Floating-integral conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000102 "Complex-real conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000103 "Pointer conversion",
104 "Pointer-to-member conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000105 "Boolean conversion",
Douglas Gregorfcb19192009-02-11 23:02:49 +0000106 "Compatible-types conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000107 "Derived-to-base conversion"
Douglas Gregord2baafd2008-10-21 16:13:35 +0000108 };
109 return Name[Kind];
110}
111
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000112/// StandardConversionSequence - Set the standard conversion
113/// sequence to the identity conversion.
114void StandardConversionSequence::setAsIdentityConversion() {
115 First = ICK_Identity;
116 Second = ICK_Identity;
117 Third = ICK_Identity;
118 Deprecated = false;
119 ReferenceBinding = false;
120 DirectBinding = false;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +0000121 RRefBinding = false;
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000122 CopyConstructor = 0;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000123}
124
Douglas Gregord2baafd2008-10-21 16:13:35 +0000125/// getRank - Retrieve the rank of this standard conversion sequence
126/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
127/// implicit conversions.
128ImplicitConversionRank StandardConversionSequence::getRank() const {
129 ImplicitConversionRank Rank = ICR_Exact_Match;
130 if (GetConversionRank(First) > Rank)
131 Rank = GetConversionRank(First);
132 if (GetConversionRank(Second) > Rank)
133 Rank = GetConversionRank(Second);
134 if (GetConversionRank(Third) > Rank)
135 Rank = GetConversionRank(Third);
136 return Rank;
137}
138
139/// isPointerConversionToBool - Determines whether this conversion is
140/// a conversion of a pointer or pointer-to-member to bool. This is
141/// used as part of the ranking of standard conversion sequences
142/// (C++ 13.3.3.2p4).
143bool StandardConversionSequence::isPointerConversionToBool() const
144{
145 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
146 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
147
148 // Note that FromType has not necessarily been transformed by the
149 // array-to-pointer or function-to-pointer implicit conversions, so
150 // check for their presence as well as checking whether FromType is
151 // a pointer.
152 if (ToType->isBooleanType() &&
Douglas Gregor80402cf2008-12-23 00:53:59 +0000153 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000154 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
155 return true;
156
157 return false;
158}
159
Douglas Gregor14046502008-10-23 00:40:37 +0000160/// isPointerConversionToVoidPointer - Determines whether this
161/// conversion is a conversion of a pointer to a void pointer. This is
162/// used as part of the ranking of standard conversion sequences (C++
163/// 13.3.3.2p4).
164bool
165StandardConversionSequence::
166isPointerConversionToVoidPointer(ASTContext& Context) const
167{
168 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
169 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
170
171 // Note that FromType has not necessarily been transformed by the
172 // array-to-pointer implicit conversion, so check for its presence
173 // and redo the conversion to get a pointer.
174 if (First == ICK_Array_To_Pointer)
175 FromType = Context.getArrayDecayedType(FromType);
176
177 if (Second == ICK_Pointer_Conversion)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000178 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor14046502008-10-23 00:40:37 +0000179 return ToPtrType->getPointeeType()->isVoidType();
180
181 return false;
182}
183
Douglas Gregord2baafd2008-10-21 16:13:35 +0000184/// DebugPrint - Print this standard conversion sequence to standard
185/// error. Useful for debugging overloading issues.
186void StandardConversionSequence::DebugPrint() const {
187 bool PrintedSomething = false;
188 if (First != ICK_Identity) {
189 fprintf(stderr, "%s", GetImplicitConversionName(First));
190 PrintedSomething = true;
191 }
192
193 if (Second != ICK_Identity) {
194 if (PrintedSomething) {
195 fprintf(stderr, " -> ");
196 }
197 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000198
199 if (CopyConstructor) {
200 fprintf(stderr, " (by copy constructor)");
201 } else if (DirectBinding) {
202 fprintf(stderr, " (direct reference binding)");
203 } else if (ReferenceBinding) {
204 fprintf(stderr, " (reference binding)");
205 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000206 PrintedSomething = true;
207 }
208
209 if (Third != ICK_Identity) {
210 if (PrintedSomething) {
211 fprintf(stderr, " -> ");
212 }
213 fprintf(stderr, "%s", GetImplicitConversionName(Third));
214 PrintedSomething = true;
215 }
216
217 if (!PrintedSomething) {
218 fprintf(stderr, "No conversions required");
219 }
220}
221
222/// DebugPrint - Print this user-defined conversion sequence to standard
223/// error. Useful for debugging overloading issues.
224void UserDefinedConversionSequence::DebugPrint() const {
225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
227 fprintf(stderr, " -> ");
228 }
Chris Lattner271d4c22008-11-24 05:29:24 +0000229 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
231 fprintf(stderr, " -> ");
232 After.DebugPrint();
233 }
234}
235
236/// DebugPrint - Print this implicit conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void ImplicitConversionSequence::DebugPrint() const {
239 switch (ConversionKind) {
240 case StandardConversion:
241 fprintf(stderr, "Standard conversion: ");
242 Standard.DebugPrint();
243 break;
244 case UserDefinedConversion:
245 fprintf(stderr, "User-defined conversion: ");
246 UserDefined.DebugPrint();
247 break;
248 case EllipsisConversion:
249 fprintf(stderr, "Ellipsis conversion");
250 break;
251 case BadConversion:
252 fprintf(stderr, "Bad conversion");
253 break;
254 }
255
256 fprintf(stderr, "\n");
257}
258
259// IsOverload - Determine whether the given New declaration is an
260// overload of the Old declaration. This routine returns false if New
261// and Old cannot be overloaded, e.g., if they are functions with the
262// same signature (C++ 1.3.10) or if the Old declaration isn't a
263// function (or overload set). When it does return false and Old is an
264// OverloadedFunctionDecl, MatchedDecl will be set to point to the
265// FunctionDecl that New cannot be overloaded with.
266//
267// Example: Given the following input:
268//
269// void f(int, float); // #1
270// void f(int, int); // #2
271// int f(int, int); // #3
272//
273// When we process #1, there is no previous declaration of "f",
274// so IsOverload will not be used.
275//
276// When we process #2, Old is a FunctionDecl for #1. By comparing the
277// parameter types, we see that #1 and #2 are overloaded (since they
278// have different signatures), so this routine returns false;
279// MatchedDecl is unchanged.
280//
281// When we process #3, Old is an OverloadedFunctionDecl containing #1
282// and #2. We compare the signatures of #3 to #1 (they're overloaded,
283// so we do nothing) and then #3 to #2. Since the signatures of #3 and
284// #2 are identical (return types of functions are not part of the
285// signature), IsOverload returns false and MatchedDecl will be set to
286// point to the FunctionDecl for #2.
287bool
288Sema::IsOverload(FunctionDecl *New, Decl* OldD,
289 OverloadedFunctionDecl::function_iterator& MatchedDecl)
290{
291 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
292 // Is this new function an overload of every function in the
293 // overload set?
294 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
295 FuncEnd = Ovl->function_end();
296 for (; Func != FuncEnd; ++Func) {
297 if (!IsOverload(New, *Func, MatchedDecl)) {
298 MatchedDecl = Func;
299 return false;
300 }
301 }
302
303 // This function overloads every function in the overload set.
304 return true;
Douglas Gregorb60eb752009-06-25 22:08:12 +0000305 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
306 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
307 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000308 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
309 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
310
311 // C++ [temp.fct]p2:
312 // A function template can be overloaded with other function templates
313 // and with normal (non-template) functions.
314 if ((OldTemplate == 0) != (NewTemplate == 0))
315 return true;
316
Douglas Gregord2baafd2008-10-21 16:13:35 +0000317 // Is the function New an overload of the function Old?
318 QualType OldQType = Context.getCanonicalType(Old->getType());
319 QualType NewQType = Context.getCanonicalType(New->getType());
320
321 // Compare the signatures (C++ 1.3.10) of the two functions to
322 // determine whether they are overloads. If we find any mismatch
323 // in the signature, they are overloads.
324
325 // If either of these functions is a K&R-style function (no
326 // prototype), then we consider them to have matching signatures.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000327 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
328 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregord2baafd2008-10-21 16:13:35 +0000329 return false;
330
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000331 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
332 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000333
334 // The signature of a function includes the types of its
335 // parameters (C++ 1.3.10), which includes the presence or absence
336 // of the ellipsis; see C++ DR 357).
337 if (OldQType != NewQType &&
338 (OldType->getNumArgs() != NewType->getNumArgs() ||
339 OldType->isVariadic() != NewType->isVariadic() ||
340 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
341 NewType->arg_type_begin())))
342 return true;
343
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000344 // C++ [temp.over.link]p4:
345 // The signature of a function template consists of its function
346 // signature, its return type and its template parameter list. The names
347 // of the template parameters are significant only for establishing the
348 // relationship between the template parameters and the rest of the
349 // signature.
350 //
351 // We check the return type and template parameter lists for function
352 // templates first; the remaining checks follow.
353 if (NewTemplate &&
354 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
355 OldTemplate->getTemplateParameters(),
356 false, false, SourceLocation()) ||
357 OldType->getResultType() != NewType->getResultType()))
358 return true;
359
Douglas Gregord2baafd2008-10-21 16:13:35 +0000360 // If the function is a class member, its signature includes the
361 // cv-qualifiers (if any) on the function itself.
362 //
363 // As part of this, also check whether one of the member functions
364 // is static, in which case they are not overloads (C++
365 // 13.1p2). While not part of the definition of the signature,
366 // this check is important to determine whether these functions
367 // can be overloaded.
368 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
369 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
370 if (OldMethod && NewMethod &&
371 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregora7b56a32008-11-21 15:36:28 +0000372 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregord2baafd2008-10-21 16:13:35 +0000373 return true;
374
375 // The signatures match; this is not an overload.
376 return false;
377 } else {
378 // (C++ 13p1):
379 // Only function declarations can be overloaded; object and type
380 // declarations cannot be overloaded.
381 return false;
382 }
383}
384
Douglas Gregor81c29152008-10-29 00:13:59 +0000385/// TryImplicitConversion - Attempt to perform an implicit conversion
386/// from the given expression (Expr) to the given type (ToType). This
387/// function returns an implicit conversion sequence that can be used
388/// to perform the initialization. Given
Douglas Gregord2baafd2008-10-21 16:13:35 +0000389///
390/// void f(float f);
391/// void g(int i) { f(i); }
392///
393/// this routine would produce an implicit conversion sequence to
394/// describe the initialization of f from i, which will be a standard
395/// conversion sequence containing an lvalue-to-rvalue conversion (C++
396/// 4.1) followed by a floating-integral conversion (C++ 4.9).
397//
398/// Note that this routine only determines how the conversion can be
399/// performed; it does not actually perform the conversion. As such,
400/// it will not produce any diagnostics if no conversion is available,
401/// but will instead return an implicit conversion sequence of kind
402/// "BadConversion".
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000403///
404/// If @p SuppressUserConversions, then user-defined conversions are
405/// not permitted.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000406/// If @p AllowExplicit, then explicit user-defined conversions are
407/// permitted.
Sebastian Redla55834a2009-04-12 17:16:29 +0000408/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
409/// no matter its actual lvalueness.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000410ImplicitConversionSequence
Anders Carlssonfcc53032009-08-27 17:14:02 +0000411Sema::TryImplicitConversion(Expr* From, QualType ToType,
412 bool SuppressUserConversions,
413 bool AllowExplicit, bool ForceRValue)
414{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000415 ImplicitConversionSequence ICS;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000416 if (IsStandardConversion(From, ToType, ICS.Standard))
417 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000418 else if (getLangOptions().CPlusPlus &&
419 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Sebastian Redla55834a2009-04-12 17:16:29 +0000420 !SuppressUserConversions, AllowExplicit,
421 ForceRValue)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000422 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000423 // C++ [over.ics.user]p4:
424 // A conversion of an expression of class type to the same class
425 // type is given Exact Match rank, and a conversion of an
426 // expression of class type to a base class of that type is
427 // given Conversion rank, in spite of the fact that a copy
428 // constructor (i.e., a user-defined conversion function) is
429 // called for those cases.
430 if (CXXConstructorDecl *Constructor
431 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregord9176392009-02-02 22:11:10 +0000432 QualType FromCanon
433 = Context.getCanonicalType(From->getType().getUnqualifiedType());
434 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
435 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000436 // Turn this into a "standard" conversion sequence, so that it
437 // gets ranked with standard conversion sequences.
Douglas Gregore640ab62008-11-03 17:51:48 +0000438 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
439 ICS.Standard.setAsIdentityConversion();
440 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
441 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000442 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregord9176392009-02-02 22:11:10 +0000443 if (ToCanon != FromCanon)
Douglas Gregore640ab62008-11-03 17:51:48 +0000444 ICS.Standard.Second = ICK_Derived_To_Base;
445 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000446 }
Douglas Gregorb206cc42009-01-30 23:27:23 +0000447
448 // C++ [over.best.ics]p4:
449 // However, when considering the argument of a user-defined
450 // conversion function that is a candidate by 13.3.1.3 when
451 // invoked for the copying of the temporary in the second step
452 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
453 // 13.3.1.6 in all cases, only standard conversion sequences and
454 // ellipsis conversion sequences are allowed.
455 if (SuppressUserConversions &&
456 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
457 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000458 } else
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000459 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000460
461 return ICS;
462}
463
464/// IsStandardConversion - Determines whether there is a standard
465/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
466/// expression From to the type ToType. Standard conversion sequences
467/// only consider non-class types; for conversions that involve class
468/// types, use TryImplicitConversion. If a conversion exists, SCS will
469/// contain the standard conversion sequence required to perform this
470/// conversion and this routine will return true. Otherwise, this
471/// routine will return false and the value of SCS is unspecified.
472bool
473Sema::IsStandardConversion(Expr* From, QualType ToType,
474 StandardConversionSequence &SCS)
475{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000476 QualType FromType = From->getType();
477
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000478 // Standard conversions (C++ [conv])
Douglas Gregor70d26122008-11-12 17:17:38 +0000479 SCS.setAsIdentityConversion();
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000480 SCS.Deprecated = false;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000481 SCS.IncompatibleObjC = false;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000482 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000483 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000484
Douglas Gregorfcb19192009-02-11 23:02:49 +0000485 // There are no standard conversions for class types in C++, so
486 // abort early. When overloading in C, however, we do permit
487 if (FromType->isRecordType() || ToType->isRecordType()) {
488 if (getLangOptions().CPlusPlus)
489 return false;
490
491 // When we're overloading in C, we allow, as standard conversions,
492 }
493
Douglas Gregord2baafd2008-10-21 16:13:35 +0000494 // The first conversion can be an lvalue-to-rvalue conversion,
495 // array-to-pointer conversion, or function-to-pointer conversion
496 // (C++ 4p1).
497
498 // Lvalue-to-rvalue conversion (C++ 4.1):
499 // An lvalue (3.10) of a non-function, non-array type T can be
500 // converted to an rvalue.
501 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
502 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor45014fd2008-11-10 20:40:00 +0000503 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000504 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000505 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000506
507 // If T is a non-class type, the type of the rvalue is the
508 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorfcb19192009-02-11 23:02:49 +0000509 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
510 // just strip the qualifiers because they don't matter.
511
512 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000513 FromType = FromType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000514 } else if (FromType->isArrayType()) {
515 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000516 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000517
518 // An lvalue or rvalue of type "array of N T" or "array of unknown
519 // bound of T" can be converted to an rvalue of type "pointer to
520 // T" (C++ 4.2p1).
521 FromType = Context.getArrayDecayedType(FromType);
522
523 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
524 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000525 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000526
527 // For the purpose of ranking in overload resolution
528 // (13.3.3.1.1), this conversion is considered an
529 // array-to-pointer conversion followed by a qualification
530 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000531 SCS.Second = ICK_Identity;
532 SCS.Third = ICK_Qualification;
533 SCS.ToTypePtr = ToType.getAsOpaquePtr();
534 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000535 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000536 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
537 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000538 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-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);
Mike Stump90fc78e2009-08-04 21:02:39 +0000544 } else if (FunctionDecl *Fn
Douglas Gregor45014fd2008-11-10 20:40:00 +0000545 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000546 // Address of overloaded function (C++ [over.over]).
Douglas Gregor45014fd2008-11-10 20:40:00 +0000547 SCS.First = ICK_Function_To_Pointer;
548
549 // We were able to resolve the address of the overloaded function,
550 // so we can convert to the type of that function.
551 FromType = Fn->getType();
Sebastian Redlce6fff02009-03-16 23:22:08 +0000552 if (ToType->isLValueReferenceType())
553 FromType = Context.getLValueReferenceType(FromType);
554 else if (ToType->isRValueReferenceType())
555 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000556 else if (ToType->isMemberPointerType()) {
557 // Resolve address only succeeds if both sides are member pointers,
558 // but it doesn't have to be the same class. See DR 247.
559 // Note that this means that the type of &Derived::fn can be
560 // Ret (Base::*)(Args) if the fn overload actually found is from the
561 // base class, even if it was brought into the derived class via a
562 // using declaration. The standard isn't clear on this issue at all.
563 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
564 FromType = Context.getMemberPointerType(FromType,
565 Context.getTypeDeclType(M->getParent()).getTypePtr());
566 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000567 FromType = Context.getPointerType(FromType);
Mike Stump90fc78e2009-08-04 21:02:39 +0000568 } else {
569 // We don't require any conversions for the first step.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000570 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000571 }
572
573 // The second conversion can be an integral promotion, floating
574 // point promotion, integral conversion, floating point conversion,
575 // floating-integral conversion, pointer conversion,
576 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorfcb19192009-02-11 23:02:49 +0000577 // For overloading in C, this can also be a "compatible-type"
578 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000579 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000580 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000581 // The unqualified versions of the types are the same: there's no
582 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000583 SCS.Second = ICK_Identity;
Mike Stump90fc78e2009-08-04 21:02:39 +0000584 } else if (IsIntegralPromotion(From, FromType, ToType)) {
585 // Integral promotion (C++ 4.5).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000586 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000587 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000588 } else if (IsFloatingPointPromotion(FromType, ToType)) {
589 // Floating point promotion (C++ 4.6).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000590 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000591 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000592 } else if (IsComplexPromotion(FromType, ToType)) {
593 // Complex promotion (Clang extension)
Douglas Gregore819caf2009-02-12 00:15:05 +0000594 SCS.Second = ICK_Complex_Promotion;
595 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000596 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000597 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000598 // Integral conversions (C++ 4.7).
599 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000600 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000601 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000602 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
603 // Floating point conversions (C++ 4.8).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000604 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000605 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000606 } else if (FromType->isComplexType() && ToType->isComplexType()) {
607 // Complex conversions (C99 6.3.1.6)
Douglas Gregore819caf2009-02-12 00:15:05 +0000608 SCS.Second = ICK_Complex_Conversion;
609 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000610 } else if ((FromType->isFloatingType() &&
611 ToType->isIntegralType() && (!ToType->isBooleanType() &&
612 !ToType->isEnumeralType())) ||
613 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
614 ToType->isFloatingType())) {
615 // Floating-integral conversions (C++ 4.9).
616 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000617 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000618 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000619 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
620 (ToType->isComplexType() && FromType->isArithmeticType())) {
621 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregore819caf2009-02-12 00:15:05 +0000622 SCS.Second = ICK_Complex_Real;
623 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000624 } else if (IsPointerConversion(From, FromType, ToType, FromType,
625 IncompatibleObjC)) {
626 // Pointer conversions (C++ 4.10).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000627 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000628 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stump90fc78e2009-08-04 21:02:39 +0000629 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
630 // Pointer to member conversions (4.11).
Sebastian Redlba387562009-01-25 19:43:20 +0000631 SCS.Second = ICK_Pointer_Member;
Mike Stump90fc78e2009-08-04 21:02:39 +0000632 } else if (ToType->isBooleanType() &&
633 (FromType->isArithmeticType() ||
634 FromType->isEnumeralType() ||
635 FromType->isPointerType() ||
636 FromType->isBlockPointerType() ||
637 FromType->isMemberPointerType() ||
638 FromType->isNullPtrType())) {
639 // Boolean conversions (C++ 4.12).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000640 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000641 FromType = Context.BoolTy;
Mike Stump90fc78e2009-08-04 21:02:39 +0000642 } else if (!getLangOptions().CPlusPlus &&
643 Context.typesAreCompatible(ToType, FromType)) {
644 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorfcb19192009-02-11 23:02:49 +0000645 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000646 } else {
647 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000648 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000649 }
650
Douglas Gregor81c29152008-10-29 00:13:59 +0000651 QualType CanonFrom;
652 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000653 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000654 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000655 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000656 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000657 CanonFrom = Context.getCanonicalType(FromType);
658 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000659 } else {
660 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000661 SCS.Third = ICK_Identity;
662
663 // C++ [over.best.ics]p6:
664 // [...] Any difference in top-level cv-qualification is
665 // subsumed by the initialization itself and does not constitute
666 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000667 CanonFrom = Context.getCanonicalType(FromType);
668 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000669 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000670 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
671 FromType = ToType;
672 CanonFrom = CanonTo;
673 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000674 }
675
676 // If we have not converted the argument type to the parameter type,
677 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000678 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000679 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000680
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000681 SCS.ToTypePtr = FromType.getAsOpaquePtr();
682 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000683}
684
685/// IsIntegralPromotion - Determines whether the conversion from the
686/// expression From (whose potentially-adjusted type is FromType) to
687/// ToType is an integral promotion (C++ 4.5). If so, returns true and
688/// sets PromotedType to the promoted type.
689bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
690{
691 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000692 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000693 if (!To) {
694 return false;
695 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000696
697 // An rvalue of type char, signed char, unsigned char, short int, or
698 // unsigned short int can be converted to an rvalue of type int if
699 // int can represent all the values of the source type; otherwise,
700 // the source rvalue can be converted to an rvalue of type unsigned
701 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000702 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000703 if (// We can promote any signed, promotable integer type to an int
704 (FromType->isSignedIntegerType() ||
705 // We can promote any unsigned integer type whose size is
706 // less than int to an int.
707 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000708 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000709 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000710 }
711
Douglas Gregord2baafd2008-10-21 16:13:35 +0000712 return To->getKind() == BuiltinType::UInt;
713 }
714
715 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
716 // can be converted to an rvalue of the first of the following types
717 // that can represent all the values of its underlying type: int,
718 // unsigned int, long, or unsigned long (C++ 4.5p2).
719 if ((FromType->isEnumeralType() || FromType->isWideCharType())
720 && ToType->isIntegerType()) {
721 // Determine whether the type we're converting from is signed or
722 // unsigned.
723 bool FromIsSigned;
724 uint64_t FromSize = Context.getTypeSize(FromType);
725 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
726 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
727 FromIsSigned = UnderlyingType->isSignedIntegerType();
728 } else {
729 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
730 FromIsSigned = true;
731 }
732
733 // The types we'll try to promote to, in the appropriate
734 // order. Try each of these types.
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000735 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000736 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000737 Context.LongTy, Context.UnsignedLongTy ,
738 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000739 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000740 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000741 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
742 if (FromSize < ToSize ||
743 (FromSize == ToSize &&
744 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
745 // We found the type that we can promote to. If this is the
746 // type we wanted, we have a promotion. Otherwise, no
747 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000748 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000749 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
750 }
751 }
752 }
753
754 // An rvalue for an integral bit-field (9.6) can be converted to an
755 // rvalue of type int if int can represent all the values of the
756 // bit-field; otherwise, it can be converted to unsigned int if
757 // unsigned int can represent all the values of the bit-field. If
758 // the bit-field is larger yet, no integral promotion applies to
759 // it. If the bit-field has an enumerated type, it is treated as any
760 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stumpe127ae32009-05-16 07:39:55 +0000761 // FIXME: We should delay checking of bit-fields until we actually perform the
762 // conversion.
Douglas Gregor531434b2009-05-02 02:18:30 +0000763 using llvm::APSInt;
764 if (From)
765 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor82d44772008-12-20 23:49:58 +0000766 APSInt BitWidth;
Douglas Gregor531434b2009-05-02 02:18:30 +0000767 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
768 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
769 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
770 ToSize = Context.getTypeSize(ToType);
Douglas Gregor82d44772008-12-20 23:49:58 +0000771
772 // Are we promoting to an int from a bitfield that fits in an int?
773 if (BitWidth < ToSize ||
774 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
775 return To->getKind() == BuiltinType::Int;
776 }
777
778 // Are we promoting to an unsigned int from an unsigned bitfield
779 // that fits into an unsigned int?
780 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
781 return To->getKind() == BuiltinType::UInt;
782 }
783
784 return false;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000785 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000786 }
Douglas Gregor531434b2009-05-02 02:18:30 +0000787
Douglas Gregord2baafd2008-10-21 16:13:35 +0000788 // An rvalue of type bool can be converted to an rvalue of type int,
789 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000790 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000791 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000792 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000793
794 return false;
795}
796
797/// IsFloatingPointPromotion - Determines whether the conversion from
798/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
799/// returns true and sets PromotedType to the promoted type.
800bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
801{
802 /// An rvalue of type float can be converted to an rvalue of type
803 /// double. (C++ 4.6p1).
804 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregore819caf2009-02-12 00:15:05 +0000805 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000806 if (FromBuiltin->getKind() == BuiltinType::Float &&
807 ToBuiltin->getKind() == BuiltinType::Double)
808 return true;
809
Douglas Gregore819caf2009-02-12 00:15:05 +0000810 // C99 6.3.1.5p1:
811 // When a float is promoted to double or long double, or a
812 // double is promoted to long double [...].
813 if (!getLangOptions().CPlusPlus &&
814 (FromBuiltin->getKind() == BuiltinType::Float ||
815 FromBuiltin->getKind() == BuiltinType::Double) &&
816 (ToBuiltin->getKind() == BuiltinType::LongDouble))
817 return true;
818 }
819
Douglas Gregord2baafd2008-10-21 16:13:35 +0000820 return false;
821}
822
Douglas Gregore819caf2009-02-12 00:15:05 +0000823/// \brief Determine if a conversion is a complex promotion.
824///
825/// A complex promotion is defined as a complex -> complex conversion
826/// where the conversion between the underlying real types is a
Douglas Gregor4ff48512009-02-12 00:26:06 +0000827/// floating-point or integral promotion.
Douglas Gregore819caf2009-02-12 00:15:05 +0000828bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
829 const ComplexType *FromComplex = FromType->getAsComplexType();
830 if (!FromComplex)
831 return false;
832
833 const ComplexType *ToComplex = ToType->getAsComplexType();
834 if (!ToComplex)
835 return false;
836
837 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor4ff48512009-02-12 00:26:06 +0000838 ToComplex->getElementType()) ||
839 IsIntegralPromotion(0, FromComplex->getElementType(),
840 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000841}
842
Douglas Gregor24a90a52008-11-26 23:31:11 +0000843/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
844/// the pointer type FromPtr to a pointer to type ToPointee, with the
845/// same type qualifiers as FromPtr has on its pointee type. ToType,
846/// if non-empty, will be a pointer to ToType that may or may not have
847/// the right set of qualifiers on its pointee.
848static QualType
849BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
850 QualType ToPointee, QualType ToType,
851 ASTContext &Context) {
852 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
853 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
854 unsigned Quals = CanonFromPointee.getCVRQualifiers();
855
856 // Exact qualifier match -> return the pointer type we're converting to.
857 if (CanonToPointee.getCVRQualifiers() == Quals) {
858 // ToType is exactly what we need. Return it.
859 if (ToType.getTypePtr())
860 return ToType;
861
862 // Build a pointer to ToPointee. It has the right qualifiers
863 // already.
864 return Context.getPointerType(ToPointee);
865 }
866
867 // Just build a canonical type that has the right qualifiers.
868 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
869}
870
Douglas Gregord2baafd2008-10-21 16:13:35 +0000871/// IsPointerConversion - Determines whether the conversion of the
872/// expression From, which has the (possibly adjusted) type FromType,
873/// can be converted to the type ToType via a pointer conversion (C++
874/// 4.10). If so, returns true and places the converted type (that
875/// might differ from ToType in its cv-qualifiers at some level) into
876/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000877///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000878/// This routine also supports conversions to and from block pointers
879/// and conversions with Objective-C's 'id', 'id<protocols...>', and
880/// pointers to interfaces. FIXME: Once we've determined the
881/// appropriate overloading rules for Objective-C, we may want to
882/// split the Objective-C checks into a different routine; however,
883/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000884/// conversions, so for now they live here. IncompatibleObjC will be
885/// set if the conversion is an allowed Objective-C conversion that
886/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000887bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000888 QualType& ConvertedType,
889 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000890{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000891 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000892 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
893 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000894
Douglas Gregorf1d75712008-12-22 20:51:52 +0000895 // Conversion from a null pointer constant to any Objective-C pointer type.
Steve Naroffad75bd22009-07-16 15:41:00 +0000896 if (ToType->isObjCObjectPointerType() &&
Douglas Gregorf1d75712008-12-22 20:51:52 +0000897 From->isNullPointerConstant(Context)) {
898 ConvertedType = ToType;
899 return true;
900 }
901
Douglas Gregor9036ef72008-11-27 00:15:41 +0000902 // Blocks: Block pointers can be converted to void*.
903 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000904 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor9036ef72008-11-27 00:15:41 +0000905 ConvertedType = ToType;
906 return true;
907 }
908 // Blocks: A null pointer constant can be converted to a block
909 // pointer type.
910 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
911 ConvertedType = ToType;
912 return true;
913 }
914
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000915 // If the left-hand-side is nullptr_t, the right side can be a null
916 // pointer constant.
917 if (ToType->isNullPtrType() && From->isNullPointerConstant(Context)) {
918 ConvertedType = ToType;
919 return true;
920 }
921
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000922 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000923 if (!ToTypePtr)
924 return false;
925
926 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
927 if (From->isNullPointerConstant(Context)) {
928 ConvertedType = ToType;
929 return true;
930 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000931
Douglas Gregor24a90a52008-11-26 23:31:11 +0000932 // Beyond this point, both types need to be pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000933 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor24a90a52008-11-26 23:31:11 +0000934 if (!FromTypePtr)
935 return false;
936
937 QualType FromPointeeType = FromTypePtr->getPointeeType();
938 QualType ToPointeeType = ToTypePtr->getPointeeType();
939
Douglas Gregord2baafd2008-10-21 16:13:35 +0000940 // An rvalue of type "pointer to cv T," where T is an object type,
941 // can be converted to an rvalue of type "pointer to cv void" (C++
942 // 4.10p2).
Douglas Gregor26ea1222009-03-24 20:32:41 +0000943 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000944 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
945 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000946 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000947 return true;
948 }
949
Douglas Gregorfcb19192009-02-11 23:02:49 +0000950 // When we're overloading in C, we allow a special kind of pointer
951 // conversion for compatible-but-not-identical pointee types.
952 if (!getLangOptions().CPlusPlus &&
953 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
954 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
955 ToPointeeType,
956 ToType, Context);
957 return true;
958 }
959
Douglas Gregor14046502008-10-23 00:40:37 +0000960 // C++ [conv.ptr]p3:
961 //
962 // An rvalue of type "pointer to cv D," where D is a class type,
963 // can be converted to an rvalue of type "pointer to cv B," where
964 // B is a base class (clause 10) of D. If B is an inaccessible
965 // (clause 11) or ambiguous (10.2) base class of D, a program that
966 // necessitates this conversion is ill-formed. The result of the
967 // conversion is a pointer to the base class sub-object of the
968 // derived class object. The null pointer value is converted to
969 // the null pointer value of the destination type.
970 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000971 // Note that we do not check for ambiguity or inaccessibility
972 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000973 if (getLangOptions().CPlusPlus &&
974 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000975 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000976 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
977 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000978 ToType, Context);
979 return true;
980 }
Douglas Gregor14046502008-10-23 00:40:37 +0000981
Douglas Gregor932778b2008-12-19 19:13:09 +0000982 return false;
983}
984
985/// isObjCPointerConversion - Determines whether this is an
986/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
987/// with the same arguments and return values.
988bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
989 QualType& ConvertedType,
990 bool &IncompatibleObjC) {
991 if (!getLangOptions().ObjC1)
992 return false;
993
Steve Naroff329ec222009-07-10 23:34:53 +0000994 // First, we handle all conversions on ObjC object pointer types.
995 const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
996 const ObjCObjectPointerType *FromObjCPtr =
997 FromType->getAsObjCObjectPointerType();
Douglas Gregor932778b2008-12-19 19:13:09 +0000998
Steve Naroff329ec222009-07-10 23:34:53 +0000999 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff7bffd372009-07-15 18:40:39 +00001000 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff329ec222009-07-10 23:34:53 +00001001 // pointer to any interface (in both directions).
Steve Naroff7bffd372009-07-15 18:40:39 +00001002 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00001003 ConvertedType = ToType;
1004 return true;
1005 }
1006 // Conversions with Objective-C's id<...>.
1007 if ((FromObjCPtr->isObjCQualifiedIdType() ||
1008 ToObjCPtr->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00001009 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1010 /*compare=*/false)) {
Steve Naroff329ec222009-07-10 23:34:53 +00001011 ConvertedType = ToType;
1012 return true;
1013 }
1014 // Objective C++: We're able to convert from a pointer to an
1015 // interface to a pointer to a different interface.
1016 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1017 ConvertedType = ToType;
1018 return true;
1019 }
1020
1021 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1022 // Okay: this is some kind of implicit downcast of Objective-C
1023 // interfaces, which is permitted. However, we're going to
1024 // complain about it.
1025 IncompatibleObjC = true;
1026 ConvertedType = FromType;
1027 return true;
1028 }
1029 }
1030 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor80402cf2008-12-23 00:53:59 +00001031 QualType ToPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001032 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001033 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001034 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001035 ToPointeeType = ToBlockPtr->getPointeeType();
1036 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001037 return false;
1038
Douglas Gregor80402cf2008-12-23 00:53:59 +00001039 QualType FromPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001040 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001041 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001042 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001043 FromPointeeType = FromBlockPtr->getPointeeType();
1044 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001045 return false;
1046
Douglas Gregor932778b2008-12-19 19:13:09 +00001047 // If we have pointers to pointers, recursively check whether this
1048 // is an Objective-C conversion.
1049 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1050 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1051 IncompatibleObjC)) {
1052 // We always complain about this conversion.
1053 IncompatibleObjC = true;
1054 ConvertedType = ToType;
1055 return true;
1056 }
Douglas Gregor80402cf2008-12-23 00:53:59 +00001057 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +00001058 // differences in the argument and result types are in Objective-C
1059 // pointer conversions. If so, we permit the conversion (but
1060 // complain about it).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001061 const FunctionProtoType *FromFunctionType
1062 = FromPointeeType->getAsFunctionProtoType();
1063 const FunctionProtoType *ToFunctionType
1064 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001065 if (FromFunctionType && ToFunctionType) {
1066 // If the function types are exactly the same, this isn't an
1067 // Objective-C pointer conversion.
1068 if (Context.getCanonicalType(FromPointeeType)
1069 == Context.getCanonicalType(ToPointeeType))
1070 return false;
1071
1072 // Perform the quick checks that will tell us whether these
1073 // function types are obviously different.
1074 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1075 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1076 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1077 return false;
1078
1079 bool HasObjCConversion = false;
1080 if (Context.getCanonicalType(FromFunctionType->getResultType())
1081 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1082 // Okay, the types match exactly. Nothing to do.
1083 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1084 ToFunctionType->getResultType(),
1085 ConvertedType, IncompatibleObjC)) {
1086 // Okay, we have an Objective-C pointer conversion.
1087 HasObjCConversion = true;
1088 } else {
1089 // Function types are too different. Abort.
1090 return false;
1091 }
1092
1093 // Check argument types.
1094 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1095 ArgIdx != NumArgs; ++ArgIdx) {
1096 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1097 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1098 if (Context.getCanonicalType(FromArgType)
1099 == Context.getCanonicalType(ToArgType)) {
1100 // Okay, the types match exactly. Nothing to do.
1101 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1102 ConvertedType, IncompatibleObjC)) {
1103 // Okay, we have an Objective-C pointer conversion.
1104 HasObjCConversion = true;
1105 } else {
1106 // Argument types are too different. Abort.
1107 return false;
1108 }
1109 }
1110
1111 if (HasObjCConversion) {
1112 // We had an Objective-C conversion. Allow this pointer
1113 // conversion, but complain about it.
1114 ConvertedType = ToType;
1115 IncompatibleObjC = true;
1116 return true;
1117 }
1118 }
1119
Sebastian Redlba387562009-01-25 19:43:20 +00001120 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001121}
1122
Douglas Gregorbb461502008-10-24 04:54:22 +00001123/// CheckPointerConversion - Check the pointer conversion from the
1124/// expression From to the type ToType. This routine checks for
Sebastian Redl0e35d042009-07-25 15:41:38 +00001125/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregorbb461502008-10-24 04:54:22 +00001126/// conversions for which IsPointerConversion has already returned
1127/// true. It returns true and produces a diagnostic if there was an
1128/// error, or returns false otherwise.
1129bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1130 QualType FromType = From->getType();
1131
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001132 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1133 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001134 QualType FromPointeeType = FromPtrType->getPointeeType(),
1135 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001136
Douglas Gregorbb461502008-10-24 04:54:22 +00001137 if (FromPointeeType->isRecordType() &&
1138 ToPointeeType->isRecordType()) {
1139 // We must have a derived-to-base conversion. Check an
1140 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001141 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1142 From->getExprLoc(),
1143 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001144 }
1145 }
Steve Naroff329ec222009-07-10 23:34:53 +00001146 if (const ObjCObjectPointerType *FromPtrType =
1147 FromType->getAsObjCObjectPointerType())
1148 if (const ObjCObjectPointerType *ToPtrType =
1149 ToType->getAsObjCObjectPointerType()) {
1150 // Objective-C++ conversions are always okay.
1151 // FIXME: We should have a different class of conversions for the
1152 // Objective-C++ implicit conversions.
Steve Naroff7bffd372009-07-15 18:40:39 +00001153 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff329ec222009-07-10 23:34:53 +00001154 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +00001155
Steve Naroff329ec222009-07-10 23:34:53 +00001156 }
Douglas Gregorbb461502008-10-24 04:54:22 +00001157 return false;
1158}
1159
Sebastian Redlba387562009-01-25 19:43:20 +00001160/// IsMemberPointerConversion - Determines whether the conversion of the
1161/// expression From, which has the (possibly adjusted) type FromType, can be
1162/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1163/// If so, returns true and places the converted type (that might differ from
1164/// ToType in its cv-qualifiers at some level) into ConvertedType.
1165bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1166 QualType ToType, QualType &ConvertedType)
1167{
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001168 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001169 if (!ToTypePtr)
1170 return false;
1171
1172 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1173 if (From->isNullPointerConstant(Context)) {
1174 ConvertedType = ToType;
1175 return true;
1176 }
1177
1178 // Otherwise, both types have to be member pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001179 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001180 if (!FromTypePtr)
1181 return false;
1182
1183 // A pointer to member of B can be converted to a pointer to member of D,
1184 // where D is derived from B (C++ 4.11p2).
1185 QualType FromClass(FromTypePtr->getClass(), 0);
1186 QualType ToClass(ToTypePtr->getClass(), 0);
1187 // FIXME: What happens when these are dependent? Is this function even called?
1188
1189 if (IsDerivedFrom(ToClass, FromClass)) {
1190 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1191 ToClass.getTypePtr());
1192 return true;
1193 }
1194
1195 return false;
1196}
1197
1198/// CheckMemberPointerConversion - Check the member pointer conversion from the
1199/// expression From to the type ToType. This routine checks for ambiguous or
1200/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1201/// for which IsMemberPointerConversion has already returned true. It returns
1202/// true and produces a diagnostic if there was an error, or returns false
1203/// otherwise.
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001204bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1205 CastExpr::CastKind &Kind) {
Sebastian Redlba387562009-01-25 19:43:20 +00001206 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001207 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001208 if (!FromPtrType) {
1209 // This must be a null pointer to member pointer conversion
1210 assert(From->isNullPointerConstant(Context) &&
1211 "Expr must be null pointer constant!");
1212 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001213 return false;
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001214 }
Sebastian Redlba387562009-01-25 19:43:20 +00001215
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001216 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001217 assert(ToPtrType && "No member pointer cast has a target type "
1218 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001219
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001220 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1221 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001222
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001223 // FIXME: What about dependent types?
1224 assert(FromClass->isRecordType() && "Pointer into non-class.");
1225 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001226
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001227 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1228 /*DetectVirtual=*/true);
1229 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1230 assert(DerivationOkay &&
1231 "Should not have been called if derivation isn't OK.");
1232 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001233
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001234 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1235 getUnqualifiedType())) {
1236 // Derivation is ambiguous. Redo the check to find the exact paths.
1237 Paths.clear();
1238 Paths.setRecordingPaths(true);
1239 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1240 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1241 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001242
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001243 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1244 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1245 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1246 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001247 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001248
Douglas Gregor2e047592009-02-28 01:32:25 +00001249 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001250 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1251 << FromClass << ToClass << QualType(VBase, 0)
1252 << From->getSourceRange();
1253 return true;
1254 }
1255
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001256 // Must be a base to derived member conversion.
1257 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redlba387562009-01-25 19:43:20 +00001258 return false;
1259}
1260
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001261/// IsQualificationConversion - Determines whether the conversion from
1262/// an rvalue of type FromType to ToType is a qualification conversion
1263/// (C++ 4.4).
1264bool
1265Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1266{
1267 FromType = Context.getCanonicalType(FromType);
1268 ToType = Context.getCanonicalType(ToType);
1269
1270 // If FromType and ToType are the same type, this is not a
1271 // qualification conversion.
1272 if (FromType == ToType)
1273 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001274
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001275 // (C++ 4.4p4):
1276 // A conversion can add cv-qualifiers at levels other than the first
1277 // in multi-level pointers, subject to the following rules: [...]
1278 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001279 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001280 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001281 // Within each iteration of the loop, we check the qualifiers to
1282 // determine if this still looks like a qualification
1283 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001284 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001285 // until there are no more pointers or pointers-to-members left to
1286 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001287 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001288
1289 // -- for every j > 0, if const is in cv 1,j then const is in cv
1290 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001291 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001292 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001293
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001294 // -- if the cv 1,j and cv 2,j are different, then const is in
1295 // every cv for 0 < k < j.
1296 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001297 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001298 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001299
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001300 // Keep track of whether all prior cv-qualifiers in the "to" type
1301 // include const.
1302 PreviousToQualsIncludeConst
1303 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001304 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001305
1306 // We are left with FromType and ToType being the pointee types
1307 // after unwrapping the original FromType and ToType the same number
1308 // of types. If we unwrapped any pointers, and if FromType and
1309 // ToType have the same unqualified type (since we checked
1310 // qualifiers above), then this is a qualification conversion.
1311 return UnwrappedAnyPointer &&
1312 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1313}
1314
Douglas Gregor8c860df2009-08-21 23:19:43 +00001315/// \brief Given a function template or function, extract the function template
1316/// declaration (if any) and the underlying function declaration.
1317template<typename T>
1318static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1319 FunctionTemplateDecl *&FunctionTemplate) {
1320 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1321 if (FunctionTemplate)
1322 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1323 else
1324 Function = cast<T>(Orig);
1325}
1326
1327
Douglas Gregorb206cc42009-01-30 23:27:23 +00001328/// Determines whether there is a user-defined conversion sequence
1329/// (C++ [over.ics.user]) that converts expression From to the type
1330/// ToType. If such a conversion exists, User will contain the
1331/// user-defined conversion sequence that performs such a conversion
1332/// and this routine will return true. Otherwise, this routine returns
1333/// false and User is unspecified.
1334///
1335/// \param AllowConversionFunctions true if the conversion should
1336/// consider conversion functions at all. If false, only constructors
1337/// will be considered.
1338///
1339/// \param AllowExplicit true if the conversion should consider C++0x
1340/// "explicit" conversion functions as well as non-explicit conversion
1341/// functions (C++0x [class.conv.fct]p2).
Sebastian Redla55834a2009-04-12 17:16:29 +00001342///
1343/// \param ForceRValue true if the expression should be treated as an rvalue
1344/// for overload resolution.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001345bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001346 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001347 bool AllowConversionFunctions,
Sebastian Redla55834a2009-04-12 17:16:29 +00001348 bool AllowExplicit, bool ForceRValue)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001349{
1350 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001351 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001352 if (CXXRecordDecl *ToRecordDecl
1353 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1354 // C++ [over.match.ctor]p1:
1355 // When objects of class type are direct-initialized (8.5), or
1356 // copy-initialized from an expression of the same or a
1357 // derived class type (8.5), overload resolution selects the
1358 // constructor. [...] For copy-initialization, the candidate
1359 // functions are all the converting constructors (12.3.1) of
1360 // that class. The argument list is the expression-list within
1361 // the parentheses of the initializer.
1362 DeclarationName ConstructorName
1363 = Context.DeclarationNames.getCXXConstructorName(
1364 Context.getCanonicalType(ToType).getUnqualifiedType());
1365 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001366 for (llvm::tie(Con, ConEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001367 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor2e047592009-02-28 01:32:25 +00001368 Con != ConEnd; ++Con) {
Douglas Gregor050cabf2009-08-21 18:42:58 +00001369 // Find the constructor (which may be a template).
1370 CXXConstructorDecl *Constructor = 0;
1371 FunctionTemplateDecl *ConstructorTmpl
1372 = dyn_cast<FunctionTemplateDecl>(*Con);
1373 if (ConstructorTmpl)
1374 Constructor
1375 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1376 else
1377 Constructor = cast<CXXConstructorDecl>(*Con);
1378
Fariborz Jahanian625fb9d2009-08-06 17:22:51 +00001379 if (!Constructor->isInvalidDecl() &&
Douglas Gregor050cabf2009-08-21 18:42:58 +00001380 Constructor->isConvertingConstructor()) {
1381 if (ConstructorTmpl)
1382 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
1383 1, CandidateSet,
1384 /*SuppressUserConversions=*/true,
1385 ForceRValue);
1386 else
1387 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1388 /*SuppressUserConversions=*/true, ForceRValue);
1389 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001390 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001391 }
1392 }
1393
Douglas Gregorb206cc42009-01-30 23:27:23 +00001394 if (!AllowConversionFunctions) {
1395 // Don't allow any conversion functions to enter the overload set.
Anders Carlssona21e7872009-08-26 23:45:07 +00001396 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1397 PDiag(0)
1398 << From->getSourceRange())) {
Douglas Gregorb35c7992009-08-24 15:23:48 +00001399 // No conversion functions from incomplete types.
Douglas Gregor2e047592009-02-28 01:32:25 +00001400 } else if (const RecordType *FromRecordType
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001401 = From->getType()->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001402 if (CXXRecordDecl *FromRecordDecl
1403 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1404 // Add all of the conversion functions as candidates.
1405 // FIXME: Look for conversions in base classes!
1406 OverloadedFunctionDecl *Conversions
1407 = FromRecordDecl->getConversionFunctions();
1408 for (OverloadedFunctionDecl::function_iterator Func
1409 = Conversions->function_begin();
1410 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00001411 CXXConversionDecl *Conv;
1412 FunctionTemplateDecl *ConvTemplate;
1413 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1414 if (ConvTemplate)
1415 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1416 else
1417 Conv = dyn_cast<CXXConversionDecl>(*Func);
1418
1419 if (AllowExplicit || !Conv->isExplicit()) {
1420 if (ConvTemplate)
1421 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1422 CandidateSet);
1423 else
1424 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1425 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001426 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001427 }
1428 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001429
1430 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001431 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001432 case OR_Success:
1433 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001434 if (CXXConstructorDecl *Constructor
1435 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1436 // C++ [over.ics.user]p1:
1437 // If the user-defined conversion is specified by a
1438 // constructor (12.3.1), the initial standard conversion
1439 // sequence converts the source type to the type required by
1440 // the argument of the constructor.
1441 //
1442 // FIXME: What about ellipsis conversions?
1443 QualType ThisType = Constructor->getThisType(Context);
1444 User.Before = Best->Conversions[0].Standard;
1445 User.ConversionFunction = Constructor;
1446 User.After.setAsIdentityConversion();
1447 User.After.FromTypePtr
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001448 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001449 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1450 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001451 } else if (CXXConversionDecl *Conversion
1452 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1453 // C++ [over.ics.user]p1:
1454 //
1455 // [...] If the user-defined conversion is specified by a
1456 // conversion function (12.3.2), the initial standard
1457 // conversion sequence converts the source type to the
1458 // implicit object parameter of the conversion function.
1459 User.Before = Best->Conversions[0].Standard;
1460 User.ConversionFunction = Conversion;
1461
1462 // C++ [over.ics.user]p2:
1463 // The second standard conversion sequence converts the
1464 // result of the user-defined conversion to the target type
1465 // for the sequence. Since an implicit conversion sequence
1466 // is an initialization, the special rules for
1467 // initialization by user-defined conversion apply when
1468 // selecting the best user-defined conversion for a
1469 // user-defined conversion sequence (see 13.3.3 and
1470 // 13.3.3.1).
1471 User.After = Best->FinalConversion;
1472 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001473 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001474 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001475 return false;
1476 }
1477
1478 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001479 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001480 // No conversion here! We're done.
1481 return false;
1482
1483 case OR_Ambiguous:
1484 // FIXME: See C++ [over.best.ics]p10 for the handling of
1485 // ambiguous conversion sequences.
1486 return false;
1487 }
1488
1489 return false;
1490}
1491
Douglas Gregord2baafd2008-10-21 16:13:35 +00001492/// CompareImplicitConversionSequences - Compare two implicit
1493/// conversion sequences to determine whether one is better than the
1494/// other or if they are indistinguishable (C++ 13.3.3.2).
1495ImplicitConversionSequence::CompareKind
1496Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1497 const ImplicitConversionSequence& ICS2)
1498{
1499 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1500 // conversion sequences (as defined in 13.3.3.1)
1501 // -- a standard conversion sequence (13.3.3.1.1) is a better
1502 // conversion sequence than a user-defined conversion sequence or
1503 // an ellipsis conversion sequence, and
1504 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1505 // conversion sequence than an ellipsis conversion sequence
1506 // (13.3.3.1.3).
1507 //
1508 if (ICS1.ConversionKind < ICS2.ConversionKind)
1509 return ImplicitConversionSequence::Better;
1510 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1511 return ImplicitConversionSequence::Worse;
1512
1513 // Two implicit conversion sequences of the same form are
1514 // indistinguishable conversion sequences unless one of the
1515 // following rules apply: (C++ 13.3.3.2p3):
1516 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1517 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1518 else if (ICS1.ConversionKind ==
1519 ImplicitConversionSequence::UserDefinedConversion) {
1520 // User-defined conversion sequence U1 is a better conversion
1521 // sequence than another user-defined conversion sequence U2 if
1522 // they contain the same user-defined conversion function or
1523 // constructor and if the second standard conversion sequence of
1524 // U1 is better than the second standard conversion sequence of
1525 // U2 (C++ 13.3.3.2p3).
1526 if (ICS1.UserDefined.ConversionFunction ==
1527 ICS2.UserDefined.ConversionFunction)
1528 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1529 ICS2.UserDefined.After);
1530 }
1531
1532 return ImplicitConversionSequence::Indistinguishable;
1533}
1534
1535/// CompareStandardConversionSequences - Compare two standard
1536/// conversion sequences to determine whether one is better than the
1537/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1538ImplicitConversionSequence::CompareKind
1539Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1540 const StandardConversionSequence& SCS2)
1541{
1542 // Standard conversion sequence S1 is a better conversion sequence
1543 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1544
1545 // -- S1 is a proper subsequence of S2 (comparing the conversion
1546 // sequences in the canonical form defined by 13.3.3.1.1,
1547 // excluding any Lvalue Transformation; the identity conversion
1548 // sequence is considered to be a subsequence of any
1549 // non-identity conversion sequence) or, if not that,
1550 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1551 // Neither is a proper subsequence of the other. Do nothing.
1552 ;
1553 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1554 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1555 (SCS1.Second == ICK_Identity &&
1556 SCS1.Third == ICK_Identity))
1557 // SCS1 is a proper subsequence of SCS2.
1558 return ImplicitConversionSequence::Better;
1559 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1560 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1561 (SCS2.Second == ICK_Identity &&
1562 SCS2.Third == ICK_Identity))
1563 // SCS2 is a proper subsequence of SCS1.
1564 return ImplicitConversionSequence::Worse;
1565
1566 // -- the rank of S1 is better than the rank of S2 (by the rules
1567 // defined below), or, if not that,
1568 ImplicitConversionRank Rank1 = SCS1.getRank();
1569 ImplicitConversionRank Rank2 = SCS2.getRank();
1570 if (Rank1 < Rank2)
1571 return ImplicitConversionSequence::Better;
1572 else if (Rank2 < Rank1)
1573 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001574
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001575 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1576 // are indistinguishable unless one of the following rules
1577 // applies:
1578
1579 // A conversion that is not a conversion of a pointer, or
1580 // pointer to member, to bool is better than another conversion
1581 // that is such a conversion.
1582 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1583 return SCS2.isPointerConversionToBool()
1584 ? ImplicitConversionSequence::Better
1585 : ImplicitConversionSequence::Worse;
1586
Douglas Gregor14046502008-10-23 00:40:37 +00001587 // C++ [over.ics.rank]p4b2:
1588 //
1589 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001590 // conversion of B* to A* is better than conversion of B* to
1591 // void*, and conversion of A* to void* is better than conversion
1592 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001593 bool SCS1ConvertsToVoid
1594 = SCS1.isPointerConversionToVoidPointer(Context);
1595 bool SCS2ConvertsToVoid
1596 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001597 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1598 // Exactly one of the conversion sequences is a conversion to
1599 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001600 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1601 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001602 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1603 // Neither conversion sequence converts to a void pointer; compare
1604 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001605 if (ImplicitConversionSequence::CompareKind DerivedCK
1606 = CompareDerivedToBaseConversions(SCS1, SCS2))
1607 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001608 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1609 // Both conversion sequences are conversions to void
1610 // pointers. Compare the source types to determine if there's an
1611 // inheritance relationship in their sources.
1612 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1613 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1614
1615 // Adjust the types we're converting from via the array-to-pointer
1616 // conversion, if we need to.
1617 if (SCS1.First == ICK_Array_To_Pointer)
1618 FromType1 = Context.getArrayDecayedType(FromType1);
1619 if (SCS2.First == ICK_Array_To_Pointer)
1620 FromType2 = Context.getArrayDecayedType(FromType2);
1621
1622 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001623 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001624 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001625 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001626
1627 if (IsDerivedFrom(FromPointee2, FromPointee1))
1628 return ImplicitConversionSequence::Better;
1629 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1630 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001631
1632 // Objective-C++: If one interface is more specific than the
1633 // other, it is the better one.
1634 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1635 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1636 if (FromIface1 && FromIface1) {
1637 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1638 return ImplicitConversionSequence::Better;
1639 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1640 return ImplicitConversionSequence::Worse;
1641 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001642 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001643
1644 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1645 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001646 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001647 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001648 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001649
Douglas Gregor0e343382008-10-29 14:50:44 +00001650 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001651 // C++0x [over.ics.rank]p3b4:
1652 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1653 // implicit object parameter of a non-static member function declared
1654 // without a ref-qualifier, and S1 binds an rvalue reference to an
1655 // rvalue and S2 binds an lvalue reference.
Sebastian Redldfc30332009-03-29 15:27:50 +00001656 // FIXME: We don't know if we're dealing with the implicit object parameter,
1657 // or if the member function in this case has a ref qualifier.
1658 // (Of course, we don't have ref qualifiers yet.)
1659 if (SCS1.RRefBinding != SCS2.RRefBinding)
1660 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1661 : ImplicitConversionSequence::Worse;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001662
1663 // C++ [over.ics.rank]p3b4:
1664 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1665 // which the references refer are the same type except for
1666 // top-level cv-qualifiers, and the type to which the reference
1667 // initialized by S2 refers is more cv-qualified than the type
1668 // to which the reference initialized by S1 refers.
Sebastian Redldfc30332009-03-29 15:27:50 +00001669 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1670 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregor0e343382008-10-29 14:50:44 +00001671 T1 = Context.getCanonicalType(T1);
1672 T2 = Context.getCanonicalType(T2);
1673 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1674 if (T2.isMoreQualifiedThan(T1))
1675 return ImplicitConversionSequence::Better;
1676 else if (T1.isMoreQualifiedThan(T2))
1677 return ImplicitConversionSequence::Worse;
1678 }
1679 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001680
1681 return ImplicitConversionSequence::Indistinguishable;
1682}
1683
1684/// CompareQualificationConversions - Compares two standard conversion
1685/// sequences to determine whether they can be ranked based on their
1686/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1687ImplicitConversionSequence::CompareKind
1688Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1689 const StandardConversionSequence& SCS2)
1690{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001691 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001692 // -- S1 and S2 differ only in their qualification conversion and
1693 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1694 // cv-qualification signature of type T1 is a proper subset of
1695 // the cv-qualification signature of type T2, and S1 is not the
1696 // deprecated string literal array-to-pointer conversion (4.2).
1697 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1698 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1699 return ImplicitConversionSequence::Indistinguishable;
1700
1701 // FIXME: the example in the standard doesn't use a qualification
1702 // conversion (!)
1703 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1704 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1705 T1 = Context.getCanonicalType(T1);
1706 T2 = Context.getCanonicalType(T2);
1707
1708 // If the types are the same, we won't learn anything by unwrapped
1709 // them.
1710 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1711 return ImplicitConversionSequence::Indistinguishable;
1712
1713 ImplicitConversionSequence::CompareKind Result
1714 = ImplicitConversionSequence::Indistinguishable;
1715 while (UnwrapSimilarPointerTypes(T1, T2)) {
1716 // Within each iteration of the loop, we check the qualifiers to
1717 // determine if this still looks like a qualification
1718 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001719 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001720 // until there are no more pointers or pointers-to-members left
1721 // to unwrap. This essentially mimics what
1722 // IsQualificationConversion does, but here we're checking for a
1723 // strict subset of qualifiers.
1724 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1725 // The qualifiers are the same, so this doesn't tell us anything
1726 // about how the sequences rank.
1727 ;
1728 else if (T2.isMoreQualifiedThan(T1)) {
1729 // T1 has fewer qualifiers, so it could be the better sequence.
1730 if (Result == ImplicitConversionSequence::Worse)
1731 // Neither has qualifiers that are a subset of the other's
1732 // qualifiers.
1733 return ImplicitConversionSequence::Indistinguishable;
1734
1735 Result = ImplicitConversionSequence::Better;
1736 } else if (T1.isMoreQualifiedThan(T2)) {
1737 // T2 has fewer qualifiers, so it could be the better sequence.
1738 if (Result == ImplicitConversionSequence::Better)
1739 // Neither has qualifiers that are a subset of the other's
1740 // qualifiers.
1741 return ImplicitConversionSequence::Indistinguishable;
1742
1743 Result = ImplicitConversionSequence::Worse;
1744 } else {
1745 // Qualifiers are disjoint.
1746 return ImplicitConversionSequence::Indistinguishable;
1747 }
1748
1749 // If the types after this point are equivalent, we're done.
1750 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1751 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001752 }
1753
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001754 // Check that the winning standard conversion sequence isn't using
1755 // the deprecated string literal array to pointer conversion.
1756 switch (Result) {
1757 case ImplicitConversionSequence::Better:
1758 if (SCS1.Deprecated)
1759 Result = ImplicitConversionSequence::Indistinguishable;
1760 break;
1761
1762 case ImplicitConversionSequence::Indistinguishable:
1763 break;
1764
1765 case ImplicitConversionSequence::Worse:
1766 if (SCS2.Deprecated)
1767 Result = ImplicitConversionSequence::Indistinguishable;
1768 break;
1769 }
1770
1771 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001772}
1773
Douglas Gregor14046502008-10-23 00:40:37 +00001774/// CompareDerivedToBaseConversions - Compares two standard conversion
1775/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001776/// various kinds of derived-to-base conversions (C++
1777/// [over.ics.rank]p4b3). As part of these checks, we also look at
1778/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001779ImplicitConversionSequence::CompareKind
1780Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1781 const StandardConversionSequence& SCS2) {
1782 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1783 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1784 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1785 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1786
1787 // Adjust the types we're converting from via the array-to-pointer
1788 // conversion, if we need to.
1789 if (SCS1.First == ICK_Array_To_Pointer)
1790 FromType1 = Context.getArrayDecayedType(FromType1);
1791 if (SCS2.First == ICK_Array_To_Pointer)
1792 FromType2 = Context.getArrayDecayedType(FromType2);
1793
1794 // Canonicalize all of the types.
1795 FromType1 = Context.getCanonicalType(FromType1);
1796 ToType1 = Context.getCanonicalType(ToType1);
1797 FromType2 = Context.getCanonicalType(FromType2);
1798 ToType2 = Context.getCanonicalType(ToType2);
1799
Douglas Gregor0e343382008-10-29 14:50:44 +00001800 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001801 //
1802 // If class B is derived directly or indirectly from class A and
1803 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001804 //
1805 // For Objective-C, we let A, B, and C also be Objective-C
1806 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001807
1808 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001809 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001810 SCS2.Second == ICK_Pointer_Conversion &&
1811 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1812 FromType1->isPointerType() && FromType2->isPointerType() &&
1813 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001814 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001815 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001816 QualType ToPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001817 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001818 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001819 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001820 QualType ToPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001821 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001822
1823 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1824 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1825 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1826 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1827
Douglas Gregor0e343382008-10-29 14:50:44 +00001828 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001829 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1830 if (IsDerivedFrom(ToPointee1, ToPointee2))
1831 return ImplicitConversionSequence::Better;
1832 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1833 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001834
1835 if (ToIface1 && ToIface2) {
1836 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1837 return ImplicitConversionSequence::Better;
1838 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1839 return ImplicitConversionSequence::Worse;
1840 }
Douglas Gregor14046502008-10-23 00:40:37 +00001841 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001842
1843 // -- conversion of B* to A* is better than conversion of C* to A*,
1844 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1845 if (IsDerivedFrom(FromPointee2, FromPointee1))
1846 return ImplicitConversionSequence::Better;
1847 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1848 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001849
1850 if (FromIface1 && FromIface2) {
1851 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1852 return ImplicitConversionSequence::Better;
1853 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1854 return ImplicitConversionSequence::Worse;
1855 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001856 }
Douglas Gregor14046502008-10-23 00:40:37 +00001857 }
1858
Douglas Gregor0e343382008-10-29 14:50:44 +00001859 // Compare based on reference bindings.
1860 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1861 SCS1.Second == ICK_Derived_To_Base) {
1862 // -- binding of an expression of type C to a reference of type
1863 // B& is better than binding an expression of type C to a
1864 // reference of type A&,
1865 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1866 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1867 if (IsDerivedFrom(ToType1, ToType2))
1868 return ImplicitConversionSequence::Better;
1869 else if (IsDerivedFrom(ToType2, ToType1))
1870 return ImplicitConversionSequence::Worse;
1871 }
1872
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001873 // -- binding of an expression of type B to a reference of type
1874 // A& is better than binding an expression of type C to a
1875 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001876 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1877 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1878 if (IsDerivedFrom(FromType2, FromType1))
1879 return ImplicitConversionSequence::Better;
1880 else if (IsDerivedFrom(FromType1, FromType2))
1881 return ImplicitConversionSequence::Worse;
1882 }
1883 }
1884
1885
1886 // FIXME: conversion of A::* to B::* is better than conversion of
1887 // A::* to C::*,
1888
1889 // FIXME: conversion of B::* to C::* is better than conversion of
1890 // A::* to C::*, and
1891
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001892 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1893 SCS1.Second == ICK_Derived_To_Base) {
1894 // -- conversion of C to B is better than conversion of C to A,
1895 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1896 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1897 if (IsDerivedFrom(ToType1, ToType2))
1898 return ImplicitConversionSequence::Better;
1899 else if (IsDerivedFrom(ToType2, ToType1))
1900 return ImplicitConversionSequence::Worse;
1901 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001902
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001903 // -- conversion of B to A is better than conversion of C to A.
1904 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1905 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1906 if (IsDerivedFrom(FromType2, FromType1))
1907 return ImplicitConversionSequence::Better;
1908 else if (IsDerivedFrom(FromType1, FromType2))
1909 return ImplicitConversionSequence::Worse;
1910 }
1911 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001912
Douglas Gregor14046502008-10-23 00:40:37 +00001913 return ImplicitConversionSequence::Indistinguishable;
1914}
1915
Douglas Gregor81c29152008-10-29 00:13:59 +00001916/// TryCopyInitialization - Try to copy-initialize a value of type
1917/// ToType from the expression From. Return the implicit conversion
1918/// sequence required to pass this argument, which may be a bad
1919/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001920/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redla55834a2009-04-12 17:16:29 +00001921/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1922/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor81c29152008-10-29 00:13:59 +00001923ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001924Sema::TryCopyInitialization(Expr *From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001925 bool SuppressUserConversions, bool ForceRValue) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001926 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001927 ImplicitConversionSequence ICS;
Anders Carlsson8f809f92009-08-27 17:30:43 +00001928 CheckReferenceInit(From, ToType,
1929 SuppressUserConversions,
1930 /*AllowExplicit=*/false,
1931 ForceRValue,
1932 &ICS);
Douglas Gregor81c29152008-10-29 00:13:59 +00001933 return ICS;
1934 } else {
Anders Carlsson6ed4a612009-08-27 17:24:15 +00001935 return TryImplicitConversion(From, ToType,
1936 SuppressUserConversions,
1937 /*AllowExplicit=*/false,
Anders Carlssonfcc53032009-08-27 17:14:02 +00001938 ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001939 }
1940}
1941
Sebastian Redla55834a2009-04-12 17:16:29 +00001942/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1943/// the expression @p From. Returns true (and emits a diagnostic) if there was
1944/// an error, returns false if the initialization succeeded. Elidable should
1945/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1946/// differently in C++0x for this case.
Douglas Gregor81c29152008-10-29 00:13:59 +00001947bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001948 const char* Flavor, bool Elidable) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001949 if (!getLangOptions().CPlusPlus) {
1950 // In C, argument passing is the same as performing an assignment.
1951 QualType FromType = From->getType();
Douglas Gregor144b06c2009-04-29 22:16:16 +00001952
Douglas Gregor81c29152008-10-29 00:13:59 +00001953 AssignConvertType ConvTy =
1954 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor144b06c2009-04-29 22:16:16 +00001955 if (ConvTy != Compatible &&
1956 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1957 ConvTy = Compatible;
1958
Douglas Gregor81c29152008-10-29 00:13:59 +00001959 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1960 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001961 }
Sebastian Redla55834a2009-04-12 17:16:29 +00001962
Chris Lattner271d4c22008-11-24 05:29:24 +00001963 if (ToType->isReferenceType())
Anders Carlsson8f809f92009-08-27 17:30:43 +00001964 return CheckReferenceInit(From, ToType,
1965 /*SuppressUserConversions=*/false,
1966 /*AllowExplicit=*/false,
1967 /*ForceRValue=*/false);
Chris Lattner271d4c22008-11-24 05:29:24 +00001968
Sebastian Redla55834a2009-04-12 17:16:29 +00001969 if (!PerformImplicitConversion(From, ToType, Flavor,
1970 /*AllowExplicit=*/false, Elidable))
Chris Lattner271d4c22008-11-24 05:29:24 +00001971 return false;
Sebastian Redla55834a2009-04-12 17:16:29 +00001972
Chris Lattner271d4c22008-11-24 05:29:24 +00001973 return Diag(From->getSourceRange().getBegin(),
1974 diag::err_typecheck_convert_incompatible)
1975 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001976}
1977
Douglas Gregor5ed15042008-11-18 23:14:02 +00001978/// TryObjectArgumentInitialization - Try to initialize the object
1979/// parameter of the given member function (@c Method) from the
1980/// expression @p From.
1981ImplicitConversionSequence
1982Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1983 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1984 unsigned MethodQuals = Method->getTypeQualifiers();
1985 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1986
1987 // Set up the conversion sequence as a "bad" conversion, to allow us
1988 // to exit early.
1989 ImplicitConversionSequence ICS;
1990 ICS.Standard.setAsIdentityConversion();
1991 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1992
1993 // We need to have an object of class type.
1994 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001995 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001996 FromType = PT->getPointeeType();
1997
1998 assert(FromType->isRecordType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00001999
2000 // The implicit object parmeter is has the type "reference to cv X",
2001 // where X is the class of which the function is a member
2002 // (C++ [over.match.funcs]p4). However, when finding an implicit
2003 // conversion sequence for the argument, we are not allowed to
2004 // create temporaries or perform user-defined conversions
2005 // (C++ [over.match.funcs]p5). We perform a simplified version of
2006 // reference binding here, that allows class rvalues to bind to
2007 // non-constant references.
2008
2009 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2010 // with the implicit object parameter (C++ [over.match.funcs]p5).
2011 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2012 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2013 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2014 return ICS;
2015
2016 // Check that we have either the same type or a derived type. It
2017 // affects the conversion rank.
2018 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2019 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2020 ICS.Standard.Second = ICK_Identity;
2021 else if (IsDerivedFrom(FromType, ClassType))
2022 ICS.Standard.Second = ICK_Derived_To_Base;
2023 else
2024 return ICS;
2025
2026 // Success. Mark this as a reference binding.
2027 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2028 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2029 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2030 ICS.Standard.ReferenceBinding = true;
2031 ICS.Standard.DirectBinding = true;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +00002032 ICS.Standard.RRefBinding = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002033 return ICS;
2034}
2035
2036/// PerformObjectArgumentInitialization - Perform initialization of
2037/// the implicit object parameter for the given Method with the given
2038/// expression.
2039bool
2040Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002041 QualType FromRecordType, DestType;
2042 QualType ImplicitParamRecordType =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002043 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002044
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002045 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002046 FromRecordType = PT->getPointeeType();
2047 DestType = Method->getThisType(Context);
2048 } else {
2049 FromRecordType = From->getType();
2050 DestType = ImplicitParamRecordType;
2051 }
2052
Douglas Gregor5ed15042008-11-18 23:14:02 +00002053 ImplicitConversionSequence ICS
2054 = TryObjectArgumentInitialization(From, Method);
2055 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2056 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002057 diag::err_implicit_object_parameter_init)
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002058 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2059
Douglas Gregor5ed15042008-11-18 23:14:02 +00002060 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002061 CheckDerivedToBaseConversion(FromRecordType,
2062 ImplicitParamRecordType,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002063 From->getSourceRange().getBegin(),
2064 From->getSourceRange()))
2065 return true;
2066
Anders Carlssone25b6cd2009-08-07 18:45:49 +00002067 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2068 /*isLvalue=*/true);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002069 return false;
2070}
2071
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002072/// TryContextuallyConvertToBool - Attempt to contextually convert the
2073/// expression From to bool (C++0x [conv]p3).
2074ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Anders Carlsson6ed4a612009-08-27 17:24:15 +00002075 return TryImplicitConversion(From, Context.BoolTy,
2076 // FIXME: Are these flags correct?
2077 /*SuppressUserConversions=*/false,
2078 /*AllowExplicit=*/true,
2079 /*ForceRValue=*/false);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002080}
2081
2082/// PerformContextuallyConvertToBool - Perform a contextual conversion
2083/// of the expression From to bool (C++0x [conv]p3).
2084bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2085 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2086 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2087 return false;
2088
2089 return Diag(From->getSourceRange().getBegin(),
2090 diag::err_typecheck_bool_condition)
2091 << From->getType() << From->getSourceRange();
2092}
2093
Douglas Gregord2baafd2008-10-21 16:13:35 +00002094/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002095/// candidate functions, using the given function call arguments. If
2096/// @p SuppressUserConversions, then don't allow user-defined
2097/// conversions via constructors or conversion operators.
Sebastian Redla55834a2009-04-12 17:16:29 +00002098/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2099/// hacky way to implement the overloading rules for elidable copy
2100/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregord2baafd2008-10-21 16:13:35 +00002101void
2102Sema::AddOverloadCandidate(FunctionDecl *Function,
2103 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002104 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002105 bool SuppressUserConversions,
2106 bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +00002107{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002108 const FunctionProtoType* Proto
2109 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002110 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00002111 assert(!isa<CXXConversionDecl>(Function) &&
2112 "Use AddConversionCandidate for conversion functions");
Douglas Gregorb60eb752009-06-25 22:08:12 +00002113 assert(!Function->getDescribedFunctionTemplate() &&
2114 "Use AddTemplateOverloadCandidate for function templates");
2115
Douglas Gregor3257fb52008-12-22 05:46:06 +00002116 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002117 if (!isa<CXXConstructorDecl>(Method)) {
2118 // If we get here, it's because we're calling a member function
2119 // that is named without a member access expression (e.g.,
2120 // "this->f") that was either written explicitly or created
2121 // implicitly. This can happen with a qualified call to a member
2122 // function, e.g., X::f(). We use a NULL object as the implied
2123 // object argument (C++ [over.call.func]p3).
2124 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2125 SuppressUserConversions, ForceRValue);
2126 return;
2127 }
2128 // We treat a constructor like a non-member function, since its object
2129 // argument doesn't participate in overload resolution.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002130 }
2131
2132
Douglas Gregord2baafd2008-10-21 16:13:35 +00002133 // Add this candidate
2134 CandidateSet.push_back(OverloadCandidate());
2135 OverloadCandidate& Candidate = CandidateSet.back();
2136 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002137 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002138 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002139 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002140
2141 unsigned NumArgsInProto = Proto->getNumArgs();
2142
2143 // (C++ 13.3.2p2): A candidate function having fewer than m
2144 // parameters is viable only if it has an ellipsis in its parameter
2145 // list (8.3.5).
2146 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2147 Candidate.Viable = false;
2148 return;
2149 }
2150
2151 // (C++ 13.3.2p2): A candidate function having more than m parameters
2152 // is viable only if the (m+1)st parameter has a default argument
2153 // (8.3.6). For the purposes of overload resolution, the
2154 // parameter list is truncated on the right, so that there are
2155 // exactly m parameters.
2156 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2157 if (NumArgs < MinRequiredArgs) {
2158 // Not enough arguments.
2159 Candidate.Viable = false;
2160 return;
2161 }
2162
2163 // Determine the implicit conversion sequences for each of the
2164 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002165 Candidate.Conversions.resize(NumArgs);
2166 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2167 if (ArgIdx < NumArgsInProto) {
2168 // (C++ 13.3.2p3): for F to be a viable function, there shall
2169 // exist for each argument an implicit conversion sequence
2170 // (13.3.3.1) that converts that argument to the corresponding
2171 // parameter of F.
2172 QualType ParamType = Proto->getArgType(ArgIdx);
2173 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002174 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002175 SuppressUserConversions, ForceRValue);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002176 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002177 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002178 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002179 break;
2180 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002181 } else {
2182 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2183 // argument for which there is no corresponding parameter is
2184 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2185 Candidate.Conversions[ArgIdx].ConversionKind
2186 = ImplicitConversionSequence::EllipsisConversion;
2187 }
2188 }
2189}
2190
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002191/// \brief Add all of the function declarations in the given function set to
2192/// the overload canddiate set.
2193void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2194 Expr **Args, unsigned NumArgs,
2195 OverloadCandidateSet& CandidateSet,
2196 bool SuppressUserConversions) {
2197 for (FunctionSet::const_iterator F = Functions.begin(),
2198 FEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00002199 F != FEnd; ++F) {
2200 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
2201 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2202 SuppressUserConversions);
2203 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002204 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2205 /*FIXME: explicit args */false, 0, 0,
2206 Args, NumArgs, CandidateSet,
Douglas Gregor993a0602009-06-27 21:05:07 +00002207 SuppressUserConversions);
2208 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002209}
2210
Douglas Gregor5ed15042008-11-18 23:14:02 +00002211/// AddMethodCandidate - Adds the given C++ member function to the set
2212/// of candidate functions, using the given function call arguments
2213/// and the object argument (@c Object). For example, in a call
2214/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2215/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2216/// allow user-defined conversions via constructors or conversion
Sebastian Redla55834a2009-04-12 17:16:29 +00002217/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2218/// a slightly hacky way to implement the overloading rules for elidable copy
2219/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor5ed15042008-11-18 23:14:02 +00002220void
2221Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2222 Expr **Args, unsigned NumArgs,
2223 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002224 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor5ed15042008-11-18 23:14:02 +00002225{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002226 const FunctionProtoType* Proto
2227 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002228 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redlbd261962009-04-16 17:51:27 +00002229 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor5ed15042008-11-18 23:14:02 +00002230 "Use AddConversionCandidate for conversion functions");
Sebastian Redlbd261962009-04-16 17:51:27 +00002231 assert(!isa<CXXConstructorDecl>(Method) &&
2232 "Use AddOverloadCandidate for constructors");
Douglas Gregor5ed15042008-11-18 23:14:02 +00002233
2234 // Add this candidate
2235 CandidateSet.push_back(OverloadCandidate());
2236 OverloadCandidate& Candidate = CandidateSet.back();
2237 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002238 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002239 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002240
2241 unsigned NumArgsInProto = Proto->getNumArgs();
2242
2243 // (C++ 13.3.2p2): A candidate function having fewer than m
2244 // parameters is viable only if it has an ellipsis in its parameter
2245 // list (8.3.5).
2246 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2247 Candidate.Viable = false;
2248 return;
2249 }
2250
2251 // (C++ 13.3.2p2): A candidate function having more than m parameters
2252 // is viable only if the (m+1)st parameter has a default argument
2253 // (8.3.6). For the purposes of overload resolution, the
2254 // parameter list is truncated on the right, so that there are
2255 // exactly m parameters.
2256 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2257 if (NumArgs < MinRequiredArgs) {
2258 // Not enough arguments.
2259 Candidate.Viable = false;
2260 return;
2261 }
2262
2263 Candidate.Viable = true;
2264 Candidate.Conversions.resize(NumArgs + 1);
2265
Douglas Gregor3257fb52008-12-22 05:46:06 +00002266 if (Method->isStatic() || !Object)
2267 // The implicit object argument is ignored.
2268 Candidate.IgnoreObjectArgument = true;
2269 else {
2270 // Determine the implicit conversion sequence for the object
2271 // parameter.
2272 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2273 if (Candidate.Conversions[0].ConversionKind
2274 == ImplicitConversionSequence::BadConversion) {
2275 Candidate.Viable = false;
2276 return;
2277 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002278 }
2279
2280 // Determine the implicit conversion sequences for each of the
2281 // arguments.
2282 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2283 if (ArgIdx < NumArgsInProto) {
2284 // (C++ 13.3.2p3): for F to be a viable function, there shall
2285 // exist for each argument an implicit conversion sequence
2286 // (13.3.3.1) that converts that argument to the corresponding
2287 // parameter of F.
2288 QualType ParamType = Proto->getArgType(ArgIdx);
2289 Candidate.Conversions[ArgIdx + 1]
2290 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002291 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002292 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2293 == ImplicitConversionSequence::BadConversion) {
2294 Candidate.Viable = false;
2295 break;
2296 }
2297 } else {
2298 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2299 // argument for which there is no corresponding parameter is
2300 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2301 Candidate.Conversions[ArgIdx + 1].ConversionKind
2302 = ImplicitConversionSequence::EllipsisConversion;
2303 }
2304 }
2305}
2306
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002307/// \brief Add a C++ member function template as a candidate to the candidate
2308/// set, using template argument deduction to produce an appropriate member
2309/// function template specialization.
2310void
2311Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2312 bool HasExplicitTemplateArgs,
2313 const TemplateArgument *ExplicitTemplateArgs,
2314 unsigned NumExplicitTemplateArgs,
2315 Expr *Object, Expr **Args, unsigned NumArgs,
2316 OverloadCandidateSet& CandidateSet,
2317 bool SuppressUserConversions,
2318 bool ForceRValue) {
2319 // C++ [over.match.funcs]p7:
2320 // In each case where a candidate is a function template, candidate
2321 // function template specializations are generated using template argument
2322 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2323 // candidate functions in the usual way.113) A given name can refer to one
2324 // or more function templates and also to a set of overloaded non-template
2325 // functions. In such a case, the candidate functions generated from each
2326 // function template are combined with the set of non-template candidate
2327 // functions.
2328 TemplateDeductionInfo Info(Context);
2329 FunctionDecl *Specialization = 0;
2330 if (TemplateDeductionResult Result
2331 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2332 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2333 Args, NumArgs, Specialization, Info)) {
2334 // FIXME: Record what happened with template argument deduction, so
2335 // that we can give the user a beautiful diagnostic.
2336 (void)Result;
2337 return;
2338 }
2339
2340 // Add the function template specialization produced by template argument
2341 // deduction as a candidate.
2342 assert(Specialization && "Missing member function template specialization?");
2343 assert(isa<CXXMethodDecl>(Specialization) &&
2344 "Specialization is not a member function?");
2345 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
2346 CandidateSet, SuppressUserConversions, ForceRValue);
2347}
2348
Douglas Gregor8c860df2009-08-21 23:19:43 +00002349/// \brief Add a C++ function template specialization as a candidate
2350/// in the candidate set, using template argument deduction to produce
2351/// an appropriate function template specialization.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002352void
2353Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002354 bool HasExplicitTemplateArgs,
2355 const TemplateArgument *ExplicitTemplateArgs,
2356 unsigned NumExplicitTemplateArgs,
Douglas Gregorb60eb752009-06-25 22:08:12 +00002357 Expr **Args, unsigned NumArgs,
2358 OverloadCandidateSet& CandidateSet,
2359 bool SuppressUserConversions,
2360 bool ForceRValue) {
2361 // C++ [over.match.funcs]p7:
2362 // In each case where a candidate is a function template, candidate
2363 // function template specializations are generated using template argument
2364 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2365 // candidate functions in the usual way.113) A given name can refer to one
2366 // or more function templates and also to a set of overloaded non-template
2367 // functions. In such a case, the candidate functions generated from each
2368 // function template are combined with the set of non-template candidate
2369 // functions.
2370 TemplateDeductionInfo Info(Context);
2371 FunctionDecl *Specialization = 0;
2372 if (TemplateDeductionResult Result
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002373 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2374 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2375 Args, NumArgs, Specialization, Info)) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00002376 // FIXME: Record what happened with template argument deduction, so
2377 // that we can give the user a beautiful diagnostic.
2378 (void)Result;
2379 return;
2380 }
2381
2382 // Add the function template specialization produced by template argument
2383 // deduction as a candidate.
2384 assert(Specialization && "Missing function template specialization?");
2385 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2386 SuppressUserConversions, ForceRValue);
2387}
2388
Douglas Gregor60714f92008-11-07 22:36:19 +00002389/// AddConversionCandidate - Add a C++ conversion function as a
2390/// candidate in the candidate set (C++ [over.match.conv],
2391/// C++ [over.match.copy]). From is the expression we're converting from,
2392/// and ToType is the type that we're eventually trying to convert to
2393/// (which may or may not be the same type as the type that the
2394/// conversion function produces).
2395void
2396Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2397 Expr *From, QualType ToType,
2398 OverloadCandidateSet& CandidateSet) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002399 assert(!Conversion->getDescribedFunctionTemplate() &&
2400 "Conversion function templates use AddTemplateConversionCandidate");
2401
Douglas Gregor60714f92008-11-07 22:36:19 +00002402 // Add this candidate
2403 CandidateSet.push_back(OverloadCandidate());
2404 OverloadCandidate& Candidate = CandidateSet.back();
2405 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002406 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002407 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002408 Candidate.FinalConversion.setAsIdentityConversion();
2409 Candidate.FinalConversion.FromTypePtr
2410 = Conversion->getConversionType().getAsOpaquePtr();
2411 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2412
Douglas Gregor5ed15042008-11-18 23:14:02 +00002413 // Determine the implicit conversion sequence for the implicit
2414 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002415 Candidate.Viable = true;
2416 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002417 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002418
Douglas Gregor60714f92008-11-07 22:36:19 +00002419 if (Candidate.Conversions[0].ConversionKind
2420 == ImplicitConversionSequence::BadConversion) {
2421 Candidate.Viable = false;
2422 return;
2423 }
2424
2425 // To determine what the conversion from the result of calling the
2426 // conversion function to the type we're eventually trying to
2427 // convert to (ToType), we need to synthesize a call to the
2428 // conversion function and attempt copy initialization from it. This
2429 // makes sure that we get the right semantics with respect to
2430 // lvalues/rvalues and the type. Fortunately, we can allocate this
2431 // call on the stack and we don't need its arguments to be
2432 // well-formed.
2433 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2434 SourceLocation());
2435 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002436 CastExpr::CK_Unknown,
Douglas Gregor70d26122008-11-12 17:17:38 +00002437 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002438
2439 // Note that it is safe to allocate CallExpr on the stack here because
2440 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2441 // allocator).
2442 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002443 Conversion->getConversionType().getNonReferenceType(),
2444 SourceLocation());
Anders Carlsson06386552009-08-27 17:18:13 +00002445 ImplicitConversionSequence ICS =
2446 TryCopyInitialization(&Call, ToType,
2447 /*SuppressUserConversions=*/true,
2448 /*ForceRValue=*/false);
2449
Douglas Gregor60714f92008-11-07 22:36:19 +00002450 switch (ICS.ConversionKind) {
2451 case ImplicitConversionSequence::StandardConversion:
2452 Candidate.FinalConversion = ICS.Standard;
2453 break;
2454
2455 case ImplicitConversionSequence::BadConversion:
2456 Candidate.Viable = false;
2457 break;
2458
2459 default:
2460 assert(false &&
2461 "Can only end up with a standard conversion sequence or failure");
2462 }
2463}
2464
Douglas Gregor8c860df2009-08-21 23:19:43 +00002465/// \brief Adds a conversion function template specialization
2466/// candidate to the overload set, using template argument deduction
2467/// to deduce the template arguments of the conversion function
2468/// template from the type that we are converting to (C++
2469/// [temp.deduct.conv]).
2470void
2471Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2472 Expr *From, QualType ToType,
2473 OverloadCandidateSet &CandidateSet) {
2474 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2475 "Only conversion function templates permitted here");
2476
2477 TemplateDeductionInfo Info(Context);
2478 CXXConversionDecl *Specialization = 0;
2479 if (TemplateDeductionResult Result
2480 = DeduceTemplateArguments(FunctionTemplate, ToType,
2481 Specialization, Info)) {
2482 // FIXME: Record what happened with template argument deduction, so
2483 // that we can give the user a beautiful diagnostic.
2484 (void)Result;
2485 return;
2486 }
2487
2488 // Add the conversion function template specialization produced by
2489 // template argument deduction as a candidate.
2490 assert(Specialization && "Missing function template specialization?");
2491 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2492}
2493
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002494/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2495/// converts the given @c Object to a function pointer via the
2496/// conversion function @c Conversion, and then attempts to call it
2497/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2498/// the type of function that we'll eventually be calling.
2499void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002500 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002501 Expr *Object, Expr **Args, unsigned NumArgs,
2502 OverloadCandidateSet& CandidateSet) {
2503 CandidateSet.push_back(OverloadCandidate());
2504 OverloadCandidate& Candidate = CandidateSet.back();
2505 Candidate.Function = 0;
2506 Candidate.Surrogate = Conversion;
2507 Candidate.Viable = true;
2508 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002509 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002510 Candidate.Conversions.resize(NumArgs + 1);
2511
2512 // Determine the implicit conversion sequence for the implicit
2513 // object parameter.
2514 ImplicitConversionSequence ObjectInit
2515 = TryObjectArgumentInitialization(Object, Conversion);
2516 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2517 Candidate.Viable = false;
2518 return;
2519 }
2520
2521 // The first conversion is actually a user-defined conversion whose
2522 // first conversion is ObjectInit's standard conversion (which is
2523 // effectively a reference binding). Record it as such.
2524 Candidate.Conversions[0].ConversionKind
2525 = ImplicitConversionSequence::UserDefinedConversion;
2526 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2527 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2528 Candidate.Conversions[0].UserDefined.After
2529 = Candidate.Conversions[0].UserDefined.Before;
2530 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2531
2532 // Find the
2533 unsigned NumArgsInProto = Proto->getNumArgs();
2534
2535 // (C++ 13.3.2p2): A candidate function having fewer than m
2536 // parameters is viable only if it has an ellipsis in its parameter
2537 // list (8.3.5).
2538 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2539 Candidate.Viable = false;
2540 return;
2541 }
2542
2543 // Function types don't have any default arguments, so just check if
2544 // we have enough arguments.
2545 if (NumArgs < NumArgsInProto) {
2546 // Not enough arguments.
2547 Candidate.Viable = false;
2548 return;
2549 }
2550
2551 // Determine the implicit conversion sequences for each of the
2552 // arguments.
2553 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2554 if (ArgIdx < NumArgsInProto) {
2555 // (C++ 13.3.2p3): for F to be a viable function, there shall
2556 // exist for each argument an implicit conversion sequence
2557 // (13.3.3.1) that converts that argument to the corresponding
2558 // parameter of F.
2559 QualType ParamType = Proto->getArgType(ArgIdx);
2560 Candidate.Conversions[ArgIdx + 1]
2561 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson06386552009-08-27 17:18:13 +00002562 /*SuppressUserConversions=*/false,
2563 /*ForceRValue=*/false);
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002564 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2565 == ImplicitConversionSequence::BadConversion) {
2566 Candidate.Viable = false;
2567 break;
2568 }
2569 } else {
2570 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2571 // argument for which there is no corresponding parameter is
2572 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2573 Candidate.Conversions[ArgIdx + 1].ConversionKind
2574 = ImplicitConversionSequence::EllipsisConversion;
2575 }
2576 }
2577}
2578
Mike Stumpe127ae32009-05-16 07:39:55 +00002579// FIXME: This will eventually be removed, once we've migrated all of the
2580// operator overloading logic over to the scheme used by binary operators, which
2581// works for template instantiation.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002582void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002583 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002584 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002585 OverloadCandidateSet& CandidateSet,
2586 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002587
2588 FunctionSet Functions;
2589
2590 QualType T1 = Args[0]->getType();
2591 QualType T2;
2592 if (NumArgs > 1)
2593 T2 = Args[1]->getType();
2594
2595 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregorde72f3e2009-05-19 00:01:19 +00002596 if (S)
2597 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002598 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2599 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2600 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2601 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2602}
2603
2604/// \brief Add overload candidates for overloaded operators that are
2605/// member functions.
2606///
2607/// Add the overloaded operator candidates that are member functions
2608/// for the operator Op that was used in an operator expression such
2609/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2610/// CandidateSet will store the added overload candidates. (C++
2611/// [over.match.oper]).
2612void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2613 SourceLocation OpLoc,
2614 Expr **Args, unsigned NumArgs,
2615 OverloadCandidateSet& CandidateSet,
2616 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002617 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2618
2619 // C++ [over.match.oper]p3:
2620 // For a unary operator @ with an operand of a type whose
2621 // cv-unqualified version is T1, and for a binary operator @ with
2622 // a left operand of a type whose cv-unqualified version is T1 and
2623 // a right operand of a type whose cv-unqualified version is T2,
2624 // three sets of candidate functions, designated member
2625 // candidates, non-member candidates and built-in candidates, are
2626 // constructed as follows:
2627 QualType T1 = Args[0]->getType();
2628 QualType T2;
2629 if (NumArgs > 1)
2630 T2 = Args[1]->getType();
2631
2632 // -- If T1 is a class type, the set of member candidates is the
2633 // result of the qualified lookup of T1::operator@
2634 // (13.3.1.1.1); otherwise, the set of member candidates is
2635 // empty.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002636 // FIXME: Lookup in base classes, too!
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002637 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002638 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002639 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002640 Oper != OperEnd; ++Oper)
2641 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2642 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002643 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002644 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002645}
2646
Douglas Gregor70d26122008-11-12 17:17:38 +00002647/// AddBuiltinCandidate - Add a candidate for a built-in
2648/// operator. ResultTy and ParamTys are the result and parameter types
2649/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002650/// arguments being passed to the candidate. IsAssignmentOperator
2651/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002652/// operator. NumContextualBoolArguments is the number of arguments
2653/// (at the beginning of the argument list) that will be contextually
2654/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002655void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2656 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002657 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002658 bool IsAssignmentOperator,
2659 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002660 // Add this candidate
2661 CandidateSet.push_back(OverloadCandidate());
2662 OverloadCandidate& Candidate = CandidateSet.back();
2663 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002664 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002665 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002666 Candidate.BuiltinTypes.ResultTy = ResultTy;
2667 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2668 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2669
2670 // Determine the implicit conversion sequences for each of the
2671 // arguments.
2672 Candidate.Viable = true;
2673 Candidate.Conversions.resize(NumArgs);
2674 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002675 // C++ [over.match.oper]p4:
2676 // For the built-in assignment operators, conversions of the
2677 // left operand are restricted as follows:
2678 // -- no temporaries are introduced to hold the left operand, and
2679 // -- no user-defined conversions are applied to the left
2680 // operand to achieve a type match with the left-most
2681 // parameter of a built-in candidate.
2682 //
2683 // We block these conversions by turning off user-defined
2684 // conversions, since that is the only way that initialization of
2685 // a reference to a non-class type can occur from something that
2686 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002687 if (ArgIdx < NumContextualBoolArguments) {
2688 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2689 "Contextual conversion to bool requires bool type");
2690 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2691 } else {
2692 Candidate.Conversions[ArgIdx]
2693 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson06386552009-08-27 17:18:13 +00002694 ArgIdx == 0 && IsAssignmentOperator,
2695 /*ForceRValue=*/false);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002696 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002697 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002698 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002699 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002700 break;
2701 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002702 }
2703}
2704
2705/// BuiltinCandidateTypeSet - A set of types that will be used for the
2706/// candidate operator functions for built-in operators (C++
2707/// [over.built]). The types are separated into pointer types and
2708/// enumeration types.
2709class BuiltinCandidateTypeSet {
2710 /// TypeSet - A set of types.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002711 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002712
2713 /// PointerTypes - The set of pointer types that will be used in the
2714 /// built-in candidates.
2715 TypeSet PointerTypes;
2716
Sebastian Redl674d1b72009-04-19 21:53:20 +00002717 /// MemberPointerTypes - The set of member pointer types that will be
2718 /// used in the built-in candidates.
2719 TypeSet MemberPointerTypes;
2720
Douglas Gregor70d26122008-11-12 17:17:38 +00002721 /// EnumerationTypes - The set of enumeration types that will be
2722 /// used in the built-in candidates.
2723 TypeSet EnumerationTypes;
2724
Douglas Gregorb35c7992009-08-24 15:23:48 +00002725 /// Sema - The semantic analysis instance where we are building the
2726 /// candidate type set.
2727 Sema &SemaRef;
2728
Douglas Gregor70d26122008-11-12 17:17:38 +00002729 /// Context - The AST context in which we will build the type sets.
2730 ASTContext &Context;
2731
Sebastian Redl674d1b72009-04-19 21:53:20 +00002732 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2733 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002734
2735public:
2736 /// iterator - Iterates through the types that are part of the set.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002737 typedef TypeSet::iterator iterator;
Douglas Gregor70d26122008-11-12 17:17:38 +00002738
Douglas Gregorb35c7992009-08-24 15:23:48 +00002739 BuiltinCandidateTypeSet(Sema &SemaRef)
2740 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregor70d26122008-11-12 17:17:38 +00002741
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002742 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2743 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002744
2745 /// pointer_begin - First pointer type found;
2746 iterator pointer_begin() { return PointerTypes.begin(); }
2747
Sebastian Redl674d1b72009-04-19 21:53:20 +00002748 /// pointer_end - Past the last pointer type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002749 iterator pointer_end() { return PointerTypes.end(); }
2750
Sebastian Redl674d1b72009-04-19 21:53:20 +00002751 /// member_pointer_begin - First member pointer type found;
2752 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2753
2754 /// member_pointer_end - Past the last member pointer type found;
2755 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2756
Douglas Gregor70d26122008-11-12 17:17:38 +00002757 /// enumeration_begin - First enumeration type found;
2758 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2759
Sebastian Redl674d1b72009-04-19 21:53:20 +00002760 /// enumeration_end - Past the last enumeration type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002761 iterator enumeration_end() { return EnumerationTypes.end(); }
2762};
2763
Sebastian Redl674d1b72009-04-19 21:53:20 +00002764/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregor70d26122008-11-12 17:17:38 +00002765/// the set of pointer types along with any more-qualified variants of
2766/// that type. For example, if @p Ty is "int const *", this routine
2767/// will add "int const *", "int const volatile *", "int const
2768/// restrict *", and "int const volatile restrict *" to the set of
2769/// pointer types. Returns true if the add of @p Ty itself succeeded,
2770/// false otherwise.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002771bool
2772BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002773 // Insert this type.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002774 if (!PointerTypes.insert(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002775 return false;
2776
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002777 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002778 QualType PointeeTy = PointerTy->getPointeeType();
2779 // FIXME: Optimize this so that we don't keep trying to add the same types.
2780
Mike Stumpe127ae32009-05-16 07:39:55 +00002781 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2782 // pointer conversions that don't cast away constness?
Douglas Gregor70d26122008-11-12 17:17:38 +00002783 if (!PointeeTy.isConstQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002784 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002785 (Context.getPointerType(PointeeTy.withConst()));
2786 if (!PointeeTy.isVolatileQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002787 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002788 (Context.getPointerType(PointeeTy.withVolatile()));
2789 if (!PointeeTy.isRestrictQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002790 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002791 (Context.getPointerType(PointeeTy.withRestrict()));
2792 }
2793
2794 return true;
2795}
2796
Sebastian Redl674d1b72009-04-19 21:53:20 +00002797/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2798/// to the set of pointer types along with any more-qualified variants of
2799/// that type. For example, if @p Ty is "int const *", this routine
2800/// will add "int const *", "int const volatile *", "int const
2801/// restrict *", and "int const volatile restrict *" to the set of
2802/// pointer types. Returns true if the add of @p Ty itself succeeded,
2803/// false otherwise.
2804bool
2805BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2806 QualType Ty) {
2807 // Insert this type.
2808 if (!MemberPointerTypes.insert(Ty))
2809 return false;
2810
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002811 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl674d1b72009-04-19 21:53:20 +00002812 QualType PointeeTy = PointerTy->getPointeeType();
2813 const Type *ClassTy = PointerTy->getClass();
2814 // FIXME: Optimize this so that we don't keep trying to add the same types.
2815
2816 if (!PointeeTy.isConstQualified())
2817 AddMemberPointerWithMoreQualifiedTypeVariants
2818 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2819 if (!PointeeTy.isVolatileQualified())
2820 AddMemberPointerWithMoreQualifiedTypeVariants
2821 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2822 if (!PointeeTy.isRestrictQualified())
2823 AddMemberPointerWithMoreQualifiedTypeVariants
2824 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2825 }
2826
2827 return true;
2828}
2829
Douglas Gregor70d26122008-11-12 17:17:38 +00002830/// AddTypesConvertedFrom - Add each of the types to which the type @p
2831/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl674d1b72009-04-19 21:53:20 +00002832/// primarily interested in pointer types and enumeration types. We also
2833/// take member pointer types, for the conditional operator.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002834/// AllowUserConversions is true if we should look at the conversion
2835/// functions of a class type, and AllowExplicitConversions if we
2836/// should also include the explicit conversion functions of a class
2837/// type.
2838void
2839BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2840 bool AllowUserConversions,
2841 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002842 // Only deal with canonical types.
2843 Ty = Context.getCanonicalType(Ty);
2844
2845 // Look through reference types; they aren't part of the type of an
2846 // expression for the purposes of conversions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002847 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregor70d26122008-11-12 17:17:38 +00002848 Ty = RefTy->getPointeeType();
2849
2850 // We don't care about qualifiers on the type.
2851 Ty = Ty.getUnqualifiedType();
2852
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002853 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002854 QualType PointeeTy = PointerTy->getPointeeType();
2855
2856 // Insert our type, and its more-qualified variants, into the set
2857 // of types.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002858 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002859 return;
2860
2861 // Add 'cv void*' to our set of types.
2862 if (!Ty->isVoidType()) {
2863 QualType QualVoid
2864 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl674d1b72009-04-19 21:53:20 +00002865 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregor70d26122008-11-12 17:17:38 +00002866 }
2867
2868 // If this is a pointer to a class type, add pointers to its bases
2869 // (with the same level of cv-qualification as the original
2870 // derived class, of course).
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002871 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002872 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2873 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2874 Base != ClassDecl->bases_end(); ++Base) {
2875 QualType BaseTy = Context.getCanonicalType(Base->getType());
2876 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2877
2878 // Add the pointer type, recursively, so that we get all of
2879 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002880 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002881 }
2882 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00002883 } else if (Ty->isMemberPointerType()) {
2884 // Member pointers are far easier, since the pointee can't be converted.
2885 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2886 return;
Douglas Gregor70d26122008-11-12 17:17:38 +00002887 } else if (Ty->isEnumeralType()) {
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002888 EnumerationTypes.insert(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002889 } else if (AllowUserConversions) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002890 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorb35c7992009-08-24 15:23:48 +00002891 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2892 // No conversion functions in incomplete types.
2893 return;
2894 }
2895
Douglas Gregor70d26122008-11-12 17:17:38 +00002896 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2897 // FIXME: Visit conversion functions in the base classes, too.
2898 OverloadedFunctionDecl *Conversions
2899 = ClassDecl->getConversionFunctions();
2900 for (OverloadedFunctionDecl::function_iterator Func
2901 = Conversions->function_begin();
2902 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002903 CXXConversionDecl *Conv;
2904 FunctionTemplateDecl *ConvTemplate;
2905 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2906
2907 // Skip conversion function templates; they don't tell us anything
2908 // about which builtin types we can convert to.
2909 if (ConvTemplate)
2910 continue;
2911
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002912 if (AllowExplicitConversions || !Conv->isExplicit())
2913 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002914 }
2915 }
2916 }
2917}
2918
Douglas Gregor9a375942009-08-24 13:43:27 +00002919/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2920/// the volatile- and non-volatile-qualified assignment operators for the
2921/// given type to the candidate set.
2922static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2923 QualType T,
2924 Expr **Args,
2925 unsigned NumArgs,
2926 OverloadCandidateSet &CandidateSet) {
2927 QualType ParamTypes[2];
2928
2929 // T& operator=(T&, T)
2930 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2931 ParamTypes[1] = T;
2932 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2933 /*IsAssignmentOperator=*/true);
2934
2935 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2936 // volatile T& operator=(volatile T&, T)
2937 ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
2938 ParamTypes[1] = T;
2939 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2940 /*IsAssignmentOperator=*/true);
2941 }
2942}
2943
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002944/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2945/// operator overloads to the candidate set (C++ [over.built]), based
2946/// on the operator @p Op and the arguments given. For example, if the
2947/// operator is a binary '+', this routine might add "int
2948/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002949void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002950Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2951 Expr **Args, unsigned NumArgs,
2952 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002953 // The set of "promoted arithmetic types", which are the arithmetic
2954 // types are that preserved by promotion (C++ [over.built]p2). Note
2955 // that the first few of these types are the promoted integral
2956 // types; these types need to be first.
2957 // FIXME: What about complex?
2958 const unsigned FirstIntegralType = 0;
2959 const unsigned LastIntegralType = 13;
2960 const unsigned FirstPromotedIntegralType = 7,
2961 LastPromotedIntegralType = 13;
2962 const unsigned FirstPromotedArithmeticType = 7,
2963 LastPromotedArithmeticType = 16;
2964 const unsigned NumArithmeticTypes = 16;
2965 QualType ArithmeticTypes[NumArithmeticTypes] = {
Alisdair Meredith2bcacb62009-07-14 06:30:34 +00002966 Context.BoolTy, Context.CharTy, Context.WCharTy,
Douglas Gregor9a375942009-08-24 13:43:27 +00002967// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregor70d26122008-11-12 17:17:38 +00002968 Context.SignedCharTy, Context.ShortTy,
2969 Context.UnsignedCharTy, Context.UnsignedShortTy,
2970 Context.IntTy, Context.LongTy, Context.LongLongTy,
2971 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2972 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2973 };
2974
2975 // Find all of the types that the arguments can convert to, but only
2976 // if the operator we're looking at has built-in operator candidates
2977 // that make use of these types.
Douglas Gregorb35c7992009-08-24 15:23:48 +00002978 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregor70d26122008-11-12 17:17:38 +00002979 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2980 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002981 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002982 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002983 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redlbd261962009-04-16 17:51:27 +00002984 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002985 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002986 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2987 true,
2988 (Op == OO_Exclaim ||
2989 Op == OO_AmpAmp ||
2990 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002991 }
2992
2993 bool isComparison = false;
2994 switch (Op) {
2995 case OO_None:
2996 case NUM_OVERLOADED_OPERATORS:
2997 assert(false && "Expected an overloaded operator");
2998 break;
2999
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003000 case OO_Star: // '*' is either unary or binary
3001 if (NumArgs == 1)
3002 goto UnaryStar;
3003 else
3004 goto BinaryStar;
3005 break;
3006
3007 case OO_Plus: // '+' is either unary or binary
3008 if (NumArgs == 1)
3009 goto UnaryPlus;
3010 else
3011 goto BinaryPlus;
3012 break;
3013
3014 case OO_Minus: // '-' is either unary or binary
3015 if (NumArgs == 1)
3016 goto UnaryMinus;
3017 else
3018 goto BinaryMinus;
3019 break;
3020
3021 case OO_Amp: // '&' is either unary or binary
3022 if (NumArgs == 1)
3023 goto UnaryAmp;
3024 else
3025 goto BinaryAmp;
3026
3027 case OO_PlusPlus:
3028 case OO_MinusMinus:
3029 // C++ [over.built]p3:
3030 //
3031 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3032 // is either volatile or empty, there exist candidate operator
3033 // functions of the form
3034 //
3035 // VQ T& operator++(VQ T&);
3036 // T operator++(VQ T&, int);
3037 //
3038 // C++ [over.built]p4:
3039 //
3040 // For every pair (T, VQ), where T is an arithmetic type other
3041 // than bool, and VQ is either volatile or empty, there exist
3042 // candidate operator functions of the form
3043 //
3044 // VQ T& operator--(VQ T&);
3045 // T operator--(VQ T&, int);
3046 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
3047 Arith < NumArithmeticTypes; ++Arith) {
3048 QualType ArithTy = ArithmeticTypes[Arith];
3049 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00003050 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003051
3052 // Non-volatile version.
3053 if (NumArgs == 1)
3054 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3055 else
3056 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3057
3058 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003059 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003060 if (NumArgs == 1)
3061 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3062 else
3063 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3064 }
3065
3066 // C++ [over.built]p5:
3067 //
3068 // For every pair (T, VQ), where T is a cv-qualified or
3069 // cv-unqualified object type, and VQ is either volatile or
3070 // empty, there exist candidate operator functions of the form
3071 //
3072 // T*VQ& operator++(T*VQ&);
3073 // T*VQ& operator--(T*VQ&);
3074 // T* operator++(T*VQ&, int);
3075 // T* operator--(T*VQ&, int);
3076 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3077 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3078 // Skip pointer types that aren't pointers to object types.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003079 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003080 continue;
3081
3082 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003083 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003084 };
3085
3086 // Without volatile
3087 if (NumArgs == 1)
3088 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3089 else
3090 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3091
3092 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3093 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00003094 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003095 if (NumArgs == 1)
3096 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3097 else
3098 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3099 }
3100 }
3101 break;
3102
3103 UnaryStar:
3104 // C++ [over.built]p6:
3105 // For every cv-qualified or cv-unqualified object type T, there
3106 // exist candidate operator functions of the form
3107 //
3108 // T& operator*(T*);
3109 //
3110 // C++ [over.built]p7:
3111 // For every function type T, there exist candidate operator
3112 // functions of the form
3113 // T& operator*(T*);
3114 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3115 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3116 QualType ParamTy = *Ptr;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003117 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003118 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003119 &ParamTy, Args, 1, CandidateSet);
3120 }
3121 break;
3122
3123 UnaryPlus:
3124 // C++ [over.built]p8:
3125 // For every type T, there exist candidate operator functions of
3126 // the form
3127 //
3128 // T* operator+(T*);
3129 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3130 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3131 QualType ParamTy = *Ptr;
3132 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3133 }
3134
3135 // Fall through
3136
3137 UnaryMinus:
3138 // C++ [over.built]p9:
3139 // For every promoted arithmetic type T, there exist candidate
3140 // operator functions of the form
3141 //
3142 // T operator+(T);
3143 // T operator-(T);
3144 for (unsigned Arith = FirstPromotedArithmeticType;
3145 Arith < LastPromotedArithmeticType; ++Arith) {
3146 QualType ArithTy = ArithmeticTypes[Arith];
3147 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3148 }
3149 break;
3150
3151 case OO_Tilde:
3152 // C++ [over.built]p10:
3153 // For every promoted integral type T, there exist candidate
3154 // operator functions of the form
3155 //
3156 // T operator~(T);
3157 for (unsigned Int = FirstPromotedIntegralType;
3158 Int < LastPromotedIntegralType; ++Int) {
3159 QualType IntTy = ArithmeticTypes[Int];
3160 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3161 }
3162 break;
3163
Douglas Gregor70d26122008-11-12 17:17:38 +00003164 case OO_New:
3165 case OO_Delete:
3166 case OO_Array_New:
3167 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00003168 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003169 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00003170 break;
3171
3172 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003173 UnaryAmp:
3174 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00003175 // C++ [over.match.oper]p3:
3176 // -- For the operator ',', the unary operator '&', or the
3177 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00003178 break;
3179
Douglas Gregor9a375942009-08-24 13:43:27 +00003180 case OO_EqualEqual:
3181 case OO_ExclaimEqual:
3182 // C++ [over.match.oper]p16:
3183 // For every pointer to member type T, there exist candidate operator
3184 // functions of the form
3185 //
3186 // bool operator==(T,T);
3187 // bool operator!=(T,T);
3188 for (BuiltinCandidateTypeSet::iterator
3189 MemPtr = CandidateTypes.member_pointer_begin(),
3190 MemPtrEnd = CandidateTypes.member_pointer_end();
3191 MemPtr != MemPtrEnd;
3192 ++MemPtr) {
3193 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3194 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3195 }
3196
3197 // Fall through
3198
Douglas Gregor70d26122008-11-12 17:17:38 +00003199 case OO_Less:
3200 case OO_Greater:
3201 case OO_LessEqual:
3202 case OO_GreaterEqual:
Douglas Gregor70d26122008-11-12 17:17:38 +00003203 // C++ [over.built]p15:
3204 //
3205 // For every pointer or enumeration type T, there exist
3206 // candidate operator functions of the form
3207 //
3208 // bool operator<(T, T);
3209 // bool operator>(T, T);
3210 // bool operator<=(T, T);
3211 // bool operator>=(T, T);
3212 // bool operator==(T, T);
3213 // bool operator!=(T, T);
3214 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3215 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3216 QualType ParamTypes[2] = { *Ptr, *Ptr };
3217 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3218 }
3219 for (BuiltinCandidateTypeSet::iterator Enum
3220 = CandidateTypes.enumeration_begin();
3221 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3222 QualType ParamTypes[2] = { *Enum, *Enum };
3223 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3224 }
3225
3226 // Fall through.
3227 isComparison = true;
3228
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003229 BinaryPlus:
3230 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00003231 if (!isComparison) {
3232 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3233
3234 // C++ [over.built]p13:
3235 //
3236 // For every cv-qualified or cv-unqualified object type T
3237 // there exist candidate operator functions of the form
3238 //
3239 // T* operator+(T*, ptrdiff_t);
3240 // T& operator[](T*, ptrdiff_t); [BELOW]
3241 // T* operator-(T*, ptrdiff_t);
3242 // T* operator+(ptrdiff_t, T*);
3243 // T& operator[](ptrdiff_t, T*); [BELOW]
3244 //
3245 // C++ [over.built]p14:
3246 //
3247 // For every T, where T is a pointer to object type, there
3248 // exist candidate operator functions of the form
3249 //
3250 // ptrdiff_t operator-(T, T);
3251 for (BuiltinCandidateTypeSet::iterator Ptr
3252 = CandidateTypes.pointer_begin();
3253 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3254 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3255
3256 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3257 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3258
3259 if (Op == OO_Plus) {
3260 // T* operator+(ptrdiff_t, T*);
3261 ParamTypes[0] = ParamTypes[1];
3262 ParamTypes[1] = *Ptr;
3263 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3264 } else {
3265 // ptrdiff_t operator-(T, T);
3266 ParamTypes[1] = *Ptr;
3267 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3268 Args, 2, CandidateSet);
3269 }
3270 }
3271 }
3272 // Fall through
3273
Douglas Gregor70d26122008-11-12 17:17:38 +00003274 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003275 BinaryStar:
Sebastian Redlbd261962009-04-16 17:51:27 +00003276 Conditional:
Douglas Gregor70d26122008-11-12 17:17:38 +00003277 // C++ [over.built]p12:
3278 //
3279 // For every pair of promoted arithmetic types L and R, there
3280 // exist candidate operator functions of the form
3281 //
3282 // LR operator*(L, R);
3283 // LR operator/(L, R);
3284 // LR operator+(L, R);
3285 // LR operator-(L, R);
3286 // bool operator<(L, R);
3287 // bool operator>(L, R);
3288 // bool operator<=(L, R);
3289 // bool operator>=(L, R);
3290 // bool operator==(L, R);
3291 // bool operator!=(L, R);
3292 //
3293 // where LR is the result of the usual arithmetic conversions
3294 // between types L and R.
Sebastian Redlbd261962009-04-16 17:51:27 +00003295 //
3296 // C++ [over.built]p24:
3297 //
3298 // For every pair of promoted arithmetic types L and R, there exist
3299 // candidate operator functions of the form
3300 //
3301 // LR operator?(bool, L, R);
3302 //
3303 // where LR is the result of the usual arithmetic conversions
3304 // between types L and R.
3305 // Our candidates ignore the first parameter.
Douglas Gregor70d26122008-11-12 17:17:38 +00003306 for (unsigned Left = FirstPromotedArithmeticType;
3307 Left < LastPromotedArithmeticType; ++Left) {
3308 for (unsigned Right = FirstPromotedArithmeticType;
3309 Right < LastPromotedArithmeticType; ++Right) {
3310 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman6ae7d112009-08-19 07:44:53 +00003311 QualType Result
3312 = isComparison
3313 ? Context.BoolTy
3314 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003315 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3316 }
3317 }
3318 break;
3319
3320 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003321 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00003322 case OO_Caret:
3323 case OO_Pipe:
3324 case OO_LessLess:
3325 case OO_GreaterGreater:
3326 // C++ [over.built]p17:
3327 //
3328 // For every pair of promoted integral types L and R, there
3329 // exist candidate operator functions of the form
3330 //
3331 // LR operator%(L, R);
3332 // LR operator&(L, R);
3333 // LR operator^(L, R);
3334 // LR operator|(L, R);
3335 // L operator<<(L, R);
3336 // L operator>>(L, R);
3337 //
3338 // where LR is the result of the usual arithmetic conversions
3339 // between types L and R.
3340 for (unsigned Left = FirstPromotedIntegralType;
3341 Left < LastPromotedIntegralType; ++Left) {
3342 for (unsigned Right = FirstPromotedIntegralType;
3343 Right < LastPromotedIntegralType; ++Right) {
3344 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3345 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3346 ? LandR[0]
Eli Friedman6ae7d112009-08-19 07:44:53 +00003347 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003348 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3349 }
3350 }
3351 break;
3352
3353 case OO_Equal:
3354 // C++ [over.built]p20:
3355 //
3356 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor9a375942009-08-24 13:43:27 +00003357 // pointer to member type and VQ is either volatile or
Douglas Gregor70d26122008-11-12 17:17:38 +00003358 // empty, there exist candidate operator functions of the form
3359 //
3360 // VQ T& operator=(VQ T&, T);
Douglas Gregor9a375942009-08-24 13:43:27 +00003361 for (BuiltinCandidateTypeSet::iterator
3362 Enum = CandidateTypes.enumeration_begin(),
3363 EnumEnd = CandidateTypes.enumeration_end();
3364 Enum != EnumEnd; ++Enum)
3365 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
3366 CandidateSet);
3367 for (BuiltinCandidateTypeSet::iterator
3368 MemPtr = CandidateTypes.member_pointer_begin(),
3369 MemPtrEnd = CandidateTypes.member_pointer_end();
3370 MemPtr != MemPtrEnd; ++MemPtr)
3371 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
3372 CandidateSet);
3373 // Fall through.
Douglas Gregor70d26122008-11-12 17:17:38 +00003374
3375 case OO_PlusEqual:
3376 case OO_MinusEqual:
3377 // C++ [over.built]p19:
3378 //
3379 // For every pair (T, VQ), where T is any type and VQ is either
3380 // volatile or empty, there exist candidate operator functions
3381 // of the form
3382 //
3383 // T*VQ& operator=(T*VQ&, T*);
3384 //
3385 // C++ [over.built]p21:
3386 //
3387 // For every pair (T, VQ), where T is a cv-qualified or
3388 // cv-unqualified object type and VQ is either volatile or
3389 // empty, there exist candidate operator functions of the form
3390 //
3391 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3392 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3393 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3394 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3395 QualType ParamTypes[2];
3396 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3397
3398 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003399 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003400 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3401 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003402
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003403 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3404 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003405 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003406 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3407 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003408 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003409 }
3410 // Fall through.
3411
3412 case OO_StarEqual:
3413 case OO_SlashEqual:
3414 // C++ [over.built]p18:
3415 //
3416 // For every triple (L, VQ, R), where L is an arithmetic type,
3417 // VQ is either volatile or empty, and R is a promoted
3418 // arithmetic type, there exist candidate operator functions of
3419 // the form
3420 //
3421 // VQ L& operator=(VQ L&, R);
3422 // VQ L& operator*=(VQ L&, R);
3423 // VQ L& operator/=(VQ L&, R);
3424 // VQ L& operator+=(VQ L&, R);
3425 // VQ L& operator-=(VQ L&, R);
3426 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3427 for (unsigned Right = FirstPromotedArithmeticType;
3428 Right < LastPromotedArithmeticType; ++Right) {
3429 QualType ParamTypes[2];
3430 ParamTypes[1] = ArithmeticTypes[Right];
3431
3432 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003433 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003434 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3435 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003436
3437 // Add this built-in operator as a candidate (VQ is 'volatile').
3438 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003439 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003440 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3441 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003442 }
3443 }
3444 break;
3445
3446 case OO_PercentEqual:
3447 case OO_LessLessEqual:
3448 case OO_GreaterGreaterEqual:
3449 case OO_AmpEqual:
3450 case OO_CaretEqual:
3451 case OO_PipeEqual:
3452 // C++ [over.built]p22:
3453 //
3454 // For every triple (L, VQ, R), where L is an integral type, VQ
3455 // is either volatile or empty, and R is a promoted integral
3456 // type, there exist candidate operator functions of the form
3457 //
3458 // VQ L& operator%=(VQ L&, R);
3459 // VQ L& operator<<=(VQ L&, R);
3460 // VQ L& operator>>=(VQ L&, R);
3461 // VQ L& operator&=(VQ L&, R);
3462 // VQ L& operator^=(VQ L&, R);
3463 // VQ L& operator|=(VQ L&, R);
3464 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3465 for (unsigned Right = FirstPromotedIntegralType;
3466 Right < LastPromotedIntegralType; ++Right) {
3467 QualType ParamTypes[2];
3468 ParamTypes[1] = ArithmeticTypes[Right];
3469
3470 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003471 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003472 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3473
3474 // Add this built-in operator as a candidate (VQ is 'volatile').
3475 ParamTypes[0] = ArithmeticTypes[Left];
3476 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003477 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003478 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3479 }
3480 }
3481 break;
3482
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003483 case OO_Exclaim: {
3484 // C++ [over.operator]p23:
3485 //
3486 // There also exist candidate operator functions of the form
3487 //
3488 // bool operator!(bool);
3489 // bool operator&&(bool, bool); [BELOW]
3490 // bool operator||(bool, bool); [BELOW]
3491 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003492 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3493 /*IsAssignmentOperator=*/false,
3494 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003495 break;
3496 }
3497
Douglas Gregor70d26122008-11-12 17:17:38 +00003498 case OO_AmpAmp:
3499 case OO_PipePipe: {
3500 // C++ [over.operator]p23:
3501 //
3502 // There also exist candidate operator functions of the form
3503 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003504 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003505 // bool operator&&(bool, bool);
3506 // bool operator||(bool, bool);
3507 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003508 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3509 /*IsAssignmentOperator=*/false,
3510 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003511 break;
3512 }
3513
3514 case OO_Subscript:
3515 // C++ [over.built]p13:
3516 //
3517 // For every cv-qualified or cv-unqualified object type T there
3518 // exist candidate operator functions of the form
3519 //
3520 // T* operator+(T*, ptrdiff_t); [ABOVE]
3521 // T& operator[](T*, ptrdiff_t);
3522 // T* operator-(T*, ptrdiff_t); [ABOVE]
3523 // T* operator+(ptrdiff_t, T*); [ABOVE]
3524 // T& operator[](ptrdiff_t, T*);
3525 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3526 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3527 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003528 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003529 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003530
3531 // T& operator[](T*, ptrdiff_t)
3532 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3533
3534 // T& operator[](ptrdiff_t, T*);
3535 ParamTypes[0] = ParamTypes[1];
3536 ParamTypes[1] = *Ptr;
3537 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3538 }
3539 break;
3540
3541 case OO_ArrowStar:
3542 // FIXME: No support for pointer-to-members yet.
3543 break;
Sebastian Redlbd261962009-04-16 17:51:27 +00003544
3545 case OO_Conditional:
3546 // Note that we don't consider the first argument, since it has been
3547 // contextually converted to bool long ago. The candidates below are
3548 // therefore added as binary.
3549 //
3550 // C++ [over.built]p24:
3551 // For every type T, where T is a pointer or pointer-to-member type,
3552 // there exist candidate operator functions of the form
3553 //
3554 // T operator?(bool, T, T);
3555 //
Sebastian Redlbd261962009-04-16 17:51:27 +00003556 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3557 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3558 QualType ParamTypes[2] = { *Ptr, *Ptr };
3559 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3560 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00003561 for (BuiltinCandidateTypeSet::iterator Ptr =
3562 CandidateTypes.member_pointer_begin(),
3563 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3564 QualType ParamTypes[2] = { *Ptr, *Ptr };
3565 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3566 }
Sebastian Redlbd261962009-04-16 17:51:27 +00003567 goto Conditional;
Douglas Gregor70d26122008-11-12 17:17:38 +00003568 }
3569}
3570
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003571/// \brief Add function candidates found via argument-dependent lookup
3572/// to the set of overloading candidates.
3573///
3574/// This routine performs argument-dependent name lookup based on the
3575/// given function name (which may also be an operator name) and adds
3576/// all of the overload candidates found by ADL to the overload
3577/// candidate set (C++ [basic.lookup.argdep]).
3578void
3579Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3580 Expr **Args, unsigned NumArgs,
3581 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003582 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003583
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003584 // Record all of the function candidates that we've already
3585 // added to the overload set, so that we don't add those same
3586 // candidates a second time.
3587 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3588 CandEnd = CandidateSet.end();
3589 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003590 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003591 Functions.insert(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003592 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3593 Functions.insert(FunTmpl);
3594 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003595
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003596 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003597
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003598 // Erase all of the candidates we already knew about.
3599 // FIXME: This is suboptimal. Is there a better way?
3600 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3601 CandEnd = CandidateSet.end();
3602 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003603 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003604 Functions.erase(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003605 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3606 Functions.erase(FunTmpl);
3607 }
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003608
3609 // For each of the ADL candidates we found, add it to the overload
3610 // set.
3611 for (FunctionSet::iterator Func = Functions.begin(),
3612 FuncEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00003613 Func != FuncEnd; ++Func) {
3614 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3615 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3616 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003617 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3618 /*FIXME: explicit args */false, 0, 0,
3619 Args, NumArgs, CandidateSet);
Douglas Gregor993a0602009-06-27 21:05:07 +00003620 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003621}
3622
Douglas Gregord2baafd2008-10-21 16:13:35 +00003623/// isBetterOverloadCandidate - Determines whether the first overload
3624/// candidate is a better candidate than the second (C++ 13.3.3p1).
3625bool
3626Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3627 const OverloadCandidate& Cand2)
3628{
3629 // Define viable functions to be better candidates than non-viable
3630 // functions.
3631 if (!Cand2.Viable)
3632 return Cand1.Viable;
3633 else if (!Cand1.Viable)
3634 return false;
3635
Douglas Gregor3257fb52008-12-22 05:46:06 +00003636 // C++ [over.match.best]p1:
3637 //
3638 // -- if F is a static member function, ICS1(F) is defined such
3639 // that ICS1(F) is neither better nor worse than ICS1(G) for
3640 // any function G, and, symmetrically, ICS1(G) is neither
3641 // better nor worse than ICS1(F).
3642 unsigned StartArg = 0;
3643 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3644 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003645
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003646 // C++ [over.match.best]p1:
3647 // A viable function F1 is defined to be a better function than another
3648 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
3649 // conversion sequence than ICSi(F2), and then...
Douglas Gregord2baafd2008-10-21 16:13:35 +00003650 unsigned NumArgs = Cand1.Conversions.size();
3651 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3652 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003653 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003654 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3655 Cand2.Conversions[ArgIdx])) {
3656 case ImplicitConversionSequence::Better:
3657 // Cand1 has a better conversion sequence.
3658 HasBetterConversion = true;
3659 break;
3660
3661 case ImplicitConversionSequence::Worse:
3662 // Cand1 can't be better than Cand2.
3663 return false;
3664
3665 case ImplicitConversionSequence::Indistinguishable:
3666 // Do nothing.
3667 break;
3668 }
3669 }
3670
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003671 // -- for some argument j, ICSj(F1) is a better conversion sequence than
3672 // ICSj(F2), or, if not that,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003673 if (HasBetterConversion)
3674 return true;
3675
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003676 // - F1 is a non-template function and F2 is a function template
3677 // specialization, or, if not that,
3678 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3679 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3680 return true;
3681
3682 // -- F1 and F2 are function template specializations, and the function
3683 // template for F1 is more specialized than the template for F2
3684 // according to the partial ordering rules described in 14.5.5.2, or,
3685 // if not that,
Douglas Gregorf8e51672009-08-02 23:46:29 +00003686 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3687 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor8c860df2009-08-21 23:19:43 +00003688 if (FunctionTemplateDecl *BetterTemplate
3689 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3690 Cand2.Function->getPrimaryTemplate(),
3691 true))
3692 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003693
Douglas Gregor60714f92008-11-07 22:36:19 +00003694 // -- the context is an initialization by user-defined conversion
3695 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3696 // from the return type of F1 to the destination type (i.e.,
3697 // the type of the entity being initialized) is a better
3698 // conversion sequence than the standard conversion sequence
3699 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003700 if (Cand1.Function && Cand2.Function &&
3701 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003702 isa<CXXConversionDecl>(Cand2.Function)) {
3703 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3704 Cand2.FinalConversion)) {
3705 case ImplicitConversionSequence::Better:
3706 // Cand1 has a better conversion sequence.
3707 return true;
3708
3709 case ImplicitConversionSequence::Worse:
3710 // Cand1 can't be better than Cand2.
3711 return false;
3712
3713 case ImplicitConversionSequence::Indistinguishable:
3714 // Do nothing
3715 break;
3716 }
3717 }
3718
Douglas Gregord2baafd2008-10-21 16:13:35 +00003719 return false;
3720}
3721
Douglas Gregor98189262009-06-19 23:52:42 +00003722/// \brief Computes the best viable function (C++ 13.3.3)
3723/// within an overload candidate set.
3724///
3725/// \param CandidateSet the set of candidate functions.
3726///
3727/// \param Loc the location of the function name (or operator symbol) for
3728/// which overload resolution occurs.
3729///
3730/// \param Best f overload resolution was successful or found a deleted
3731/// function, Best points to the candidate function found.
3732///
3733/// \returns The result of overload resolution.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003734Sema::OverloadingResult
3735Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregor98189262009-06-19 23:52:42 +00003736 SourceLocation Loc,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003737 OverloadCandidateSet::iterator& Best)
3738{
3739 // Find the best viable function.
3740 Best = CandidateSet.end();
3741 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3742 Cand != CandidateSet.end(); ++Cand) {
3743 if (Cand->Viable) {
3744 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3745 Best = Cand;
3746 }
3747 }
3748
3749 // If we didn't find any viable functions, abort.
3750 if (Best == CandidateSet.end())
3751 return OR_No_Viable_Function;
3752
3753 // Make sure that this function is better than every other viable
3754 // function. If not, we have an ambiguity.
3755 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3756 Cand != CandidateSet.end(); ++Cand) {
3757 if (Cand->Viable &&
3758 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003759 !isBetterOverloadCandidate(*Best, *Cand)) {
3760 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003761 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003762 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003763 }
3764
3765 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003766 if (Best->Function &&
3767 (Best->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003768 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregoraa57e862009-02-18 21:56:37 +00003769 return OR_Deleted;
3770
Douglas Gregor98189262009-06-19 23:52:42 +00003771 // C++ [basic.def.odr]p2:
3772 // An overloaded function is used if it is selected by overload resolution
3773 // when referred to from a potentially-evaluated expression. [Note: this
3774 // covers calls to named functions (5.2.2), operator overloading
3775 // (clause 13), user-defined conversions (12.3.2), allocation function for
3776 // placement new (5.3.4), as well as non-default initialization (8.5).
3777 if (Best->Function)
3778 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregord2baafd2008-10-21 16:13:35 +00003779 return OR_Success;
3780}
3781
3782/// PrintOverloadCandidates - When overload resolution fails, prints
3783/// diagnostic messages containing the candidates in the candidate
3784/// set. If OnlyViable is true, only viable candidates will be printed.
3785void
3786Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3787 bool OnlyViable)
3788{
3789 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3790 LastCand = CandidateSet.end();
3791 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003792 if (Cand->Viable || !OnlyViable) {
3793 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003794 if (Cand->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003795 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003796 // Deleted or "unavailable" function.
3797 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3798 << Cand->Function->isDeleted();
3799 } else {
3800 // Normal function
3801 // FIXME: Give a better reason!
3802 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3803 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003804 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003805 // Desugar the type of the surrogate down to a function type,
3806 // retaining as many typedefs as possible while still showing
3807 // the function type (and, therefore, its parameter types).
3808 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003809 bool isLValueReference = false;
3810 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003811 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003812 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003813 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003814 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003815 isLValueReference = true;
3816 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003817 FnType->getAs<RValueReferenceType>()) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003818 FnType = FnTypeRef->getPointeeType();
3819 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003820 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003821 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003822 FnType = FnTypePtr->getPointeeType();
3823 isPointer = true;
3824 }
3825 // Desugar down to a function type.
3826 FnType = QualType(FnType->getAsFunctionType(), 0);
3827 // Reconstruct the pointer/reference as appropriate.
3828 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003829 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3830 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003831
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003832 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003833 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003834 } else {
3835 // FIXME: We need to get the identifier in here
Mike Stumpe127ae32009-05-16 07:39:55 +00003836 // FIXME: Do we want the error message to point at the operator?
3837 // (built-ins won't have a location)
Douglas Gregor70d26122008-11-12 17:17:38 +00003838 QualType FnType
3839 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3840 Cand->BuiltinTypes.ParamTypes,
3841 Cand->Conversions.size(),
3842 false, 0);
3843
Chris Lattner4bfd2232008-11-24 06:25:27 +00003844 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003845 }
3846 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003847 }
3848}
3849
Douglas Gregor45014fd2008-11-10 20:40:00 +00003850/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3851/// an overloaded function (C++ [over.over]), where @p From is an
3852/// expression with overloaded function type and @p ToType is the type
3853/// we're trying to resolve to. For example:
3854///
3855/// @code
3856/// int f(double);
3857/// int f(int);
3858///
3859/// int (*pfd)(double) = f; // selects f(double)
3860/// @endcode
3861///
3862/// This routine returns the resulting FunctionDecl if it could be
3863/// resolved, and NULL otherwise. When @p Complain is true, this
3864/// routine will emit diagnostics if there is an error.
3865FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003866Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003867 bool Complain) {
3868 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003869 bool IsMember = false;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003870 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003871 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003872 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003873 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003874 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003875 ToType->getAs<MemberPointerType>()) {
Sebastian Redl7434fc32009-02-04 21:23:32 +00003876 FunctionType = MemTypePtr->getPointeeType();
3877 IsMember = true;
3878 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003879
3880 // We only look at pointers or references to functions.
Douglas Gregor72bb4992009-07-09 17:16:51 +00003881 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor62f78762009-07-08 20:55:45 +00003882 if (!FunctionType->isFunctionType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003883 return 0;
3884
3885 // Find the actual overloaded function declaration.
3886 OverloadedFunctionDecl *Ovl = 0;
3887
3888 // C++ [over.over]p1:
3889 // [...] [Note: any redundant set of parentheses surrounding the
3890 // overloaded function name is ignored (5.1). ]
3891 Expr *OvlExpr = From->IgnoreParens();
3892
3893 // C++ [over.over]p1:
3894 // [...] The overloaded function name can be preceded by the &
3895 // operator.
3896 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3897 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3898 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3899 }
3900
3901 // Try to dig out the overloaded function.
Douglas Gregor62f78762009-07-08 20:55:45 +00003902 FunctionTemplateDecl *FunctionTemplate = 0;
3903 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003904 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor62f78762009-07-08 20:55:45 +00003905 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3906 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003907
Douglas Gregor62f78762009-07-08 20:55:45 +00003908 // If there's no overloaded function declaration or function template,
3909 // we're done.
3910 if (!Ovl && !FunctionTemplate)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003911 return 0;
3912
Douglas Gregor62f78762009-07-08 20:55:45 +00003913 OverloadIterator Fun;
3914 if (Ovl)
3915 Fun = Ovl;
3916 else
3917 Fun = FunctionTemplate;
3918
Douglas Gregor45014fd2008-11-10 20:40:00 +00003919 // Look through all of the overloaded functions, searching for one
3920 // whose type matches exactly.
Douglas Gregora142a052009-07-08 23:33:52 +00003921 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
3922
3923 bool FoundNonTemplateFunction = false;
Douglas Gregor62f78762009-07-08 20:55:45 +00003924 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003925 // C++ [over.over]p3:
3926 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003927 // targets of type "pointer-to-function" or "reference-to-function."
3928 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003929 // type "pointer-to-member-function."
3930 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor62f78762009-07-08 20:55:45 +00003931
3932 if (FunctionTemplateDecl *FunctionTemplate
3933 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003934 if (CXXMethodDecl *Method
3935 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
3936 // Skip non-static function templates when converting to pointer, and
3937 // static when converting to member pointer.
3938 if (Method->isStatic() == IsMember)
3939 continue;
3940 } else if (IsMember)
3941 continue;
3942
3943 // C++ [over.over]p2:
3944 // If the name is a function template, template argument deduction is
3945 // done (14.8.2.2), and if the argument deduction succeeds, the
3946 // resulting template argument list is used to generate a single
3947 // function template specialization, which is added to the set of
3948 // overloaded functions considered.
Douglas Gregor62f78762009-07-08 20:55:45 +00003949 FunctionDecl *Specialization = 0;
3950 TemplateDeductionInfo Info(Context);
3951 if (TemplateDeductionResult Result
3952 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3953 /*FIXME:*/0, /*FIXME:*/0,
3954 FunctionType, Specialization, Info)) {
3955 // FIXME: make a note of the failed deduction for diagnostics.
3956 (void)Result;
3957 } else {
3958 assert(FunctionType
3959 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregora142a052009-07-08 23:33:52 +00003960 Matches.insert(
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003961 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor62f78762009-07-08 20:55:45 +00003962 }
3963 }
3964
Sebastian Redl7434fc32009-02-04 21:23:32 +00003965 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3966 // Skip non-static functions when converting to pointer, and static
3967 // when converting to member pointer.
3968 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003969 continue;
Douglas Gregora142a052009-07-08 23:33:52 +00003970 } else if (IsMember)
Sebastian Redl7434fc32009-02-04 21:23:32 +00003971 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003972
Douglas Gregorb60eb752009-06-25 22:08:12 +00003973 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003974 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003975 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregora142a052009-07-08 23:33:52 +00003976 FoundNonTemplateFunction = true;
3977 }
Douglas Gregor62f78762009-07-08 20:55:45 +00003978 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003979 }
3980
Douglas Gregora142a052009-07-08 23:33:52 +00003981 // If there were 0 or 1 matches, we're done.
3982 if (Matches.empty())
3983 return 0;
3984 else if (Matches.size() == 1)
3985 return *Matches.begin();
3986
3987 // C++ [over.over]p4:
3988 // If more than one function is selected, [...]
3989 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor8c860df2009-08-21 23:19:43 +00003990 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregora142a052009-07-08 23:33:52 +00003991 if (FoundNonTemplateFunction) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00003992 // [...] any function template specializations in the set are
3993 // eliminated if the set also contains a non-template function, [...]
3994 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregora142a052009-07-08 23:33:52 +00003995 if ((*M)->getPrimaryTemplate() == 0)
3996 RemainingMatches.push_back(*M);
3997 } else {
Douglas Gregor8c860df2009-08-21 23:19:43 +00003998 // [...] and any given function template specialization F1 is
3999 // eliminated if the set contains a second function template
4000 // specialization whose function template is more specialized
4001 // than the function template of F1 according to the partial
4002 // ordering rules of 14.5.5.2.
4003
4004 // The algorithm specified above is quadratic. We instead use a
4005 // two-pass algorithm (similar to the one used to identify the
4006 // best viable function in an overload set) that identifies the
4007 // best function template (if it exists).
4008 MatchIter Best = Matches.begin();
4009 MatchIter M = Best, MEnd = Matches.end();
4010 // Find the most specialized function.
4011 for (++M; M != MEnd; ++M)
4012 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4013 (*Best)->getPrimaryTemplate(),
4014 false)
4015 == (*M)->getPrimaryTemplate())
4016 Best = M;
4017
4018 // Determine whether this function template is more specialized
4019 // that all of the others.
4020 bool Ambiguous = false;
4021 for (M = Matches.begin(); M != MEnd; ++M) {
4022 if (M != Best &&
4023 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4024 (*Best)->getPrimaryTemplate(),
4025 false)
4026 != (*Best)->getPrimaryTemplate()) {
4027 Ambiguous = true;
4028 break;
4029 }
4030 }
4031
4032 // If one function template was more specialized than all of the
4033 // others, return it.
4034 if (!Ambiguous)
4035 return *Best;
4036
4037 // We could not find a most-specialized function template, which
4038 // is equivalent to having a set of function templates with more
4039 // than one such template. So, we place all of the function
4040 // templates into the set of remaining matches and produce a
4041 // diagnostic below. FIXME: we could perform the quadratic
4042 // algorithm here, pruning the result set to limit the number of
4043 // candidates output later.
4044 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregora142a052009-07-08 23:33:52 +00004045 }
4046
4047 // [...] After such eliminations, if any, there shall remain exactly one
4048 // selected function.
4049 if (RemainingMatches.size() == 1)
4050 return RemainingMatches.front();
4051
4052 // FIXME: We should probably return the same thing that BestViableFunction
4053 // returns (even if we issue the diagnostics here).
4054 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4055 << RemainingMatches[0]->getDeclName();
4056 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4057 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor45014fd2008-11-10 20:40:00 +00004058 return 0;
4059}
4060
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004061/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004062/// (which eventually refers to the declaration Func) and the call
4063/// arguments Args/NumArgs, attempt to resolve the function call down
4064/// to a specific function. If overload resolution succeeds, returns
4065/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004066/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004067/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004068FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004069 DeclarationName UnqualifiedName,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004070 bool HasExplicitTemplateArgs,
4071 const TemplateArgument *ExplicitTemplateArgs,
4072 unsigned NumExplicitTemplateArgs,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004073 SourceLocation LParenLoc,
4074 Expr **Args, unsigned NumArgs,
4075 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004076 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004077 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004078 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004079
4080 // Add the functions denoted by Callee to the set of candidate
4081 // functions. While we're doing so, track whether argument-dependent
4082 // lookup still applies, per:
4083 //
4084 // C++0x [basic.lookup.argdep]p3:
4085 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4086 // and let Y be the lookup set produced by argument dependent
4087 // lookup (defined as follows). If X contains
4088 //
4089 // -- a declaration of a class member, or
4090 //
4091 // -- a block-scope function declaration that is not a
4092 // using-declaration, or
4093 //
4094 // -- a declaration that is neither a function or a function
4095 // template
4096 //
4097 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004098 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004099 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4100 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4101 FuncEnd = Ovl->function_end();
4102 Func != FuncEnd; ++Func) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00004103 DeclContext *Ctx = 0;
4104 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004105 if (HasExplicitTemplateArgs)
4106 continue;
4107
Douglas Gregorb60eb752009-06-25 22:08:12 +00004108 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4109 Ctx = FunDecl->getDeclContext();
4110 } else {
4111 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004112 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4113 ExplicitTemplateArgs,
4114 NumExplicitTemplateArgs,
4115 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004116 Ctx = FunTmpl->getDeclContext();
4117 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004118
Douglas Gregorb60eb752009-06-25 22:08:12 +00004119
4120 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004121 ArgumentDependentLookup = false;
4122 }
4123 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004124 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004125 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4126
4127 if (Func->getDeclContext()->isRecord() ||
4128 Func->getDeclContext()->isFunctionOrMethod())
4129 ArgumentDependentLookup = false;
Douglas Gregorb60eb752009-06-25 22:08:12 +00004130 } else if (FunctionTemplateDecl *FuncTemplate
4131 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004132 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4133 ExplicitTemplateArgs,
4134 NumExplicitTemplateArgs,
4135 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004136
4137 if (FuncTemplate->getDeclContext()->isRecord())
4138 ArgumentDependentLookup = false;
4139 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004140
4141 if (Callee)
4142 UnqualifiedName = Callee->getDeclName();
4143
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004144 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004145 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004146 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004147 CandidateSet);
4148
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004149 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004150 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004151 case OR_Success:
4152 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004153
4154 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00004155 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004156 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004157 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004158 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4159 break;
4160
4161 case OR_Ambiguous:
4162 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004163 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004164 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4165 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004166
4167 case OR_Deleted:
4168 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4169 << Best->Function->isDeleted()
4170 << UnqualifiedName
4171 << Fn->getSourceRange();
4172 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4173 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004174 }
4175
4176 // Overload resolution failed. Destroy all of the subexpressions and
4177 // return NULL.
4178 Fn->Destroy(Context);
4179 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4180 Args[Arg]->Destroy(Context);
4181 return 0;
4182}
4183
Douglas Gregorc78182d2009-03-13 23:49:33 +00004184/// \brief Create a unary operation that may resolve to an overloaded
4185/// operator.
4186///
4187/// \param OpLoc The location of the operator itself (e.g., '*').
4188///
4189/// \param OpcIn The UnaryOperator::Opcode that describes this
4190/// operator.
4191///
4192/// \param Functions The set of non-member functions that will be
4193/// considered by overload resolution. The caller needs to build this
4194/// set based on the context using, e.g.,
4195/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4196/// set should not contain any member functions; those will be added
4197/// by CreateOverloadedUnaryOp().
4198///
4199/// \param input The input argument.
4200Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4201 unsigned OpcIn,
4202 FunctionSet &Functions,
4203 ExprArg input) {
4204 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4205 Expr *Input = (Expr *)input.get();
4206
4207 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4208 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4209 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4210
4211 Expr *Args[2] = { Input, 0 };
4212 unsigned NumArgs = 1;
4213
4214 // For post-increment and post-decrement, add the implicit '0' as
4215 // the second argument, so that we know this is a post-increment or
4216 // post-decrement.
4217 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4218 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4219 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4220 SourceLocation());
4221 NumArgs = 2;
4222 }
4223
4224 if (Input->isTypeDependent()) {
4225 OverloadedFunctionDecl *Overloads
4226 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4227 for (FunctionSet::iterator Func = Functions.begin(),
4228 FuncEnd = Functions.end();
4229 Func != FuncEnd; ++Func)
4230 Overloads->addOverload(*Func);
4231
4232 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4233 OpLoc, false, false);
4234
4235 input.release();
4236 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4237 &Args[0], NumArgs,
4238 Context.DependentTy,
4239 OpLoc));
4240 }
4241
4242 // Build an empty overload set.
4243 OverloadCandidateSet CandidateSet;
4244
4245 // Add the candidates from the given function set.
4246 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4247
4248 // Add operator candidates that are member functions.
4249 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4250
4251 // Add builtin operator candidates.
4252 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4253
4254 // Perform overload resolution.
4255 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004256 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004257 case OR_Success: {
4258 // We found a built-in operator or an overloaded operator.
4259 FunctionDecl *FnDecl = Best->Function;
4260
4261 if (FnDecl) {
4262 // We matched an overloaded operator. Build a call to that
4263 // operator.
4264
4265 // Convert the arguments.
4266 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4267 if (PerformObjectArgumentInitialization(Input, Method))
4268 return ExprError();
4269 } else {
4270 // Convert the arguments.
4271 if (PerformCopyInitialization(Input,
4272 FnDecl->getParamDecl(0)->getType(),
4273 "passing"))
4274 return ExprError();
4275 }
4276
4277 // Determine the result type
4278 QualType ResultTy
4279 = FnDecl->getType()->getAsFunctionType()->getResultType();
4280 ResultTy = ResultTy.getNonReferenceType();
4281
4282 // Build the actual expression node.
4283 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4284 SourceLocation());
4285 UsualUnaryConversions(FnExpr);
4286
4287 input.release();
Anders Carlsson16497742009-08-16 04:11:06 +00004288
4289 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4290 &Input, 1, ResultTy, OpLoc);
4291 return MaybeBindToTemporary(CE);
Douglas Gregorc78182d2009-03-13 23:49:33 +00004292 } else {
4293 // We matched a built-in operator. Convert the arguments, then
4294 // break out so that we will build the appropriate built-in
4295 // operator node.
4296 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4297 Best->Conversions[0], "passing"))
4298 return ExprError();
4299
4300 break;
4301 }
4302 }
4303
4304 case OR_No_Viable_Function:
4305 // No viable function; fall through to handling this as a
4306 // built-in operator, which will produce an error message for us.
4307 break;
4308
4309 case OR_Ambiguous:
4310 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4311 << UnaryOperator::getOpcodeStr(Opc)
4312 << Input->getSourceRange();
4313 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4314 return ExprError();
4315
4316 case OR_Deleted:
4317 Diag(OpLoc, diag::err_ovl_deleted_oper)
4318 << Best->Function->isDeleted()
4319 << UnaryOperator::getOpcodeStr(Opc)
4320 << Input->getSourceRange();
4321 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4322 return ExprError();
4323 }
4324
4325 // Either we found no viable overloaded operator or we matched a
4326 // built-in operator. In either case, fall through to trying to
4327 // build a built-in operation.
4328 input.release();
4329 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4330}
4331
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004332/// \brief Create a binary operation that may resolve to an overloaded
4333/// operator.
4334///
4335/// \param OpLoc The location of the operator itself (e.g., '+').
4336///
4337/// \param OpcIn The BinaryOperator::Opcode that describes this
4338/// operator.
4339///
4340/// \param Functions The set of non-member functions that will be
4341/// considered by overload resolution. The caller needs to build this
4342/// set based on the context using, e.g.,
4343/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4344/// set should not contain any member functions; those will be added
4345/// by CreateOverloadedBinOp().
4346///
4347/// \param LHS Left-hand argument.
4348/// \param RHS Right-hand argument.
4349Sema::OwningExprResult
4350Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4351 unsigned OpcIn,
4352 FunctionSet &Functions,
4353 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004354 Expr *Args[2] = { LHS, RHS };
Douglas Gregor114c6192009-08-26 17:08:25 +00004355 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004356
4357 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4358 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4359 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4360
4361 // If either side is type-dependent, create an appropriate dependent
4362 // expression.
Douglas Gregor114c6192009-08-26 17:08:25 +00004363 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004364 // .* cannot be overloaded.
4365 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregor114c6192009-08-26 17:08:25 +00004366 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004367 Context.DependentTy, OpLoc));
4368
4369 OverloadedFunctionDecl *Overloads
4370 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4371 for (FunctionSet::iterator Func = Functions.begin(),
4372 FuncEnd = Functions.end();
4373 Func != FuncEnd; ++Func)
4374 Overloads->addOverload(*Func);
4375
4376 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4377 OpLoc, false, false);
4378
4379 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4380 Args, 2,
4381 Context.DependentTy,
4382 OpLoc));
4383 }
4384
4385 // If this is the .* operator, which is not overloadable, just
4386 // create a built-in binary operator.
4387 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregor114c6192009-08-26 17:08:25 +00004388 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004389
4390 // If this is one of the assignment operators, we only perform
4391 // overload resolution if the left-hand side is a class or
4392 // enumeration type (C++ [expr.ass]p3).
4393 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregor114c6192009-08-26 17:08:25 +00004394 !Args[0]->getType()->isOverloadableType())
4395 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004396
Douglas Gregorc78182d2009-03-13 23:49:33 +00004397 // Build an empty overload set.
4398 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004399
4400 // Add the candidates from the given function set.
4401 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4402
4403 // Add operator candidates that are member functions.
4404 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4405
4406 // Add builtin operator candidates.
4407 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4408
4409 // Perform overload resolution.
4410 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004411 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00004412 case OR_Success: {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004413 // We found a built-in operator or an overloaded operator.
4414 FunctionDecl *FnDecl = Best->Function;
4415
4416 if (FnDecl) {
4417 // We matched an overloaded operator. Build a call to that
4418 // operator.
4419
4420 // Convert the arguments.
4421 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregor114c6192009-08-26 17:08:25 +00004422 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4423 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004424 "passing"))
4425 return ExprError();
4426 } else {
4427 // Convert the arguments.
Douglas Gregor114c6192009-08-26 17:08:25 +00004428 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004429 "passing") ||
Douglas Gregor114c6192009-08-26 17:08:25 +00004430 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004431 "passing"))
4432 return ExprError();
4433 }
4434
4435 // Determine the result type
4436 QualType ResultTy
4437 = FnDecl->getType()->getAsFunctionType()->getResultType();
4438 ResultTy = ResultTy.getNonReferenceType();
4439
4440 // Build the actual expression node.
4441 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argiris Kirtzidiscca21b82009-07-14 03:19:38 +00004442 OpLoc);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004443 UsualUnaryConversions(FnExpr);
4444
Anders Carlsson16497742009-08-16 04:11:06 +00004445 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4446 Args, 2, ResultTy, OpLoc);
4447 return MaybeBindToTemporary(CE);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004448 } else {
4449 // We matched a built-in operator. Convert the arguments, then
4450 // break out so that we will build the appropriate built-in
4451 // operator node.
Douglas Gregor114c6192009-08-26 17:08:25 +00004452 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004453 Best->Conversions[0], "passing") ||
Douglas Gregor114c6192009-08-26 17:08:25 +00004454 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004455 Best->Conversions[1], "passing"))
4456 return ExprError();
4457
4458 break;
4459 }
4460 }
4461
4462 case OR_No_Viable_Function:
Sebastian Redl35196b42009-05-21 11:50:50 +00004463 // For class as left operand for assignment or compound assigment operator
4464 // do not fall through to handling in built-in, but report that no overloaded
4465 // assignment operator found
Douglas Gregor114c6192009-08-26 17:08:25 +00004466 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl35196b42009-05-21 11:50:50 +00004467 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4468 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor114c6192009-08-26 17:08:25 +00004469 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl35196b42009-05-21 11:50:50 +00004470 return ExprError();
4471 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004472 // No viable function; fall through to handling this as a
4473 // built-in operator, which will produce an error message for us.
4474 break;
4475
4476 case OR_Ambiguous:
4477 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4478 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor114c6192009-08-26 17:08:25 +00004479 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004480 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4481 return ExprError();
4482
4483 case OR_Deleted:
4484 Diag(OpLoc, diag::err_ovl_deleted_oper)
4485 << Best->Function->isDeleted()
4486 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor114c6192009-08-26 17:08:25 +00004487 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004488 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4489 return ExprError();
4490 }
4491
4492 // Either we found no viable overloaded operator or we matched a
4493 // built-in operator. In either case, try to build a built-in
4494 // operation.
Douglas Gregor114c6192009-08-26 17:08:25 +00004495 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004496}
4497
Douglas Gregor3257fb52008-12-22 05:46:06 +00004498/// BuildCallToMemberFunction - Build a call to a member
4499/// function. MemExpr is the expression that refers to the member
4500/// function (and includes the object parameter), Args/NumArgs are the
4501/// arguments to the function call (not including the object
4502/// parameter). The caller needs to validate that the member
4503/// expression refers to a member function or an overloaded member
4504/// function.
4505Sema::ExprResult
4506Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4507 SourceLocation LParenLoc, Expr **Args,
4508 unsigned NumArgs, SourceLocation *CommaLocs,
4509 SourceLocation RParenLoc) {
4510 // Dig out the member expression. This holds both the object
4511 // argument and the member function we're referring to.
4512 MemberExpr *MemExpr = 0;
4513 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4514 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4515 else
4516 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4517 assert(MemExpr && "Building member call without member expression");
4518
4519 // Extract the object argument.
4520 Expr *ObjectArg = MemExpr->getBase();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00004521
Douglas Gregor3257fb52008-12-22 05:46:06 +00004522 CXXMethodDecl *Method = 0;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004523 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4524 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004525 // Add overload candidates
4526 OverloadCandidateSet CandidateSet;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004527 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
4528
Douglas Gregor050cabf2009-08-21 18:42:58 +00004529 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4530 Func != FuncEnd; ++Func) {
4531 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
4532 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4533 /*SuppressUserConversions=*/false);
4534 else
4535 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4536 /*FIXME:*/false, /*FIXME:*/0,
4537 /*FIXME:*/0, ObjectArg, Args, NumArgs,
4538 CandidateSet,
4539 /*SuppressUsedConversions=*/false);
4540 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004541
Douglas Gregor3257fb52008-12-22 05:46:06 +00004542 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004543 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004544 case OR_Success:
4545 Method = cast<CXXMethodDecl>(Best->Function);
4546 break;
4547
4548 case OR_No_Viable_Function:
4549 Diag(MemExpr->getSourceRange().getBegin(),
4550 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004551 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004552 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4553 // FIXME: Leaking incoming expressions!
4554 return true;
4555
4556 case OR_Ambiguous:
4557 Diag(MemExpr->getSourceRange().getBegin(),
4558 diag::err_ovl_ambiguous_member_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004559 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004560 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4561 // FIXME: Leaking incoming expressions!
4562 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004563
4564 case OR_Deleted:
4565 Diag(MemExpr->getSourceRange().getBegin(),
4566 diag::err_ovl_deleted_member_call)
4567 << Best->Function->isDeleted()
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004568 << DeclName << MemExprE->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004569 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4570 // FIXME: Leaking incoming expressions!
4571 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004572 }
4573
4574 FixOverloadedFunctionReference(MemExpr, Method);
4575 } else {
4576 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4577 }
4578
4579 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00004580 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004581 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4582 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004583 Method->getResultType().getNonReferenceType(),
4584 RParenLoc));
4585
4586 // Convert the object argument (for a non-static member function call).
4587 if (!Method->isStatic() &&
4588 PerformObjectArgumentInitialization(ObjectArg, Method))
4589 return true;
4590 MemExpr->setBase(ObjectArg);
4591
4592 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004593 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004594 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4595 RParenLoc))
4596 return true;
4597
Anders Carlsson7fb13802009-08-16 01:56:34 +00004598 if (CheckFunctionCall(Method, TheCall.get()))
4599 return true;
Anders Carlssonb8ff3402009-08-16 03:42:12 +00004600
4601 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004602}
4603
Douglas Gregor10f3c502008-11-19 21:05:33 +00004604/// BuildCallToObjectOfClassType - Build a call to an object of class
4605/// type (C++ [over.call.object]), which can end up invoking an
4606/// overloaded function call operator (@c operator()) or performing a
4607/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004608Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004609Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4610 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004611 Expr **Args, unsigned NumArgs,
4612 SourceLocation *CommaLocs,
4613 SourceLocation RParenLoc) {
4614 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004615 const RecordType *Record = Object->getType()->getAs<RecordType>();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004616
4617 // C++ [over.call.object]p1:
4618 // If the primary-expression E in the function call syntax
Eli Friedmand5a72f02009-08-05 19:21:58 +00004619 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor10f3c502008-11-19 21:05:33 +00004620 // candidate functions includes at least the function call
4621 // operators of T. The function call operators of T are obtained by
4622 // ordinary lookup of the name operator() in the context of
4623 // (E).operator().
4624 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004625 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004626 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004627 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004628 Oper != OperEnd; ++Oper)
4629 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4630 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004631
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004632 // C++ [over.call.object]p2:
4633 // In addition, for each conversion function declared in T of the
4634 // form
4635 //
4636 // operator conversion-type-id () cv-qualifier;
4637 //
4638 // where cv-qualifier is the same cv-qualification as, or a
4639 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004640 // denotes the type "pointer to function of (P1,...,Pn) returning
4641 // R", or the type "reference to pointer to function of
4642 // (P1,...,Pn) returning R", or the type "reference to function
4643 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004644 // is also considered as a candidate function. Similarly,
4645 // surrogate call functions are added to the set of candidate
4646 // functions for each conversion function declared in an
4647 // accessible base class provided the function is not hidden
4648 // within T by another intervening declaration.
Douglas Gregorb35c7992009-08-24 15:23:48 +00004649
4650 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4651 // FIXME: Look in base classes for more conversion operators!
4652 OverloadedFunctionDecl *Conversions
4653 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
4654 for (OverloadedFunctionDecl::function_iterator
4655 Func = Conversions->function_begin(),
4656 FuncEnd = Conversions->function_end();
4657 Func != FuncEnd; ++Func) {
4658 CXXConversionDecl *Conv;
4659 FunctionTemplateDecl *ConvTemplate;
4660 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor8c860df2009-08-21 23:19:43 +00004661
Douglas Gregorb35c7992009-08-24 15:23:48 +00004662 // Skip over templated conversion functions; they aren't
4663 // surrogates.
4664 if (ConvTemplate)
4665 continue;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004666
Douglas Gregorb35c7992009-08-24 15:23:48 +00004667 // Strip the reference type (if any) and then the pointer type (if
4668 // any) to get down to what might be a function type.
4669 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4670 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4671 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004672
Douglas Gregorb35c7992009-08-24 15:23:48 +00004673 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
4674 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4675 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004676 }
Douglas Gregorb35c7992009-08-24 15:23:48 +00004677
Douglas Gregor10f3c502008-11-19 21:05:33 +00004678 // Perform overload resolution.
4679 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004680 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004681 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004682 // Overload resolution succeeded; we'll build the appropriate call
4683 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004684 break;
4685
4686 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004687 Diag(Object->getSourceRange().getBegin(),
4688 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004689 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004690 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004691 break;
4692
4693 case OR_Ambiguous:
4694 Diag(Object->getSourceRange().getBegin(),
4695 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004696 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004697 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4698 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004699
4700 case OR_Deleted:
4701 Diag(Object->getSourceRange().getBegin(),
4702 diag::err_ovl_deleted_object_call)
4703 << Best->Function->isDeleted()
4704 << Object->getType() << Object->getSourceRange();
4705 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4706 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004707 }
4708
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004709 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004710 // We had an error; delete all of the subexpressions and return
4711 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004712 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004713 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004714 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004715 return true;
4716 }
4717
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004718 if (Best->Function == 0) {
4719 // Since there is no function declaration, this is one of the
4720 // surrogate candidates. Dig out the conversion function.
4721 CXXConversionDecl *Conv
4722 = cast<CXXConversionDecl>(
4723 Best->Conversions[0].UserDefined.ConversionFunction);
4724
4725 // We selected one of the surrogate functions that converts the
4726 // object parameter to a function pointer. Perform the conversion
4727 // on the object argument, then let ActOnCallExpr finish the job.
4728 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004729 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004730 Conv->getConversionType().getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +00004731 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +00004732 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004733 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4734 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4735 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004736 }
4737
4738 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4739 // that calls this method, using Object for the implicit object
4740 // parameter and passing along the remaining arguments.
4741 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004742 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004743
4744 unsigned NumArgsInProto = Proto->getNumArgs();
4745 unsigned NumArgsToCheck = NumArgs;
4746
4747 // Build the full argument list for the method call (the
4748 // implicit object parameter is placed at the beginning of the
4749 // list).
4750 Expr **MethodArgs;
4751 if (NumArgs < NumArgsInProto) {
4752 NumArgsToCheck = NumArgsInProto;
4753 MethodArgs = new Expr*[NumArgsInProto + 1];
4754 } else {
4755 MethodArgs = new Expr*[NumArgs + 1];
4756 }
4757 MethodArgs[0] = Object;
4758 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4759 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4760
Ted Kremenek0c97e042009-02-07 01:47:29 +00004761 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4762 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004763 UsualUnaryConversions(NewFn);
4764
4765 // Once we've built TheCall, all of the expressions are properly
4766 // owned.
4767 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004768 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004769 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4770 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004771 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004772 delete [] MethodArgs;
4773
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004774 // We may have default arguments. If so, we need to allocate more
4775 // slots in the call for them.
4776 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004777 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004778 else if (NumArgs > NumArgsInProto)
4779 NumArgsToCheck = NumArgsInProto;
4780
Chris Lattner81f00ed2009-04-12 08:11:20 +00004781 bool IsError = false;
4782
Douglas Gregor10f3c502008-11-19 21:05:33 +00004783 // Initialize the implicit object parameter.
Chris Lattner81f00ed2009-04-12 08:11:20 +00004784 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004785 TheCall->setArg(0, Object);
4786
Chris Lattner81f00ed2009-04-12 08:11:20 +00004787
Douglas Gregor10f3c502008-11-19 21:05:33 +00004788 // Check the argument types.
4789 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004790 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004791 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004792 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004793
4794 // Pass the argument.
4795 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner81f00ed2009-04-12 08:11:20 +00004796 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004797 } else {
Anders Carlsson3d752db2009-08-14 18:30:22 +00004798 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004799 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004800
4801 TheCall->setArg(i + 1, Arg);
4802 }
4803
4804 // If this is a variadic call, handle args passed through "...".
4805 if (Proto->isVariadic()) {
4806 // Promote the arguments (C99 6.5.2.2p7).
4807 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4808 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00004809 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004810 TheCall->setArg(i + 1, Arg);
4811 }
4812 }
4813
Chris Lattner81f00ed2009-04-12 08:11:20 +00004814 if (IsError) return true;
4815
Anders Carlsson7fb13802009-08-16 01:56:34 +00004816 if (CheckFunctionCall(Method, TheCall.get()))
4817 return true;
4818
Anders Carlsson422a5fe2009-08-16 03:53:54 +00004819 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004820}
4821
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004822/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4823/// (if one exists), where @c Base is an expression of class type and
4824/// @c Member is the name of the member we're trying to find.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004825Sema::OwningExprResult
4826Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4827 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004828 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4829
4830 // C++ [over.ref]p1:
4831 //
4832 // [...] An expression x->m is interpreted as (x.operator->())->m
4833 // for a class object x of type T if T::operator->() exists and if
4834 // the operator is selected as the best match function by the
4835 // overload resolution mechanism (13.3).
4836 // FIXME: look in base classes.
4837 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4838 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004839 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorda61ad22009-08-06 03:17:00 +00004840
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004841 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004842 for (llvm::tie(Oper, OperEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004843 = BaseRecord->getDecl()->lookup(OpName); Oper != OperEnd; ++Oper)
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004844 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004845 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004846
4847 // Perform overload resolution.
4848 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004849 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004850 case OR_Success:
4851 // Overload resolution succeeded; we'll build the call below.
4852 break;
4853
4854 case OR_No_Viable_Function:
4855 if (CandidateSet.empty())
4856 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004857 << Base->getType() << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004858 else
4859 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004860 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004861 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004862 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004863
4864 case OR_Ambiguous:
4865 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004866 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004867 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004868 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004869
4870 case OR_Deleted:
4871 Diag(OpLoc, diag::err_ovl_deleted_oper)
4872 << Best->Function->isDeleted()
Douglas Gregorda61ad22009-08-06 03:17:00 +00004873 << "operator->" << Base->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004874 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004875 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004876 }
4877
4878 // Convert the object parameter.
4879 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004880 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorda61ad22009-08-06 03:17:00 +00004881 return ExprError();
Douglas Gregor9c690e92008-11-21 03:04:22 +00004882
4883 // No concerns about early exits now.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004884 BaseIn.release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004885
4886 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004887 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4888 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004889 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004890 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004891 Method->getResultType().getNonReferenceType(),
4892 OpLoc);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004893 return Owned(Base);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004894}
4895
Douglas Gregor45014fd2008-11-10 20:40:00 +00004896/// FixOverloadedFunctionReference - E is an expression that refers to
4897/// a C++ overloaded function (possibly with some parentheses and
4898/// perhaps a '&' around it). We have resolved the overloaded function
4899/// to the function declaration Fn, so patch up the expression E to
4900/// refer (possibly indirectly) to Fn.
4901void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4902 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4903 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4904 E->setType(PE->getSubExpr()->getType());
4905 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4906 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4907 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4909 if (Method->isStatic()) {
4910 // Do nothing: static member functions aren't any different
4911 // from non-member functions.
Mike Stump90fc78e2009-08-04 21:02:39 +00004912 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor3f411962009-02-11 01:18:59 +00004913 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4914 // We have taken the address of a pointer to member
4915 // function. Perform the computation here so that we get the
4916 // appropriate pointer to member type.
4917 DRE->setDecl(Fn);
4918 DRE->setType(Fn->getType());
4919 QualType ClassType
4920 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4921 E->setType(Context.getMemberPointerType(Fn->getType(),
4922 ClassType.getTypePtr()));
4923 return;
4924 }
4925 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004926 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004927 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004928 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor62f78762009-07-08 20:55:45 +00004929 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
4930 isa<FunctionTemplateDecl>(DR->getDecl())) &&
4931 "Expected overloaded function or function template");
Douglas Gregor45014fd2008-11-10 20:40:00 +00004932 DR->setDecl(Fn);
4933 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004934 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4935 MemExpr->setMemberDecl(Fn);
4936 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004937 } else {
4938 assert(false && "Invalid reference to overloaded function");
4939 }
4940}
4941
Douglas Gregord2baafd2008-10-21 16:13:35 +00004942} // end namespace clang