blob: 04bc6b10c0d7368f633d53b1c98d299520c7b101 [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000020#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000022#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000024#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000025#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000026#include "llvm/Support/Compiler.h"
27#include <algorithm>
Torok Edwindb714922009-08-24 13:25:12 +000028#include <cstdio>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000029
30namespace clang {
31
32/// GetConversionCategory - Retrieve the implicit conversion
33/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000034ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035GetConversionCategory(ImplicitConversionKind Kind) {
36 static const ImplicitConversionCategory
37 Category[(int)ICK_Num_Conversion_Kinds] = {
38 ICC_Identity,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
41 ICC_Lvalue_Transformation,
42 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
70 ICR_Promotion,
71 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000072 ICR_Promotion,
73 ICR_Conversion,
74 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000075 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000080 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000081 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000082 ICR_Conversion
83 };
84 return Rank[(int)Kind];
85}
86
87/// GetImplicitConversionName - Return the name of this kind of
88/// implicit conversion.
89const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
90 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
91 "No conversion",
92 "Lvalue-to-rvalue",
93 "Array-to-pointer",
94 "Function-to-pointer",
95 "Qualification",
96 "Integral promotion",
97 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +000098 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000099 "Integral conversion",
100 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000101 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000102 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 "Pointer conversion",
105 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000106 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000107 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109 };
110 return Name[Kind];
111}
112
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000113/// StandardConversionSequence - Set the standard conversion
114/// sequence to the identity conversion.
115void StandardConversionSequence::setAsIdentityConversion() {
116 First = ICK_Identity;
117 Second = ICK_Identity;
118 Third = ICK_Identity;
119 Deprecated = false;
120 ReferenceBinding = false;
121 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000122 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000123 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000124}
125
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000126/// getRank - Retrieve the rank of this standard conversion sequence
127/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
128/// implicit conversions.
129ImplicitConversionRank StandardConversionSequence::getRank() const {
130 ImplicitConversionRank Rank = ICR_Exact_Match;
131 if (GetConversionRank(First) > Rank)
132 Rank = GetConversionRank(First);
133 if (GetConversionRank(Second) > Rank)
134 Rank = GetConversionRank(Second);
135 if (GetConversionRank(Third) > Rank)
136 Rank = GetConversionRank(Third);
137 return Rank;
138}
139
140/// isPointerConversionToBool - Determines whether this conversion is
141/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000142/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000143/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000144bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145 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 Gregor033f56d2008-12-23 00:53:59 +0000153 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor5251f1b2008-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 Gregor5c407d92008-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).
Mike Stump11289f42009-09-09 15:08:12 +0000164bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000165StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000166isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregor5c407d92008-10-23 00:40:37 +0000167 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
168 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
169
170 // Note that FromType has not necessarily been transformed by the
171 // array-to-pointer implicit conversion, so check for its presence
172 // and redo the conversion to get a pointer.
173 if (First == ICK_Array_To_Pointer)
174 FromType = Context.getArrayDecayedType(FromType);
175
176 if (Second == ICK_Pointer_Conversion)
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000177 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000178 return ToPtrType->getPointeeType()->isVoidType();
179
180 return false;
181}
182
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000183/// DebugPrint - Print this standard conversion sequence to standard
184/// error. Useful for debugging overloading issues.
185void StandardConversionSequence::DebugPrint() const {
186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
188 fprintf(stderr, "%s", GetImplicitConversionName(First));
189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
194 fprintf(stderr, " -> ");
195 }
196 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor2fe98832008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
199 fprintf(stderr, " (by copy constructor)");
200 } else if (DirectBinding) {
201 fprintf(stderr, " (direct reference binding)");
202 } else if (ReferenceBinding) {
203 fprintf(stderr, " (reference binding)");
204 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
210 fprintf(stderr, " -> ");
211 }
212 fprintf(stderr, "%s", GetImplicitConversionName(Third));
213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
217 fprintf(stderr, "No conversions required");
218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
224 if (Before.First || Before.Second || Before.Third) {
225 Before.DebugPrint();
226 fprintf(stderr, " -> ");
227 }
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000228 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000229 if (After.First || After.Second || After.Third) {
230 fprintf(stderr, " -> ");
231 After.DebugPrint();
232 }
233}
234
235/// DebugPrint - Print this implicit conversion sequence to standard
236/// error. Useful for debugging overloading issues.
237void ImplicitConversionSequence::DebugPrint() const {
238 switch (ConversionKind) {
239 case StandardConversion:
240 fprintf(stderr, "Standard conversion: ");
241 Standard.DebugPrint();
242 break;
243 case UserDefinedConversion:
244 fprintf(stderr, "User-defined conversion: ");
245 UserDefined.DebugPrint();
246 break;
247 case EllipsisConversion:
248 fprintf(stderr, "Ellipsis conversion");
249 break;
250 case BadConversion:
251 fprintf(stderr, "Bad conversion");
252 break;
253 }
254
255 fprintf(stderr, "\n");
256}
257
258// IsOverload - Determine whether the given New declaration is an
259// overload of the Old declaration. This routine returns false if New
260// and Old cannot be overloaded, e.g., if they are functions with the
261// same signature (C++ 1.3.10) or if the Old declaration isn't a
262// function (or overload set). When it does return false and Old is an
263// OverloadedFunctionDecl, MatchedDecl will be set to point to the
Mike Stump11289f42009-09-09 15:08:12 +0000264// FunctionDecl that New cannot be overloaded with.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265//
266// Example: Given the following input:
267//
268// void f(int, float); // #1
269// void f(int, int); // #2
270// int f(int, int); // #3
271//
272// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000273// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000274//
275// When we process #2, Old is a FunctionDecl for #1. By comparing the
276// parameter types, we see that #1 and #2 are overloaded (since they
277// have different signatures), so this routine returns false;
278// MatchedDecl is unchanged.
279//
280// When we process #3, Old is an OverloadedFunctionDecl containing #1
281// and #2. We compare the signatures of #3 to #1 (they're overloaded,
282// so we do nothing) and then #3 to #2. Since the signatures of #3 and
283// #2 are identical (return types of functions are not part of the
284// signature), IsOverload returns false and MatchedDecl will be set to
285// point to the FunctionDecl for #2.
286bool
John McCall1f82f242009-11-18 22:49:29 +0000287Sema::IsOverload(FunctionDecl *New, LookupResult &Previous, NamedDecl *&Match) {
288 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
289 I != E; ++I) {
290 NamedDecl *Old = (*I)->getUnderlyingDecl();
291 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(Old)) {
292 if (!IsOverload(New, OldT->getTemplatedDecl())) {
293 Match = Old;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000294 return false;
295 }
John McCall1f82f242009-11-18 22:49:29 +0000296 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(Old)) {
297 if (!IsOverload(New, OldF)) {
298 Match = Old;
299 return false;
300 }
301 } else {
302 // (C++ 13p1):
303 // Only function declarations can be overloaded; object and type
304 // declarations cannot be overloaded.
305 Match = Old;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000306 return false;
John McCall1f82f242009-11-18 22:49:29 +0000307 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000308 }
John McCall1f82f242009-11-18 22:49:29 +0000309
310 return true;
311}
312
313bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
314 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
315 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
316
317 // C++ [temp.fct]p2:
318 // A function template can be overloaded with other function templates
319 // and with normal (non-template) functions.
320 if ((OldTemplate == 0) != (NewTemplate == 0))
321 return true;
322
323 // Is the function New an overload of the function Old?
324 QualType OldQType = Context.getCanonicalType(Old->getType());
325 QualType NewQType = Context.getCanonicalType(New->getType());
326
327 // Compare the signatures (C++ 1.3.10) of the two functions to
328 // determine whether they are overloads. If we find any mismatch
329 // in the signature, they are overloads.
330
331 // If either of these functions is a K&R-style function (no
332 // prototype), then we consider them to have matching signatures.
333 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
334 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
335 return false;
336
337 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
338 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
339
340 // The signature of a function includes the types of its
341 // parameters (C++ 1.3.10), which includes the presence or absence
342 // of the ellipsis; see C++ DR 357).
343 if (OldQType != NewQType &&
344 (OldType->getNumArgs() != NewType->getNumArgs() ||
345 OldType->isVariadic() != NewType->isVariadic() ||
346 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
347 NewType->arg_type_begin())))
348 return true;
349
350 // C++ [temp.over.link]p4:
351 // The signature of a function template consists of its function
352 // signature, its return type and its template parameter list. The names
353 // of the template parameters are significant only for establishing the
354 // relationship between the template parameters and the rest of the
355 // signature.
356 //
357 // We check the return type and template parameter lists for function
358 // templates first; the remaining checks follow.
359 if (NewTemplate &&
360 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
361 OldTemplate->getTemplateParameters(),
362 false, TPL_TemplateMatch) ||
363 OldType->getResultType() != NewType->getResultType()))
364 return true;
365
366 // If the function is a class member, its signature includes the
367 // cv-qualifiers (if any) on the function itself.
368 //
369 // As part of this, also check whether one of the member functions
370 // is static, in which case they are not overloads (C++
371 // 13.1p2). While not part of the definition of the signature,
372 // this check is important to determine whether these functions
373 // can be overloaded.
374 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
375 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
376 if (OldMethod && NewMethod &&
377 !OldMethod->isStatic() && !NewMethod->isStatic() &&
378 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
379 return true;
380
381 // The signatures match; this is not an overload.
382 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000383}
384
Douglas Gregor8e1cf602008-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 Gregor5251f1b2008-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 Gregor2fe98832008-11-03 19:09:14 +0000403///
404/// If @p SuppressUserConversions, then user-defined conversions are
405/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000406/// If @p AllowExplicit, then explicit user-defined conversions are
407/// permitted.
Sebastian Redl42e92c42009-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.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000410/// If @p UserCast, the implicit conversion is being done for a user-specified
411/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000412ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000413Sema::TryImplicitConversion(Expr* From, QualType ToType,
414 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000415 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000416 bool InOverloadResolution,
417 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000418 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000419 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000420 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000421 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000422 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000423 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000424 (UserDefResult = IsUserDefinedConversion(From, ToType,
425 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000426 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000427 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000428 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000429 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000430 // C++ [over.ics.user]p4:
431 // A conversion of an expression of class type to the same class
432 // type is given Exact Match rank, and a conversion of an
433 // expression of class type to a base class of that type is
434 // given Conversion rank, in spite of the fact that a copy
435 // constructor (i.e., a user-defined conversion function) is
436 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000437 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000438 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000439 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000440 = Context.getCanonicalType(From->getType().getUnqualifiedType());
441 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
442 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000443 // Turn this into a "standard" conversion sequence, so that it
444 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000445 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
446 ICS.Standard.setAsIdentityConversion();
447 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
448 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000449 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000450 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000451 ICS.Standard.Second = ICK_Derived_To_Base;
452 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000453 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000454
455 // C++ [over.best.ics]p4:
456 // However, when considering the argument of a user-defined
457 // conversion function that is a candidate by 13.3.1.3 when
458 // invoked for the copying of the temporary in the second step
459 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
460 // 13.3.1.6 in all cases, only standard conversion sequences and
461 // ellipsis conversion sequences are allowed.
462 if (SuppressUserConversions &&
463 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
464 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000465 } else {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000466 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000467 if (UserDefResult == OR_Ambiguous) {
468 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
469 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian574de2c2009-10-12 17:51:19 +0000470 if (Cand->Viable)
471 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000472 }
473 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000474
475 return ICS;
476}
477
478/// IsStandardConversion - Determines whether there is a standard
479/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
480/// expression From to the type ToType. Standard conversion sequences
481/// only consider non-class types; for conversions that involve class
482/// types, use TryImplicitConversion. If a conversion exists, SCS will
483/// contain the standard conversion sequence required to perform this
484/// conversion and this routine will return true. Otherwise, this
485/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000486bool
487Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000488 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000489 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000490 QualType FromType = From->getType();
491
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000492 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000493 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000494 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000495 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000496 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000497 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000499 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000500 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000501 if (FromType->isRecordType() || ToType->isRecordType()) {
502 if (getLangOptions().CPlusPlus)
503 return false;
504
Mike Stump11289f42009-09-09 15:08:12 +0000505 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000506 }
507
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000508 // The first conversion can be an lvalue-to-rvalue conversion,
509 // array-to-pointer conversion, or function-to-pointer conversion
510 // (C++ 4p1).
511
Mike Stump11289f42009-09-09 15:08:12 +0000512 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513 // An lvalue (3.10) of a non-function, non-array type T can be
514 // converted to an rvalue.
515 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000516 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000517 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000518 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000519 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520
521 // If T is a non-class type, the type of the rvalue is the
522 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000523 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
524 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000525 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000526 } else if (FromType->isArrayType()) {
527 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000528 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000529
530 // An lvalue or rvalue of type "array of N T" or "array of unknown
531 // bound of T" can be converted to an rvalue of type "pointer to
532 // T" (C++ 4.2p1).
533 FromType = Context.getArrayDecayedType(FromType);
534
535 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
536 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000537 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000538
539 // For the purpose of ranking in overload resolution
540 // (13.3.3.1.1), this conversion is considered an
541 // array-to-pointer conversion followed by a qualification
542 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000543 SCS.Second = ICK_Identity;
544 SCS.Third = ICK_Qualification;
545 SCS.ToTypePtr = ToType.getAsOpaquePtr();
546 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000547 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000548 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
549 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000550 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000551
552 // An lvalue of function type T can be converted to an rvalue of
553 // type "pointer to T." The result is a pointer to the
554 // function. (C++ 4.3p1).
555 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000556 } else if (FunctionDecl *Fn
Douglas Gregorcd695e52008-11-10 20:40:00 +0000557 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000558 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000559 SCS.First = ICK_Function_To_Pointer;
560
561 // We were able to resolve the address of the overloaded function,
562 // so we can convert to the type of that function.
563 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000564 if (ToType->isLValueReferenceType())
565 FromType = Context.getLValueReferenceType(FromType);
566 else if (ToType->isRValueReferenceType())
567 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000568 else if (ToType->isMemberPointerType()) {
569 // Resolve address only succeeds if both sides are member pointers,
570 // but it doesn't have to be the same class. See DR 247.
571 // Note that this means that the type of &Derived::fn can be
572 // Ret (Base::*)(Args) if the fn overload actually found is from the
573 // base class, even if it was brought into the derived class via a
574 // using declaration. The standard isn't clear on this issue at all.
575 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
576 FromType = Context.getMemberPointerType(FromType,
577 Context.getTypeDeclType(M->getParent()).getTypePtr());
578 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000579 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000580 } else {
581 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000582 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000583 }
584
585 // The second conversion can be an integral promotion, floating
586 // point promotion, integral conversion, floating point conversion,
587 // floating-integral conversion, pointer conversion,
588 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000589 // For overloading in C, this can also be a "compatible-type"
590 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000591 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000592 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000593 // The unqualified versions of the types are the same: there's no
594 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000595 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000596 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000597 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000598 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000599 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000600 } else if (IsFloatingPointPromotion(FromType, ToType)) {
601 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000602 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000603 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000604 } else if (IsComplexPromotion(FromType, ToType)) {
605 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000606 SCS.Second = ICK_Complex_Promotion;
607 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000608 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000609 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000610 // Integral conversions (C++ 4.7).
611 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000612 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000613 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000614 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
615 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000616 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000617 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000618 } else if (FromType->isComplexType() && ToType->isComplexType()) {
619 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000620 SCS.Second = ICK_Complex_Conversion;
621 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000622 } else if ((FromType->isFloatingType() &&
623 ToType->isIntegralType() && (!ToType->isBooleanType() &&
624 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000625 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000626 ToType->isFloatingType())) {
627 // Floating-integral conversions (C++ 4.9).
628 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000629 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000630 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000631 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
632 (ToType->isComplexType() && FromType->isArithmeticType())) {
633 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000634 SCS.Second = ICK_Complex_Real;
635 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000636 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
637 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000638 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000639 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000640 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000641 } else if (IsMemberPointerConversion(From, FromType, ToType,
642 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000643 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000644 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000645 } else if (ToType->isBooleanType() &&
646 (FromType->isArithmeticType() ||
647 FromType->isEnumeralType() ||
648 FromType->isPointerType() ||
649 FromType->isBlockPointerType() ||
650 FromType->isMemberPointerType() ||
651 FromType->isNullPtrType())) {
652 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000653 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000654 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000655 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000656 Context.typesAreCompatible(ToType, FromType)) {
657 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000658 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000659 } else {
660 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000661 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000662 }
663
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000664 QualType CanonFrom;
665 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000666 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000667 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000668 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000669 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000670 CanonFrom = Context.getCanonicalType(FromType);
671 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000672 } else {
673 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000674 SCS.Third = ICK_Identity;
675
Mike Stump11289f42009-09-09 15:08:12 +0000676 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000677 // [...] Any difference in top-level cv-qualification is
678 // subsumed by the initialization itself and does not constitute
679 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000680 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000681 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000682 if (CanonFrom.getLocalUnqualifiedType()
683 == CanonTo.getLocalUnqualifiedType() &&
684 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000685 FromType = ToType;
686 CanonFrom = CanonTo;
687 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000688 }
689
690 // If we have not converted the argument type to the parameter type,
691 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000692 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000693 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000694
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000695 SCS.ToTypePtr = FromType.getAsOpaquePtr();
696 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000697}
698
699/// IsIntegralPromotion - Determines whether the conversion from the
700/// expression From (whose potentially-adjusted type is FromType) to
701/// ToType is an integral promotion (C++ 4.5). If so, returns true and
702/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000703bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000704 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000705 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000706 if (!To) {
707 return false;
708 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000709
710 // An rvalue of type char, signed char, unsigned char, short int, or
711 // unsigned short int can be converted to an rvalue of type int if
712 // int can represent all the values of the source type; otherwise,
713 // the source rvalue can be converted to an rvalue of type unsigned
714 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000715 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000716 if (// We can promote any signed, promotable integer type to an int
717 (FromType->isSignedIntegerType() ||
718 // We can promote any unsigned integer type whose size is
719 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000720 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000721 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000722 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000723 }
724
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000725 return To->getKind() == BuiltinType::UInt;
726 }
727
728 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
729 // can be converted to an rvalue of the first of the following types
730 // that can represent all the values of its underlying type: int,
731 // unsigned int, long, or unsigned long (C++ 4.5p2).
732 if ((FromType->isEnumeralType() || FromType->isWideCharType())
733 && ToType->isIntegerType()) {
734 // Determine whether the type we're converting from is signed or
735 // unsigned.
736 bool FromIsSigned;
737 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall9dd450b2009-09-21 23:43:11 +0000738 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000739 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
740 FromIsSigned = UnderlyingType->isSignedIntegerType();
741 } else {
742 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
743 FromIsSigned = true;
744 }
745
746 // The types we'll try to promote to, in the appropriate
747 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000748 QualType PromoteTypes[6] = {
749 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000750 Context.LongTy, Context.UnsignedLongTy ,
751 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000752 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000753 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000754 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
755 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000756 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000757 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
758 // We found the type that we can promote to. If this is the
759 // type we wanted, we have a promotion. Otherwise, no
760 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000761 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000762 }
763 }
764 }
765
766 // An rvalue for an integral bit-field (9.6) can be converted to an
767 // rvalue of type int if int can represent all the values of the
768 // bit-field; otherwise, it can be converted to unsigned int if
769 // unsigned int can represent all the values of the bit-field. If
770 // the bit-field is larger yet, no integral promotion applies to
771 // it. If the bit-field has an enumerated type, it is treated as any
772 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000773 // FIXME: We should delay checking of bit-fields until we actually perform the
774 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000775 using llvm::APSInt;
776 if (From)
777 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000778 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000779 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
780 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
781 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
782 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000783
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000784 // Are we promoting to an int from a bitfield that fits in an int?
785 if (BitWidth < ToSize ||
786 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
787 return To->getKind() == BuiltinType::Int;
788 }
Mike Stump11289f42009-09-09 15:08:12 +0000789
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000790 // Are we promoting to an unsigned int from an unsigned bitfield
791 // that fits into an unsigned int?
792 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
793 return To->getKind() == BuiltinType::UInt;
794 }
Mike Stump11289f42009-09-09 15:08:12 +0000795
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000796 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000797 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000798 }
Mike Stump11289f42009-09-09 15:08:12 +0000799
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000800 // An rvalue of type bool can be converted to an rvalue of type int,
801 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000802 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000803 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000804 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000805
806 return false;
807}
808
809/// IsFloatingPointPromotion - Determines whether the conversion from
810/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
811/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000812bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000813 /// An rvalue of type float can be converted to an rvalue of type
814 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000815 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
816 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000817 if (FromBuiltin->getKind() == BuiltinType::Float &&
818 ToBuiltin->getKind() == BuiltinType::Double)
819 return true;
820
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000821 // C99 6.3.1.5p1:
822 // When a float is promoted to double or long double, or a
823 // double is promoted to long double [...].
824 if (!getLangOptions().CPlusPlus &&
825 (FromBuiltin->getKind() == BuiltinType::Float ||
826 FromBuiltin->getKind() == BuiltinType::Double) &&
827 (ToBuiltin->getKind() == BuiltinType::LongDouble))
828 return true;
829 }
830
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000831 return false;
832}
833
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000834/// \brief Determine if a conversion is a complex promotion.
835///
836/// A complex promotion is defined as a complex -> complex conversion
837/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000838/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000839bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000840 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000841 if (!FromComplex)
842 return false;
843
John McCall9dd450b2009-09-21 23:43:11 +0000844 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000845 if (!ToComplex)
846 return false;
847
848 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000849 ToComplex->getElementType()) ||
850 IsIntegralPromotion(0, FromComplex->getElementType(),
851 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000852}
853
Douglas Gregor237f96c2008-11-26 23:31:11 +0000854/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
855/// the pointer type FromPtr to a pointer to type ToPointee, with the
856/// same type qualifiers as FromPtr has on its pointee type. ToType,
857/// if non-empty, will be a pointer to ToType that may or may not have
858/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000859static QualType
860BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000861 QualType ToPointee, QualType ToType,
862 ASTContext &Context) {
863 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
864 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000865 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000866
867 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000868 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000869 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000870 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000871 return ToType;
872
873 // Build a pointer to ToPointee. It has the right qualifiers
874 // already.
875 return Context.getPointerType(ToPointee);
876 }
877
878 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000879 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000880 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
881 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000882}
883
Mike Stump11289f42009-09-09 15:08:12 +0000884static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000885 bool InOverloadResolution,
886 ASTContext &Context) {
887 // Handle value-dependent integral null pointer constants correctly.
888 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
889 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
890 Expr->getType()->isIntegralType())
891 return !InOverloadResolution;
892
Douglas Gregor56751b52009-09-25 04:25:58 +0000893 return Expr->isNullPointerConstant(Context,
894 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
895 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000896}
Mike Stump11289f42009-09-09 15:08:12 +0000897
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000898/// IsPointerConversion - Determines whether the conversion of the
899/// expression From, which has the (possibly adjusted) type FromType,
900/// can be converted to the type ToType via a pointer conversion (C++
901/// 4.10). If so, returns true and places the converted type (that
902/// might differ from ToType in its cv-qualifiers at some level) into
903/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000904///
Douglas Gregora29dc052008-11-27 01:19:21 +0000905/// This routine also supports conversions to and from block pointers
906/// and conversions with Objective-C's 'id', 'id<protocols...>', and
907/// pointers to interfaces. FIXME: Once we've determined the
908/// appropriate overloading rules for Objective-C, we may want to
909/// split the Objective-C checks into a different routine; however,
910/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000911/// conversions, so for now they live here. IncompatibleObjC will be
912/// set if the conversion is an allowed Objective-C conversion that
913/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000914bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000915 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000916 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000917 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000918 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000919 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
920 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000921
Mike Stump11289f42009-09-09 15:08:12 +0000922 // Conversion from a null pointer constant to any Objective-C pointer type.
923 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000924 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000925 ConvertedType = ToType;
926 return true;
927 }
928
Douglas Gregor231d1c62008-11-27 00:15:41 +0000929 // Blocks: Block pointers can be converted to void*.
930 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000931 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000932 ConvertedType = ToType;
933 return true;
934 }
935 // Blocks: A null pointer constant can be converted to a block
936 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000937 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000938 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000939 ConvertedType = ToType;
940 return true;
941 }
942
Sebastian Redl576fd422009-05-10 18:38:11 +0000943 // If the left-hand-side is nullptr_t, the right side can be a null
944 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000945 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000946 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000947 ConvertedType = ToType;
948 return true;
949 }
950
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000951 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000952 if (!ToTypePtr)
953 return false;
954
955 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000956 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000957 ConvertedType = ToType;
958 return true;
959 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000960
Douglas Gregor237f96c2008-11-26 23:31:11 +0000961 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000962 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000963 if (!FromTypePtr)
964 return false;
965
966 QualType FromPointeeType = FromTypePtr->getPointeeType();
967 QualType ToPointeeType = ToTypePtr->getPointeeType();
968
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000969 // An rvalue of type "pointer to cv T," where T is an object type,
970 // can be converted to an rvalue of type "pointer to cv void" (C++
971 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000972 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000973 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000974 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000975 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000976 return true;
977 }
978
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000979 // When we're overloading in C, we allow a special kind of pointer
980 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +0000981 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000982 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000983 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000984 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +0000985 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000986 return true;
987 }
988
Douglas Gregor5c407d92008-10-23 00:40:37 +0000989 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +0000990 //
Douglas Gregor5c407d92008-10-23 00:40:37 +0000991 // An rvalue of type "pointer to cv D," where D is a class type,
992 // can be converted to an rvalue of type "pointer to cv B," where
993 // B is a base class (clause 10) of D. If B is an inaccessible
994 // (clause 11) or ambiguous (10.2) base class of D, a program that
995 // necessitates this conversion is ill-formed. The result of the
996 // conversion is a pointer to the base class sub-object of the
997 // derived class object. The null pointer value is converted to
998 // the null pointer value of the destination type.
999 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001000 // Note that we do not check for ambiguity or inaccessibility
1001 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001002 if (getLangOptions().CPlusPlus &&
1003 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001004 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001005 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001006 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001007 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001008 ToType, Context);
1009 return true;
1010 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001011
Douglas Gregora119f102008-12-19 19:13:09 +00001012 return false;
1013}
1014
1015/// isObjCPointerConversion - Determines whether this is an
1016/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1017/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001018bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001019 QualType& ConvertedType,
1020 bool &IncompatibleObjC) {
1021 if (!getLangOptions().ObjC1)
1022 return false;
1023
Steve Naroff7cae42b2009-07-10 23:34:53 +00001024 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001025 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001026 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001027 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001028
Steve Naroff7cae42b2009-07-10 23:34:53 +00001029 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001030 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001031 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001032 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001033 ConvertedType = ToType;
1034 return true;
1035 }
1036 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001037 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001038 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001039 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001040 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001041 ConvertedType = ToType;
1042 return true;
1043 }
1044 // Objective C++: We're able to convert from a pointer to an
1045 // interface to a pointer to a different interface.
1046 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1047 ConvertedType = ToType;
1048 return true;
1049 }
1050
1051 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1052 // Okay: this is some kind of implicit downcast of Objective-C
1053 // interfaces, which is permitted. However, we're going to
1054 // complain about it.
1055 IncompatibleObjC = true;
1056 ConvertedType = FromType;
1057 return true;
1058 }
Mike Stump11289f42009-09-09 15:08:12 +00001059 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001060 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001061 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001062 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001063 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001064 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001065 ToPointeeType = ToBlockPtr->getPointeeType();
1066 else
Douglas Gregora119f102008-12-19 19:13:09 +00001067 return false;
1068
Douglas Gregor033f56d2008-12-23 00:53:59 +00001069 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001070 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001071 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001072 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001073 FromPointeeType = FromBlockPtr->getPointeeType();
1074 else
Douglas Gregora119f102008-12-19 19:13:09 +00001075 return false;
1076
Douglas Gregora119f102008-12-19 19:13:09 +00001077 // If we have pointers to pointers, recursively check whether this
1078 // is an Objective-C conversion.
1079 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1080 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1081 IncompatibleObjC)) {
1082 // We always complain about this conversion.
1083 IncompatibleObjC = true;
1084 ConvertedType = ToType;
1085 return true;
1086 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001087 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001088 // differences in the argument and result types are in Objective-C
1089 // pointer conversions. If so, we permit the conversion (but
1090 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001091 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001092 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001093 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001094 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001095 if (FromFunctionType && ToFunctionType) {
1096 // If the function types are exactly the same, this isn't an
1097 // Objective-C pointer conversion.
1098 if (Context.getCanonicalType(FromPointeeType)
1099 == Context.getCanonicalType(ToPointeeType))
1100 return false;
1101
1102 // Perform the quick checks that will tell us whether these
1103 // function types are obviously different.
1104 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1105 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1106 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1107 return false;
1108
1109 bool HasObjCConversion = false;
1110 if (Context.getCanonicalType(FromFunctionType->getResultType())
1111 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1112 // Okay, the types match exactly. Nothing to do.
1113 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1114 ToFunctionType->getResultType(),
1115 ConvertedType, IncompatibleObjC)) {
1116 // Okay, we have an Objective-C pointer conversion.
1117 HasObjCConversion = true;
1118 } else {
1119 // Function types are too different. Abort.
1120 return false;
1121 }
Mike Stump11289f42009-09-09 15:08:12 +00001122
Douglas Gregora119f102008-12-19 19:13:09 +00001123 // Check argument types.
1124 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1125 ArgIdx != NumArgs; ++ArgIdx) {
1126 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1127 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1128 if (Context.getCanonicalType(FromArgType)
1129 == Context.getCanonicalType(ToArgType)) {
1130 // Okay, the types match exactly. Nothing to do.
1131 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1132 ConvertedType, IncompatibleObjC)) {
1133 // Okay, we have an Objective-C pointer conversion.
1134 HasObjCConversion = true;
1135 } else {
1136 // Argument types are too different. Abort.
1137 return false;
1138 }
1139 }
1140
1141 if (HasObjCConversion) {
1142 // We had an Objective-C conversion. Allow this pointer
1143 // conversion, but complain about it.
1144 ConvertedType = ToType;
1145 IncompatibleObjC = true;
1146 return true;
1147 }
1148 }
1149
Sebastian Redl72b597d2009-01-25 19:43:20 +00001150 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001151}
1152
Douglas Gregor39c16d42008-10-24 04:54:22 +00001153/// CheckPointerConversion - Check the pointer conversion from the
1154/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001155/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001156/// conversions for which IsPointerConversion has already returned
1157/// true. It returns true and produces a diagnostic if there was an
1158/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001159bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001160 CastExpr::CastKind &Kind,
1161 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001162 QualType FromType = From->getType();
1163
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001164 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1165 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001166 QualType FromPointeeType = FromPtrType->getPointeeType(),
1167 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001168
Douglas Gregor39c16d42008-10-24 04:54:22 +00001169 if (FromPointeeType->isRecordType() &&
1170 ToPointeeType->isRecordType()) {
1171 // We must have a derived-to-base conversion. Check an
1172 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001173 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1174 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001175 From->getSourceRange(),
1176 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001177 return true;
1178
1179 // The conversion was successful.
1180 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001181 }
1182 }
Mike Stump11289f42009-09-09 15:08:12 +00001183 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001184 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001185 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001186 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001187 // Objective-C++ conversions are always okay.
1188 // FIXME: We should have a different class of conversions for the
1189 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001190 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001191 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001192
Steve Naroff7cae42b2009-07-10 23:34:53 +00001193 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001194 return false;
1195}
1196
Sebastian Redl72b597d2009-01-25 19:43:20 +00001197/// IsMemberPointerConversion - Determines whether the conversion of the
1198/// expression From, which has the (possibly adjusted) type FromType, can be
1199/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1200/// If so, returns true and places the converted type (that might differ from
1201/// ToType in its cv-qualifiers at some level) into ConvertedType.
1202bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001203 QualType ToType,
1204 bool InOverloadResolution,
1205 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001206 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001207 if (!ToTypePtr)
1208 return false;
1209
1210 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001211 if (From->isNullPointerConstant(Context,
1212 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1213 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001214 ConvertedType = ToType;
1215 return true;
1216 }
1217
1218 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001219 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001220 if (!FromTypePtr)
1221 return false;
1222
1223 // A pointer to member of B can be converted to a pointer to member of D,
1224 // where D is derived from B (C++ 4.11p2).
1225 QualType FromClass(FromTypePtr->getClass(), 0);
1226 QualType ToClass(ToTypePtr->getClass(), 0);
1227 // FIXME: What happens when these are dependent? Is this function even called?
1228
1229 if (IsDerivedFrom(ToClass, FromClass)) {
1230 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1231 ToClass.getTypePtr());
1232 return true;
1233 }
1234
1235 return false;
1236}
1237
1238/// CheckMemberPointerConversion - Check the member pointer conversion from the
1239/// expression From to the type ToType. This routine checks for ambiguous or
1240/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1241/// for which IsMemberPointerConversion has already returned true. It returns
1242/// true and produces a diagnostic if there was an error, or returns false
1243/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001244bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001245 CastExpr::CastKind &Kind,
1246 bool IgnoreBaseAccess) {
1247 (void)IgnoreBaseAccess;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001248 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001249 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001250 if (!FromPtrType) {
1251 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001252 assert(From->isNullPointerConstant(Context,
1253 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001254 "Expr must be null pointer constant!");
1255 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001256 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001257 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001258
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001259 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001260 assert(ToPtrType && "No member pointer cast has a target type "
1261 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001262
Sebastian Redled8f2002009-01-28 18:33:18 +00001263 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1264 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001265
Sebastian Redled8f2002009-01-28 18:33:18 +00001266 // FIXME: What about dependent types?
1267 assert(FromClass->isRecordType() && "Pointer into non-class.");
1268 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001269
Douglas Gregor36d1b142009-10-06 17:59:45 +00001270 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1271 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001272 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1273 assert(DerivationOkay &&
1274 "Should not have been called if derivation isn't OK.");
1275 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001276
Sebastian Redled8f2002009-01-28 18:33:18 +00001277 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1278 getUnqualifiedType())) {
1279 // Derivation is ambiguous. Redo the check to find the exact paths.
1280 Paths.clear();
1281 Paths.setRecordingPaths(true);
1282 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1283 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1284 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001285
Sebastian Redled8f2002009-01-28 18:33:18 +00001286 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1287 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1288 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1289 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001290 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001291
Douglas Gregor89ee6822009-02-28 01:32:25 +00001292 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001293 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1294 << FromClass << ToClass << QualType(VBase, 0)
1295 << From->getSourceRange();
1296 return true;
1297 }
1298
Anders Carlssond7923c62009-08-22 23:33:40 +00001299 // Must be a base to derived member conversion.
1300 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001301 return false;
1302}
1303
Douglas Gregor9a657932008-10-21 23:43:52 +00001304/// IsQualificationConversion - Determines whether the conversion from
1305/// an rvalue of type FromType to ToType is a qualification conversion
1306/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001307bool
1308Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001309 FromType = Context.getCanonicalType(FromType);
1310 ToType = Context.getCanonicalType(ToType);
1311
1312 // If FromType and ToType are the same type, this is not a
1313 // qualification conversion.
1314 if (FromType == ToType)
1315 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001316
Douglas Gregor9a657932008-10-21 23:43:52 +00001317 // (C++ 4.4p4):
1318 // A conversion can add cv-qualifiers at levels other than the first
1319 // in multi-level pointers, subject to the following rules: [...]
1320 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001321 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001322 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001323 // Within each iteration of the loop, we check the qualifiers to
1324 // determine if this still looks like a qualification
1325 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001326 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001327 // until there are no more pointers or pointers-to-members left to
1328 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001329 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001330
1331 // -- for every j > 0, if const is in cv 1,j then const is in cv
1332 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001333 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001334 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001335
Douglas Gregor9a657932008-10-21 23:43:52 +00001336 // -- if the cv 1,j and cv 2,j are different, then const is in
1337 // every cv for 0 < k < j.
1338 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001339 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001340 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001341
Douglas Gregor9a657932008-10-21 23:43:52 +00001342 // Keep track of whether all prior cv-qualifiers in the "to" type
1343 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001344 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001345 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001346 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001347
1348 // We are left with FromType and ToType being the pointee types
1349 // after unwrapping the original FromType and ToType the same number
1350 // of types. If we unwrapped any pointers, and if FromType and
1351 // ToType have the same unqualified type (since we checked
1352 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001353 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001354}
1355
Douglas Gregor05155d82009-08-21 23:19:43 +00001356/// \brief Given a function template or function, extract the function template
1357/// declaration (if any) and the underlying function declaration.
1358template<typename T>
1359static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1360 FunctionTemplateDecl *&FunctionTemplate) {
1361 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1362 if (FunctionTemplate)
1363 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1364 else
1365 Function = cast<T>(Orig);
1366}
1367
Douglas Gregor576e98c2009-01-30 23:27:23 +00001368/// Determines whether there is a user-defined conversion sequence
1369/// (C++ [over.ics.user]) that converts expression From to the type
1370/// ToType. If such a conversion exists, User will contain the
1371/// user-defined conversion sequence that performs such a conversion
1372/// and this routine will return true. Otherwise, this routine returns
1373/// false and User is unspecified.
1374///
1375/// \param AllowConversionFunctions true if the conversion should
1376/// consider conversion functions at all. If false, only constructors
1377/// will be considered.
1378///
1379/// \param AllowExplicit true if the conversion should consider C++0x
1380/// "explicit" conversion functions as well as non-explicit conversion
1381/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001382///
1383/// \param ForceRValue true if the expression should be treated as an rvalue
1384/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001385/// \param UserCast true if looking for user defined conversion for a static
1386/// cast.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001387Sema::OverloadingResult Sema::IsUserDefinedConversion(
1388 Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001389 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001390 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001391 bool AllowConversionFunctions,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001392 bool AllowExplicit, bool ForceRValue,
1393 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001394 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001395 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1396 // We're not going to find any constructors.
1397 } else if (CXXRecordDecl *ToRecordDecl
1398 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001399 // C++ [over.match.ctor]p1:
1400 // When objects of class type are direct-initialized (8.5), or
1401 // copy-initialized from an expression of the same or a
1402 // derived class type (8.5), overload resolution selects the
1403 // constructor. [...] For copy-initialization, the candidate
1404 // functions are all the converting constructors (12.3.1) of
1405 // that class. The argument list is the expression-list within
1406 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001407 bool SuppressUserConversions = !UserCast;
1408 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1409 IsDerivedFrom(From->getType(), ToType)) {
1410 SuppressUserConversions = false;
1411 AllowConversionFunctions = false;
1412 }
1413
Mike Stump11289f42009-09-09 15:08:12 +00001414 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001415 = Context.DeclarationNames.getCXXConstructorName(
1416 Context.getCanonicalType(ToType).getUnqualifiedType());
1417 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001418 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001419 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001420 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001421 // Find the constructor (which may be a template).
1422 CXXConstructorDecl *Constructor = 0;
1423 FunctionTemplateDecl *ConstructorTmpl
1424 = dyn_cast<FunctionTemplateDecl>(*Con);
1425 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001426 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001427 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1428 else
1429 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001430
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001431 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001432 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001433 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001434 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001435 1, CandidateSet,
1436 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001437 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001438 // Allow one user-defined conversion when user specifies a
1439 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001440 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001441 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001442 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001443 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001444 }
1445 }
1446
Douglas Gregor576e98c2009-01-30 23:27:23 +00001447 if (!AllowConversionFunctions) {
1448 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001449 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1450 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001451 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001452 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001453 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001454 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001455 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001456 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1457 // Add all of the conversion functions as candidates.
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001458 OverloadedFunctionDecl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001459 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001460 for (OverloadedFunctionDecl::function_iterator Func
1461 = Conversions->function_begin();
1462 Func != Conversions->function_end(); ++Func) {
1463 CXXConversionDecl *Conv;
1464 FunctionTemplateDecl *ConvTemplate;
1465 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1466 if (ConvTemplate)
1467 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1468 else
1469 Conv = dyn_cast<CXXConversionDecl>(*Func);
1470
1471 if (AllowExplicit || !Conv->isExplicit()) {
1472 if (ConvTemplate)
1473 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1474 CandidateSet);
1475 else
1476 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1477 }
1478 }
1479 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001480 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001481
1482 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001483 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001484 case OR_Success:
1485 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001486 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001487 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1488 // C++ [over.ics.user]p1:
1489 // If the user-defined conversion is specified by a
1490 // constructor (12.3.1), the initial standard conversion
1491 // sequence converts the source type to the type required by
1492 // the argument of the constructor.
1493 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001494 QualType ThisType = Constructor->getThisType(Context);
Fariborz Jahanian55824512009-11-06 00:23:08 +00001495 if (Best->Conversions[0].ConversionKind ==
1496 ImplicitConversionSequence::EllipsisConversion)
1497 User.EllipsisConversion = true;
1498 else {
1499 User.Before = Best->Conversions[0].Standard;
1500 User.EllipsisConversion = false;
1501 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001502 User.ConversionFunction = Constructor;
1503 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001504 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001505 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001506 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001507 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001508 } else if (CXXConversionDecl *Conversion
1509 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1510 // C++ [over.ics.user]p1:
1511 //
1512 // [...] If the user-defined conversion is specified by a
1513 // conversion function (12.3.2), the initial standard
1514 // conversion sequence converts the source type to the
1515 // implicit object parameter of the conversion function.
1516 User.Before = Best->Conversions[0].Standard;
1517 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001518 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001519
1520 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001521 // The second standard conversion sequence converts the
1522 // result of the user-defined conversion to the target type
1523 // for the sequence. Since an implicit conversion sequence
1524 // is an initialization, the special rules for
1525 // initialization by user-defined conversion apply when
1526 // selecting the best user-defined conversion for a
1527 // user-defined conversion sequence (see 13.3.3 and
1528 // 13.3.3.1).
1529 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001530 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001531 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001532 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001533 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001534 }
Mike Stump11289f42009-09-09 15:08:12 +00001535
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001536 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001537 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001538 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001539 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001540 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001541
1542 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001543 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001544 }
1545
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001546 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001547}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001548
1549bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001550Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001551 ImplicitConversionSequence ICS;
1552 OverloadCandidateSet CandidateSet;
1553 OverloadingResult OvResult =
1554 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1555 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001556 if (OvResult == OR_Ambiguous)
1557 Diag(From->getSourceRange().getBegin(),
1558 diag::err_typecheck_ambiguous_condition)
1559 << From->getType() << ToType << From->getSourceRange();
1560 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1561 Diag(From->getSourceRange().getBegin(),
1562 diag::err_typecheck_nonviable_condition)
1563 << From->getType() << ToType << From->getSourceRange();
1564 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001565 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00001566 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001567 return true;
1568}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001569
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001570/// CompareImplicitConversionSequences - Compare two implicit
1571/// conversion sequences to determine whether one is better than the
1572/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001573ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001574Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1575 const ImplicitConversionSequence& ICS2)
1576{
1577 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1578 // conversion sequences (as defined in 13.3.3.1)
1579 // -- a standard conversion sequence (13.3.3.1.1) is a better
1580 // conversion sequence than a user-defined conversion sequence or
1581 // an ellipsis conversion sequence, and
1582 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1583 // conversion sequence than an ellipsis conversion sequence
1584 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001585 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001586 if (ICS1.ConversionKind < ICS2.ConversionKind)
1587 return ImplicitConversionSequence::Better;
1588 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1589 return ImplicitConversionSequence::Worse;
1590
1591 // Two implicit conversion sequences of the same form are
1592 // indistinguishable conversion sequences unless one of the
1593 // following rules apply: (C++ 13.3.3.2p3):
1594 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1595 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001596 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001597 ImplicitConversionSequence::UserDefinedConversion) {
1598 // User-defined conversion sequence U1 is a better conversion
1599 // sequence than another user-defined conversion sequence U2 if
1600 // they contain the same user-defined conversion function or
1601 // constructor and if the second standard conversion sequence of
1602 // U1 is better than the second standard conversion sequence of
1603 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001604 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001605 ICS2.UserDefined.ConversionFunction)
1606 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1607 ICS2.UserDefined.After);
1608 }
1609
1610 return ImplicitConversionSequence::Indistinguishable;
1611}
1612
1613/// CompareStandardConversionSequences - Compare two standard
1614/// conversion sequences to determine whether one is better than the
1615/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001616ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001617Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1618 const StandardConversionSequence& SCS2)
1619{
1620 // Standard conversion sequence S1 is a better conversion sequence
1621 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1622
1623 // -- S1 is a proper subsequence of S2 (comparing the conversion
1624 // sequences in the canonical form defined by 13.3.3.1.1,
1625 // excluding any Lvalue Transformation; the identity conversion
1626 // sequence is considered to be a subsequence of any
1627 // non-identity conversion sequence) or, if not that,
1628 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1629 // Neither is a proper subsequence of the other. Do nothing.
1630 ;
1631 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1632 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001633 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001634 SCS1.Third == ICK_Identity))
1635 // SCS1 is a proper subsequence of SCS2.
1636 return ImplicitConversionSequence::Better;
1637 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1638 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001639 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001640 SCS2.Third == ICK_Identity))
1641 // SCS2 is a proper subsequence of SCS1.
1642 return ImplicitConversionSequence::Worse;
1643
1644 // -- the rank of S1 is better than the rank of S2 (by the rules
1645 // defined below), or, if not that,
1646 ImplicitConversionRank Rank1 = SCS1.getRank();
1647 ImplicitConversionRank Rank2 = SCS2.getRank();
1648 if (Rank1 < Rank2)
1649 return ImplicitConversionSequence::Better;
1650 else if (Rank2 < Rank1)
1651 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001652
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001653 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1654 // are indistinguishable unless one of the following rules
1655 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001656
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001657 // A conversion that is not a conversion of a pointer, or
1658 // pointer to member, to bool is better than another conversion
1659 // that is such a conversion.
1660 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1661 return SCS2.isPointerConversionToBool()
1662 ? ImplicitConversionSequence::Better
1663 : ImplicitConversionSequence::Worse;
1664
Douglas Gregor5c407d92008-10-23 00:40:37 +00001665 // C++ [over.ics.rank]p4b2:
1666 //
1667 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001668 // conversion of B* to A* is better than conversion of B* to
1669 // void*, and conversion of A* to void* is better than conversion
1670 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001671 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001672 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001673 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001674 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001675 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1676 // Exactly one of the conversion sequences is a conversion to
1677 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001678 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1679 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001680 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1681 // Neither conversion sequence converts to a void pointer; compare
1682 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001683 if (ImplicitConversionSequence::CompareKind DerivedCK
1684 = CompareDerivedToBaseConversions(SCS1, SCS2))
1685 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001686 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1687 // Both conversion sequences are conversions to void
1688 // pointers. Compare the source types to determine if there's an
1689 // inheritance relationship in their sources.
1690 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1691 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1692
1693 // Adjust the types we're converting from via the array-to-pointer
1694 // conversion, if we need to.
1695 if (SCS1.First == ICK_Array_To_Pointer)
1696 FromType1 = Context.getArrayDecayedType(FromType1);
1697 if (SCS2.First == ICK_Array_To_Pointer)
1698 FromType2 = Context.getArrayDecayedType(FromType2);
1699
Mike Stump11289f42009-09-09 15:08:12 +00001700 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001701 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001702 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001703 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001704
1705 if (IsDerivedFrom(FromPointee2, FromPointee1))
1706 return ImplicitConversionSequence::Better;
1707 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1708 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001709
1710 // Objective-C++: If one interface is more specific than the
1711 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001712 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1713 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001714 if (FromIface1 && FromIface1) {
1715 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1716 return ImplicitConversionSequence::Better;
1717 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1718 return ImplicitConversionSequence::Worse;
1719 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001720 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001721
1722 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1723 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001724 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001725 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001726 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001727
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001728 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001729 // C++0x [over.ics.rank]p3b4:
1730 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1731 // implicit object parameter of a non-static member function declared
1732 // without a ref-qualifier, and S1 binds an rvalue reference to an
1733 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001734 // FIXME: We don't know if we're dealing with the implicit object parameter,
1735 // or if the member function in this case has a ref qualifier.
1736 // (Of course, we don't have ref qualifiers yet.)
1737 if (SCS1.RRefBinding != SCS2.RRefBinding)
1738 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1739 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001740
1741 // C++ [over.ics.rank]p3b4:
1742 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1743 // which the references refer are the same type except for
1744 // top-level cv-qualifiers, and the type to which the reference
1745 // initialized by S2 refers is more cv-qualified than the type
1746 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001747 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1748 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001749 T1 = Context.getCanonicalType(T1);
1750 T2 = Context.getCanonicalType(T2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001751 if (Context.hasSameUnqualifiedType(T1, T2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001752 if (T2.isMoreQualifiedThan(T1))
1753 return ImplicitConversionSequence::Better;
1754 else if (T1.isMoreQualifiedThan(T2))
1755 return ImplicitConversionSequence::Worse;
1756 }
1757 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001758
1759 return ImplicitConversionSequence::Indistinguishable;
1760}
1761
1762/// CompareQualificationConversions - Compares two standard conversion
1763/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001764/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1765ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001766Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001767 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001768 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001769 // -- S1 and S2 differ only in their qualification conversion and
1770 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1771 // cv-qualification signature of type T1 is a proper subset of
1772 // the cv-qualification signature of type T2, and S1 is not the
1773 // deprecated string literal array-to-pointer conversion (4.2).
1774 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1775 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1776 return ImplicitConversionSequence::Indistinguishable;
1777
1778 // FIXME: the example in the standard doesn't use a qualification
1779 // conversion (!)
1780 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1781 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1782 T1 = Context.getCanonicalType(T1);
1783 T2 = Context.getCanonicalType(T2);
1784
1785 // If the types are the same, we won't learn anything by unwrapped
1786 // them.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001787 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001788 return ImplicitConversionSequence::Indistinguishable;
1789
Mike Stump11289f42009-09-09 15:08:12 +00001790 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001791 = ImplicitConversionSequence::Indistinguishable;
1792 while (UnwrapSimilarPointerTypes(T1, T2)) {
1793 // Within each iteration of the loop, we check the qualifiers to
1794 // determine if this still looks like a qualification
1795 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001796 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001797 // until there are no more pointers or pointers-to-members left
1798 // to unwrap. This essentially mimics what
1799 // IsQualificationConversion does, but here we're checking for a
1800 // strict subset of qualifiers.
1801 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1802 // The qualifiers are the same, so this doesn't tell us anything
1803 // about how the sequences rank.
1804 ;
1805 else if (T2.isMoreQualifiedThan(T1)) {
1806 // T1 has fewer qualifiers, so it could be the better sequence.
1807 if (Result == ImplicitConversionSequence::Worse)
1808 // Neither has qualifiers that are a subset of the other's
1809 // qualifiers.
1810 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001811
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001812 Result = ImplicitConversionSequence::Better;
1813 } else if (T1.isMoreQualifiedThan(T2)) {
1814 // T2 has fewer qualifiers, so it could be the better sequence.
1815 if (Result == ImplicitConversionSequence::Better)
1816 // Neither has qualifiers that are a subset of the other's
1817 // qualifiers.
1818 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001819
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001820 Result = ImplicitConversionSequence::Worse;
1821 } else {
1822 // Qualifiers are disjoint.
1823 return ImplicitConversionSequence::Indistinguishable;
1824 }
1825
1826 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001827 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001828 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001829 }
1830
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001831 // Check that the winning standard conversion sequence isn't using
1832 // the deprecated string literal array to pointer conversion.
1833 switch (Result) {
1834 case ImplicitConversionSequence::Better:
1835 if (SCS1.Deprecated)
1836 Result = ImplicitConversionSequence::Indistinguishable;
1837 break;
1838
1839 case ImplicitConversionSequence::Indistinguishable:
1840 break;
1841
1842 case ImplicitConversionSequence::Worse:
1843 if (SCS2.Deprecated)
1844 Result = ImplicitConversionSequence::Indistinguishable;
1845 break;
1846 }
1847
1848 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001849}
1850
Douglas Gregor5c407d92008-10-23 00:40:37 +00001851/// CompareDerivedToBaseConversions - Compares two standard conversion
1852/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001853/// various kinds of derived-to-base conversions (C++
1854/// [over.ics.rank]p4b3). As part of these checks, we also look at
1855/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001856ImplicitConversionSequence::CompareKind
1857Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1858 const StandardConversionSequence& SCS2) {
1859 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1860 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1861 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1862 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1863
1864 // Adjust the types we're converting from via the array-to-pointer
1865 // conversion, if we need to.
1866 if (SCS1.First == ICK_Array_To_Pointer)
1867 FromType1 = Context.getArrayDecayedType(FromType1);
1868 if (SCS2.First == ICK_Array_To_Pointer)
1869 FromType2 = Context.getArrayDecayedType(FromType2);
1870
1871 // Canonicalize all of the types.
1872 FromType1 = Context.getCanonicalType(FromType1);
1873 ToType1 = Context.getCanonicalType(ToType1);
1874 FromType2 = Context.getCanonicalType(FromType2);
1875 ToType2 = Context.getCanonicalType(ToType2);
1876
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001877 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001878 //
1879 // If class B is derived directly or indirectly from class A and
1880 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001881 //
1882 // For Objective-C, we let A, B, and C also be Objective-C
1883 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001884
1885 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001886 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001887 SCS2.Second == ICK_Pointer_Conversion &&
1888 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1889 FromType1->isPointerType() && FromType2->isPointerType() &&
1890 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001891 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001892 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001893 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001894 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001895 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001896 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001897 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001898 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001899
John McCall9dd450b2009-09-21 23:43:11 +00001900 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1901 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1902 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1903 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001904
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001905 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001906 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1907 if (IsDerivedFrom(ToPointee1, ToPointee2))
1908 return ImplicitConversionSequence::Better;
1909 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1910 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001911
1912 if (ToIface1 && ToIface2) {
1913 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1914 return ImplicitConversionSequence::Better;
1915 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1916 return ImplicitConversionSequence::Worse;
1917 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001918 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001919
1920 // -- conversion of B* to A* is better than conversion of C* to A*,
1921 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1922 if (IsDerivedFrom(FromPointee2, FromPointee1))
1923 return ImplicitConversionSequence::Better;
1924 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1925 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001926
Douglas Gregor237f96c2008-11-26 23:31:11 +00001927 if (FromIface1 && FromIface2) {
1928 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1929 return ImplicitConversionSequence::Better;
1930 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1931 return ImplicitConversionSequence::Worse;
1932 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001933 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001934 }
1935
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001936 // Compare based on reference bindings.
1937 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1938 SCS1.Second == ICK_Derived_To_Base) {
1939 // -- binding of an expression of type C to a reference of type
1940 // B& is better than binding an expression of type C to a
1941 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001942 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1943 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001944 if (IsDerivedFrom(ToType1, ToType2))
1945 return ImplicitConversionSequence::Better;
1946 else if (IsDerivedFrom(ToType2, ToType1))
1947 return ImplicitConversionSequence::Worse;
1948 }
1949
Douglas Gregor2fe98832008-11-03 19:09:14 +00001950 // -- binding of an expression of type B to a reference of type
1951 // A& is better than binding an expression of type C to a
1952 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001953 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1954 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001955 if (IsDerivedFrom(FromType2, FromType1))
1956 return ImplicitConversionSequence::Better;
1957 else if (IsDerivedFrom(FromType1, FromType2))
1958 return ImplicitConversionSequence::Worse;
1959 }
1960 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001961
1962 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001963 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1964 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1965 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1966 const MemberPointerType * FromMemPointer1 =
1967 FromType1->getAs<MemberPointerType>();
1968 const MemberPointerType * ToMemPointer1 =
1969 ToType1->getAs<MemberPointerType>();
1970 const MemberPointerType * FromMemPointer2 =
1971 FromType2->getAs<MemberPointerType>();
1972 const MemberPointerType * ToMemPointer2 =
1973 ToType2->getAs<MemberPointerType>();
1974 const Type *FromPointeeType1 = FromMemPointer1->getClass();
1975 const Type *ToPointeeType1 = ToMemPointer1->getClass();
1976 const Type *FromPointeeType2 = FromMemPointer2->getClass();
1977 const Type *ToPointeeType2 = ToMemPointer2->getClass();
1978 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1979 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
1980 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
1981 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001982 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001983 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1984 if (IsDerivedFrom(ToPointee1, ToPointee2))
1985 return ImplicitConversionSequence::Worse;
1986 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1987 return ImplicitConversionSequence::Better;
1988 }
1989 // conversion of B::* to C::* is better than conversion of A::* to C::*
1990 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
1991 if (IsDerivedFrom(FromPointee1, FromPointee2))
1992 return ImplicitConversionSequence::Better;
1993 else if (IsDerivedFrom(FromPointee2, FromPointee1))
1994 return ImplicitConversionSequence::Worse;
1995 }
1996 }
1997
Douglas Gregor2fe98832008-11-03 19:09:14 +00001998 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1999 SCS1.Second == ICK_Derived_To_Base) {
2000 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002001 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2002 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002003 if (IsDerivedFrom(ToType1, ToType2))
2004 return ImplicitConversionSequence::Better;
2005 else if (IsDerivedFrom(ToType2, ToType1))
2006 return ImplicitConversionSequence::Worse;
2007 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002008
Douglas Gregor2fe98832008-11-03 19:09:14 +00002009 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002010 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2011 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002012 if (IsDerivedFrom(FromType2, FromType1))
2013 return ImplicitConversionSequence::Better;
2014 else if (IsDerivedFrom(FromType1, FromType2))
2015 return ImplicitConversionSequence::Worse;
2016 }
2017 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002018
Douglas Gregor5c407d92008-10-23 00:40:37 +00002019 return ImplicitConversionSequence::Indistinguishable;
2020}
2021
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002022/// TryCopyInitialization - Try to copy-initialize a value of type
2023/// ToType from the expression From. Return the implicit conversion
2024/// sequence required to pass this argument, which may be a bad
2025/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002026/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002027/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2028/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002029ImplicitConversionSequence
2030Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002031 bool SuppressUserConversions, bool ForceRValue,
2032 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002033 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002034 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00002035 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002036 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002037 SuppressUserConversions,
2038 /*AllowExplicit=*/false,
2039 ForceRValue,
2040 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002041 return ICS;
2042 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002043 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002044 SuppressUserConversions,
2045 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002046 ForceRValue,
2047 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002048 }
2049}
2050
Sebastian Redl42e92c42009-04-12 17:16:29 +00002051/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2052/// the expression @p From. Returns true (and emits a diagnostic) if there was
2053/// an error, returns false if the initialization succeeded. Elidable should
2054/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2055/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002056bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002057 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002058 if (!getLangOptions().CPlusPlus) {
2059 // In C, argument passing is the same as performing an assignment.
2060 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002061
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002062 AssignConvertType ConvTy =
2063 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002064 if (ConvTy != Compatible &&
2065 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2066 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002067
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002068 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2069 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002070 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002071
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002072 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002073 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002074 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002075 /*SuppressUserConversions=*/false,
2076 /*AllowExplicit=*/false,
2077 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002078
Sebastian Redl42e92c42009-04-12 17:16:29 +00002079 if (!PerformImplicitConversion(From, ToType, Flavor,
2080 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002081 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002082 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002083 return Diag(From->getSourceRange().getBegin(),
2084 diag::err_typecheck_convert_incompatible)
2085 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002086 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002087}
2088
Douglas Gregor436424c2008-11-18 23:14:02 +00002089/// TryObjectArgumentInitialization - Try to initialize the object
2090/// parameter of the given member function (@c Method) from the
2091/// expression @p From.
2092ImplicitConversionSequence
2093Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2094 QualType ClassType = Context.getTypeDeclType(Method->getParent());
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002095 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2096 // const volatile object.
2097 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2098 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2099 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002100
2101 // Set up the conversion sequence as a "bad" conversion, to allow us
2102 // to exit early.
2103 ImplicitConversionSequence ICS;
2104 ICS.Standard.setAsIdentityConversion();
2105 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2106
2107 // We need to have an object of class type.
2108 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002109 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002110 FromType = PT->getPointeeType();
2111
2112 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002113
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002114 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002115 // where X is the class of which the function is a member
2116 // (C++ [over.match.funcs]p4). However, when finding an implicit
2117 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002118 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002119 // (C++ [over.match.funcs]p5). We perform a simplified version of
2120 // reference binding here, that allows class rvalues to bind to
2121 // non-constant references.
2122
2123 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2124 // with the implicit object parameter (C++ [over.match.funcs]p5).
2125 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002126 if (ImplicitParamType.getCVRQualifiers()
2127 != FromTypeCanon.getLocalCVRQualifiers() &&
Douglas Gregor01df9462009-11-05 00:07:36 +00002128 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor436424c2008-11-18 23:14:02 +00002129 return ICS;
2130
2131 // Check that we have either the same type or a derived type. It
2132 // affects the conversion rank.
2133 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002134 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002135 ICS.Standard.Second = ICK_Identity;
2136 else if (IsDerivedFrom(FromType, ClassType))
2137 ICS.Standard.Second = ICK_Derived_To_Base;
2138 else
2139 return ICS;
2140
2141 // Success. Mark this as a reference binding.
2142 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2143 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2144 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2145 ICS.Standard.ReferenceBinding = true;
2146 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002147 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002148 return ICS;
2149}
2150
2151/// PerformObjectArgumentInitialization - Perform initialization of
2152/// the implicit object parameter for the given Method with the given
2153/// expression.
2154bool
2155Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002156 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002157 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002158 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002159
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002160 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002161 FromRecordType = PT->getPointeeType();
2162 DestType = Method->getThisType(Context);
2163 } else {
2164 FromRecordType = From->getType();
2165 DestType = ImplicitParamRecordType;
2166 }
2167
Mike Stump11289f42009-09-09 15:08:12 +00002168 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002169 = TryObjectArgumentInitialization(From, Method);
2170 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2171 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002172 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002173 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002174
Douglas Gregor436424c2008-11-18 23:14:02 +00002175 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002176 CheckDerivedToBaseConversion(FromRecordType,
2177 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002178 From->getSourceRange().getBegin(),
2179 From->getSourceRange()))
2180 return true;
2181
Mike Stump11289f42009-09-09 15:08:12 +00002182 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002183 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002184 return false;
2185}
2186
Douglas Gregor5fb53972009-01-14 15:45:31 +00002187/// TryContextuallyConvertToBool - Attempt to contextually convert the
2188/// expression From to bool (C++0x [conv]p3).
2189ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002190 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002191 // FIXME: Are these flags correct?
2192 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002193 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002194 /*ForceRValue=*/false,
2195 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002196}
2197
2198/// PerformContextuallyConvertToBool - Perform a contextual conversion
2199/// of the expression From to bool (C++0x [conv]p3).
2200bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2201 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2202 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2203 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002204
Fariborz Jahanian76197412009-11-18 18:26:29 +00002205 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002206 return Diag(From->getSourceRange().getBegin(),
2207 diag::err_typecheck_bool_condition)
2208 << From->getType() << From->getSourceRange();
2209 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002210}
2211
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002212/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002213/// candidate functions, using the given function call arguments. If
2214/// @p SuppressUserConversions, then don't allow user-defined
2215/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002216/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2217/// hacky way to implement the overloading rules for elidable copy
2218/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002219///
2220/// \para PartialOverloading true if we are performing "partial" overloading
2221/// based on an incomplete set of function arguments. This feature is used by
2222/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002223void
2224Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002225 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002226 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002227 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002228 bool ForceRValue,
2229 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002230 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002231 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002232 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002233 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002234 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002235 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002236 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002237
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002238 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002239 if (!isa<CXXConstructorDecl>(Method)) {
2240 // If we get here, it's because we're calling a member function
2241 // that is named without a member access expression (e.g.,
2242 // "this->f") that was either written explicitly or created
2243 // implicitly. This can happen with a qualified call to a member
2244 // function, e.g., X::f(). We use a NULL object as the implied
2245 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002246 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002247 SuppressUserConversions, ForceRValue);
2248 return;
2249 }
2250 // We treat a constructor like a non-member function, since its object
2251 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002252 }
2253
Douglas Gregorff7028a2009-11-13 23:59:09 +00002254 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002255 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002256
2257 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2258 // C++ [class.copy]p3:
2259 // A member function template is never instantiated to perform the copy
2260 // of a class object to an object of its class type.
2261 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2262 if (NumArgs == 1 &&
2263 Constructor->isCopyConstructorLikeSpecialization() &&
2264 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2265 return;
2266 }
2267
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002268 // Add this candidate
2269 CandidateSet.push_back(OverloadCandidate());
2270 OverloadCandidate& Candidate = CandidateSet.back();
2271 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002272 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002273 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002274 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002275
2276 unsigned NumArgsInProto = Proto->getNumArgs();
2277
2278 // (C++ 13.3.2p2): A candidate function having fewer than m
2279 // parameters is viable only if it has an ellipsis in its parameter
2280 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002281 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2282 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002283 Candidate.Viable = false;
2284 return;
2285 }
2286
2287 // (C++ 13.3.2p2): A candidate function having more than m parameters
2288 // is viable only if the (m+1)st parameter has a default argument
2289 // (8.3.6). For the purposes of overload resolution, the
2290 // parameter list is truncated on the right, so that there are
2291 // exactly m parameters.
2292 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002293 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002294 // Not enough arguments.
2295 Candidate.Viable = false;
2296 return;
2297 }
2298
2299 // Determine the implicit conversion sequences for each of the
2300 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002301 Candidate.Conversions.resize(NumArgs);
2302 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2303 if (ArgIdx < NumArgsInProto) {
2304 // (C++ 13.3.2p3): for F to be a viable function, there shall
2305 // exist for each argument an implicit conversion sequence
2306 // (13.3.3.1) that converts that argument to the corresponding
2307 // parameter of F.
2308 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002309 Candidate.Conversions[ArgIdx]
2310 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002311 SuppressUserConversions, ForceRValue,
2312 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002313 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002314 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002315 // 13.3.3.1-p10 If several different sequences of conversions exist that
2316 // each convert the argument to the parameter type, the implicit conversion
2317 // sequence associated with the parameter is defined to be the unique conversion
2318 // sequence designated the ambiguous conversion sequence. For the purpose of
2319 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2320 // conversion sequence is treated as a user-defined sequence that is
2321 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002322 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002323 Candidate.Conversions[ArgIdx].ConversionKind =
2324 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002325 // Set the conversion function to one of them. As due to ambiguity,
2326 // they carry the same weight and is needed for overload resolution
2327 // later.
2328 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2329 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2330 }
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002331 else {
2332 Candidate.Viable = false;
2333 break;
2334 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002335 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002336 } else {
2337 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2338 // argument for which there is no corresponding parameter is
2339 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002340 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002341 = ImplicitConversionSequence::EllipsisConversion;
2342 }
2343 }
2344}
2345
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002346/// \brief Add all of the function declarations in the given function set to
2347/// the overload canddiate set.
2348void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2349 Expr **Args, unsigned NumArgs,
2350 OverloadCandidateSet& CandidateSet,
2351 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002352 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002353 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002354 F != FEnd; ++F) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002355 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2356 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2357 AddMethodCandidate(cast<CXXMethodDecl>(FD),
2358 Args[0], Args + 1, NumArgs - 1,
2359 CandidateSet, SuppressUserConversions);
2360 else
2361 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2362 SuppressUserConversions);
2363 } else {
2364 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2365 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2366 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2367 AddMethodTemplateCandidate(FunTmpl,
Douglas Gregor89026b52009-06-30 23:57:56 +00002368 /*FIXME: explicit args */false, 0, 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002369 Args[0], Args + 1, NumArgs - 1,
2370 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002371 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002372 else
2373 AddTemplateOverloadCandidate(FunTmpl,
2374 /*FIXME: explicit args */false, 0, 0,
2375 Args, NumArgs, CandidateSet,
2376 SuppressUserConversions);
2377 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002378 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002379}
2380
John McCallf0f1cf02009-11-17 07:50:12 +00002381/// AddMethodCandidate - Adds a named decl (which is some kind of
2382/// method) as a method candidate to the given overload set.
2383void Sema::AddMethodCandidate(NamedDecl *Decl, Expr *Object,
2384 Expr **Args, unsigned NumArgs,
2385 OverloadCandidateSet& CandidateSet,
2386 bool SuppressUserConversions, bool ForceRValue) {
2387
2388 // FIXME: use this
2389 //DeclContext *ActingContext = Decl->getDeclContext();
2390
2391 if (isa<UsingShadowDecl>(Decl))
2392 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2393
2394 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2395 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2396 "Expected a member function template");
2397 AddMethodTemplateCandidate(TD, false, 0, 0,
2398 Object, Args, NumArgs,
2399 CandidateSet,
2400 SuppressUserConversions,
2401 ForceRValue);
2402 } else {
2403 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Object, Args, NumArgs,
2404 CandidateSet, SuppressUserConversions, ForceRValue);
2405 }
2406}
2407
Douglas Gregor436424c2008-11-18 23:14:02 +00002408/// AddMethodCandidate - Adds the given C++ member function to the set
2409/// of candidate functions, using the given function call arguments
2410/// and the object argument (@c Object). For example, in a call
2411/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2412/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2413/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002414/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2415/// a slightly hacky way to implement the overloading rules for elidable copy
2416/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002417void
Douglas Gregor436424c2008-11-18 23:14:02 +00002418Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2419 Expr **Args, unsigned NumArgs,
2420 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002421 bool SuppressUserConversions, bool ForceRValue) {
2422 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002423 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002424 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002425 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002426 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002427 assert(!isa<CXXConstructorDecl>(Method) &&
2428 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002429
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002430 if (!CandidateSet.isNewCandidate(Method))
2431 return;
2432
Douglas Gregor436424c2008-11-18 23:14:02 +00002433 // Add this candidate
2434 CandidateSet.push_back(OverloadCandidate());
2435 OverloadCandidate& Candidate = CandidateSet.back();
2436 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002437 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002438 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002439
2440 unsigned NumArgsInProto = Proto->getNumArgs();
2441
2442 // (C++ 13.3.2p2): A candidate function having fewer than m
2443 // parameters is viable only if it has an ellipsis in its parameter
2444 // list (8.3.5).
2445 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2446 Candidate.Viable = false;
2447 return;
2448 }
2449
2450 // (C++ 13.3.2p2): A candidate function having more than m parameters
2451 // is viable only if the (m+1)st parameter has a default argument
2452 // (8.3.6). For the purposes of overload resolution, the
2453 // parameter list is truncated on the right, so that there are
2454 // exactly m parameters.
2455 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2456 if (NumArgs < MinRequiredArgs) {
2457 // Not enough arguments.
2458 Candidate.Viable = false;
2459 return;
2460 }
2461
2462 Candidate.Viable = true;
2463 Candidate.Conversions.resize(NumArgs + 1);
2464
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002465 if (Method->isStatic() || !Object)
2466 // The implicit object argument is ignored.
2467 Candidate.IgnoreObjectArgument = true;
2468 else {
2469 // Determine the implicit conversion sequence for the object
2470 // parameter.
2471 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002472 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002473 == ImplicitConversionSequence::BadConversion) {
2474 Candidate.Viable = false;
2475 return;
2476 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002477 }
2478
2479 // Determine the implicit conversion sequences for each of the
2480 // arguments.
2481 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2482 if (ArgIdx < NumArgsInProto) {
2483 // (C++ 13.3.2p3): for F to be a viable function, there shall
2484 // exist for each argument an implicit conversion sequence
2485 // (13.3.3.1) that converts that argument to the corresponding
2486 // parameter of F.
2487 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002488 Candidate.Conversions[ArgIdx + 1]
2489 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002490 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002491 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002492 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002493 == ImplicitConversionSequence::BadConversion) {
2494 Candidate.Viable = false;
2495 break;
2496 }
2497 } else {
2498 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2499 // argument for which there is no corresponding parameter is
2500 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002501 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002502 = ImplicitConversionSequence::EllipsisConversion;
2503 }
2504 }
2505}
2506
Douglas Gregor97628d62009-08-21 00:16:32 +00002507/// \brief Add a C++ member function template as a candidate to the candidate
2508/// set, using template argument deduction to produce an appropriate member
2509/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002510void
Douglas Gregor97628d62009-08-21 00:16:32 +00002511Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2512 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00002513 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002514 unsigned NumExplicitTemplateArgs,
2515 Expr *Object, Expr **Args, unsigned NumArgs,
2516 OverloadCandidateSet& CandidateSet,
2517 bool SuppressUserConversions,
2518 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002519 if (!CandidateSet.isNewCandidate(MethodTmpl))
2520 return;
2521
Douglas Gregor97628d62009-08-21 00:16:32 +00002522 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002523 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002524 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002525 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002526 // candidate functions in the usual way.113) A given name can refer to one
2527 // or more function templates and also to a set of overloaded non-template
2528 // functions. In such a case, the candidate functions generated from each
2529 // function template are combined with the set of non-template candidate
2530 // functions.
2531 TemplateDeductionInfo Info(Context);
2532 FunctionDecl *Specialization = 0;
2533 if (TemplateDeductionResult Result
2534 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2535 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2536 Args, NumArgs, Specialization, Info)) {
2537 // FIXME: Record what happened with template argument deduction, so
2538 // that we can give the user a beautiful diagnostic.
2539 (void)Result;
2540 return;
2541 }
Mike Stump11289f42009-09-09 15:08:12 +00002542
Douglas Gregor97628d62009-08-21 00:16:32 +00002543 // Add the function template specialization produced by template argument
2544 // deduction as a candidate.
2545 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002546 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002547 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002548 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002549 CandidateSet, SuppressUserConversions, ForceRValue);
2550}
2551
Douglas Gregor05155d82009-08-21 23:19:43 +00002552/// \brief Add a C++ function template specialization as a candidate
2553/// in the candidate set, using template argument deduction to produce
2554/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002555void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002556Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor89026b52009-06-30 23:57:56 +00002557 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00002558 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002559 unsigned NumExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002560 Expr **Args, unsigned NumArgs,
2561 OverloadCandidateSet& CandidateSet,
2562 bool SuppressUserConversions,
2563 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002564 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2565 return;
2566
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002567 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002568 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002569 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002570 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002571 // candidate functions in the usual way.113) A given name can refer to one
2572 // or more function templates and also to a set of overloaded non-template
2573 // functions. In such a case, the candidate functions generated from each
2574 // function template are combined with the set of non-template candidate
2575 // functions.
2576 TemplateDeductionInfo Info(Context);
2577 FunctionDecl *Specialization = 0;
2578 if (TemplateDeductionResult Result
Douglas Gregor89026b52009-06-30 23:57:56 +00002579 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2580 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2581 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002582 // FIXME: Record what happened with template argument deduction, so
2583 // that we can give the user a beautiful diagnostic.
2584 (void)Result;
2585 return;
2586 }
Mike Stump11289f42009-09-09 15:08:12 +00002587
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002588 // Add the function template specialization produced by template argument
2589 // deduction as a candidate.
2590 assert(Specialization && "Missing function template specialization?");
2591 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2592 SuppressUserConversions, ForceRValue);
2593}
Mike Stump11289f42009-09-09 15:08:12 +00002594
Douglas Gregora1f013e2008-11-07 22:36:19 +00002595/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002596/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002597/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002598/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002599/// (which may or may not be the same type as the type that the
2600/// conversion function produces).
2601void
2602Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2603 Expr *From, QualType ToType,
2604 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002605 assert(!Conversion->getDescribedFunctionTemplate() &&
2606 "Conversion function templates use AddTemplateConversionCandidate");
2607
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002608 if (!CandidateSet.isNewCandidate(Conversion))
2609 return;
2610
Douglas Gregora1f013e2008-11-07 22:36:19 +00002611 // Add this candidate
2612 CandidateSet.push_back(OverloadCandidate());
2613 OverloadCandidate& Candidate = CandidateSet.back();
2614 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002615 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002616 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002617 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002618 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002619 = Conversion->getConversionType().getAsOpaquePtr();
2620 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2621
Douglas Gregor436424c2008-11-18 23:14:02 +00002622 // Determine the implicit conversion sequence for the implicit
2623 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002624 Candidate.Viable = true;
2625 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002626 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002627 // Conversion functions to a different type in the base class is visible in
2628 // the derived class. So, a derived to base conversion should not participate
2629 // in overload resolution.
2630 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2631 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002632 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002633 == ImplicitConversionSequence::BadConversion) {
2634 Candidate.Viable = false;
2635 return;
2636 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002637
2638 // We won't go through a user-define type conversion function to convert a
2639 // derived to base as such conversions are given Conversion Rank. They only
2640 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2641 QualType FromCanon
2642 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2643 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2644 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2645 Candidate.Viable = false;
2646 return;
2647 }
2648
Douglas Gregora1f013e2008-11-07 22:36:19 +00002649
2650 // To determine what the conversion from the result of calling the
2651 // conversion function to the type we're eventually trying to
2652 // convert to (ToType), we need to synthesize a call to the
2653 // conversion function and attempt copy initialization from it. This
2654 // makes sure that we get the right semantics with respect to
2655 // lvalues/rvalues and the type. Fortunately, we can allocate this
2656 // call on the stack and we don't need its arguments to be
2657 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002658 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002659 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002660 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002661 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002662 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002663
2664 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002665 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2666 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002667 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002668 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002669 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002670 ImplicitConversionSequence ICS =
2671 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002672 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002673 /*ForceRValue=*/false,
2674 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002675
Douglas Gregora1f013e2008-11-07 22:36:19 +00002676 switch (ICS.ConversionKind) {
2677 case ImplicitConversionSequence::StandardConversion:
2678 Candidate.FinalConversion = ICS.Standard;
2679 break;
2680
2681 case ImplicitConversionSequence::BadConversion:
2682 Candidate.Viable = false;
2683 break;
2684
2685 default:
Mike Stump11289f42009-09-09 15:08:12 +00002686 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002687 "Can only end up with a standard conversion sequence or failure");
2688 }
2689}
2690
Douglas Gregor05155d82009-08-21 23:19:43 +00002691/// \brief Adds a conversion function template specialization
2692/// candidate to the overload set, using template argument deduction
2693/// to deduce the template arguments of the conversion function
2694/// template from the type that we are converting to (C++
2695/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002696void
Douglas Gregor05155d82009-08-21 23:19:43 +00002697Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2698 Expr *From, QualType ToType,
2699 OverloadCandidateSet &CandidateSet) {
2700 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2701 "Only conversion function templates permitted here");
2702
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002703 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2704 return;
2705
Douglas Gregor05155d82009-08-21 23:19:43 +00002706 TemplateDeductionInfo Info(Context);
2707 CXXConversionDecl *Specialization = 0;
2708 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002709 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002710 Specialization, Info)) {
2711 // FIXME: Record what happened with template argument deduction, so
2712 // that we can give the user a beautiful diagnostic.
2713 (void)Result;
2714 return;
2715 }
Mike Stump11289f42009-09-09 15:08:12 +00002716
Douglas Gregor05155d82009-08-21 23:19:43 +00002717 // Add the conversion function template specialization produced by
2718 // template argument deduction as a candidate.
2719 assert(Specialization && "Missing function template specialization?");
2720 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2721}
2722
Douglas Gregorab7897a2008-11-19 22:57:39 +00002723/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2724/// converts the given @c Object to a function pointer via the
2725/// conversion function @c Conversion, and then attempts to call it
2726/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2727/// the type of function that we'll eventually be calling.
2728void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002729 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002730 Expr *Object, Expr **Args, unsigned NumArgs,
2731 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002732 if (!CandidateSet.isNewCandidate(Conversion))
2733 return;
2734
Douglas Gregorab7897a2008-11-19 22:57:39 +00002735 CandidateSet.push_back(OverloadCandidate());
2736 OverloadCandidate& Candidate = CandidateSet.back();
2737 Candidate.Function = 0;
2738 Candidate.Surrogate = Conversion;
2739 Candidate.Viable = true;
2740 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002741 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002742 Candidate.Conversions.resize(NumArgs + 1);
2743
2744 // Determine the implicit conversion sequence for the implicit
2745 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002746 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002747 = TryObjectArgumentInitialization(Object, Conversion);
2748 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2749 Candidate.Viable = false;
2750 return;
2751 }
2752
2753 // The first conversion is actually a user-defined conversion whose
2754 // first conversion is ObjectInit's standard conversion (which is
2755 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002756 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002757 = ImplicitConversionSequence::UserDefinedConversion;
2758 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002759 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002760 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002761 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002762 = Candidate.Conversions[0].UserDefined.Before;
2763 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2764
Mike Stump11289f42009-09-09 15:08:12 +00002765 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002766 unsigned NumArgsInProto = Proto->getNumArgs();
2767
2768 // (C++ 13.3.2p2): A candidate function having fewer than m
2769 // parameters is viable only if it has an ellipsis in its parameter
2770 // list (8.3.5).
2771 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2772 Candidate.Viable = false;
2773 return;
2774 }
2775
2776 // Function types don't have any default arguments, so just check if
2777 // we have enough arguments.
2778 if (NumArgs < NumArgsInProto) {
2779 // Not enough arguments.
2780 Candidate.Viable = false;
2781 return;
2782 }
2783
2784 // Determine the implicit conversion sequences for each of the
2785 // arguments.
2786 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2787 if (ArgIdx < NumArgsInProto) {
2788 // (C++ 13.3.2p3): for F to be a viable function, there shall
2789 // exist for each argument an implicit conversion sequence
2790 // (13.3.3.1) that converts that argument to the corresponding
2791 // parameter of F.
2792 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002793 Candidate.Conversions[ArgIdx + 1]
2794 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002795 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002796 /*ForceRValue=*/false,
2797 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002798 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002799 == ImplicitConversionSequence::BadConversion) {
2800 Candidate.Viable = false;
2801 break;
2802 }
2803 } else {
2804 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2805 // argument for which there is no corresponding parameter is
2806 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002807 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002808 = ImplicitConversionSequence::EllipsisConversion;
2809 }
2810 }
2811}
2812
Mike Stump87c57ac2009-05-16 07:39:55 +00002813// FIXME: This will eventually be removed, once we've migrated all of the
2814// operator overloading logic over to the scheme used by binary operators, which
2815// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002816void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002817 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002818 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002819 OverloadCandidateSet& CandidateSet,
2820 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002821 FunctionSet Functions;
2822
2823 QualType T1 = Args[0]->getType();
2824 QualType T2;
2825 if (NumArgs > 1)
2826 T2 = Args[1]->getType();
2827
2828 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002829 if (S)
2830 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002831 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002832 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2833 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002834 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002835}
2836
2837/// \brief Add overload candidates for overloaded operators that are
2838/// member functions.
2839///
2840/// Add the overloaded operator candidates that are member functions
2841/// for the operator Op that was used in an operator expression such
2842/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2843/// CandidateSet will store the added overload candidates. (C++
2844/// [over.match.oper]).
2845void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2846 SourceLocation OpLoc,
2847 Expr **Args, unsigned NumArgs,
2848 OverloadCandidateSet& CandidateSet,
2849 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002850 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2851
2852 // C++ [over.match.oper]p3:
2853 // For a unary operator @ with an operand of a type whose
2854 // cv-unqualified version is T1, and for a binary operator @ with
2855 // a left operand of a type whose cv-unqualified version is T1 and
2856 // a right operand of a type whose cv-unqualified version is T2,
2857 // three sets of candidate functions, designated member
2858 // candidates, non-member candidates and built-in candidates, are
2859 // constructed as follows:
2860 QualType T1 = Args[0]->getType();
2861 QualType T2;
2862 if (NumArgs > 1)
2863 T2 = Args[1]->getType();
2864
2865 // -- If T1 is a class type, the set of member candidates is the
2866 // result of the qualified lookup of T1::operator@
2867 // (13.3.1.1.1); otherwise, the set of member candidates is
2868 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002869 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002870 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002871 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002872 return;
Mike Stump11289f42009-09-09 15:08:12 +00002873
John McCall27b18f82009-11-17 02:14:36 +00002874 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2875 LookupQualifiedName(Operators, T1Rec->getDecl());
2876 Operators.suppressDiagnostics();
2877
Mike Stump11289f42009-09-09 15:08:12 +00002878 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002879 OperEnd = Operators.end();
2880 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00002881 ++Oper)
2882 AddMethodCandidate(*Oper, Args[0], Args + 1, NumArgs - 1, CandidateSet,
2883 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002884 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002885}
2886
Douglas Gregora11693b2008-11-12 17:17:38 +00002887/// AddBuiltinCandidate - Add a candidate for a built-in
2888/// operator. ResultTy and ParamTys are the result and parameter types
2889/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002890/// arguments being passed to the candidate. IsAssignmentOperator
2891/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002892/// operator. NumContextualBoolArguments is the number of arguments
2893/// (at the beginning of the argument list) that will be contextually
2894/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002895void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002896 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002897 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002898 bool IsAssignmentOperator,
2899 unsigned NumContextualBoolArguments) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002900 // Add this candidate
2901 CandidateSet.push_back(OverloadCandidate());
2902 OverloadCandidate& Candidate = CandidateSet.back();
2903 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002904 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002905 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002906 Candidate.BuiltinTypes.ResultTy = ResultTy;
2907 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2908 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2909
2910 // Determine the implicit conversion sequences for each of the
2911 // arguments.
2912 Candidate.Viable = true;
2913 Candidate.Conversions.resize(NumArgs);
2914 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002915 // C++ [over.match.oper]p4:
2916 // For the built-in assignment operators, conversions of the
2917 // left operand are restricted as follows:
2918 // -- no temporaries are introduced to hold the left operand, and
2919 // -- no user-defined conversions are applied to the left
2920 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002921 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002922 //
2923 // We block these conversions by turning off user-defined
2924 // conversions, since that is the only way that initialization of
2925 // a reference to a non-class type can occur from something that
2926 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002927 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002928 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002929 "Contextual conversion to bool requires bool type");
2930 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2931 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002932 Candidate.Conversions[ArgIdx]
2933 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002934 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002935 /*ForceRValue=*/false,
2936 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002937 }
Mike Stump11289f42009-09-09 15:08:12 +00002938 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002939 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002940 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002941 break;
2942 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002943 }
2944}
2945
2946/// BuiltinCandidateTypeSet - A set of types that will be used for the
2947/// candidate operator functions for built-in operators (C++
2948/// [over.built]). The types are separated into pointer types and
2949/// enumeration types.
2950class BuiltinCandidateTypeSet {
2951 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002952 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002953
2954 /// PointerTypes - The set of pointer types that will be used in the
2955 /// built-in candidates.
2956 TypeSet PointerTypes;
2957
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002958 /// MemberPointerTypes - The set of member pointer types that will be
2959 /// used in the built-in candidates.
2960 TypeSet MemberPointerTypes;
2961
Douglas Gregora11693b2008-11-12 17:17:38 +00002962 /// EnumerationTypes - The set of enumeration types that will be
2963 /// used in the built-in candidates.
2964 TypeSet EnumerationTypes;
2965
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002966 /// Sema - The semantic analysis instance where we are building the
2967 /// candidate type set.
2968 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002969
Douglas Gregora11693b2008-11-12 17:17:38 +00002970 /// Context - The AST context in which we will build the type sets.
2971 ASTContext &Context;
2972
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00002973 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2974 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002975 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002976
2977public:
2978 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002979 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002980
Mike Stump11289f42009-09-09 15:08:12 +00002981 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002982 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002983
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002984 void AddTypesConvertedFrom(QualType Ty,
2985 SourceLocation Loc,
2986 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00002987 bool AllowExplicitConversions,
2988 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00002989
2990 /// pointer_begin - First pointer type found;
2991 iterator pointer_begin() { return PointerTypes.begin(); }
2992
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002993 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002994 iterator pointer_end() { return PointerTypes.end(); }
2995
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002996 /// member_pointer_begin - First member pointer type found;
2997 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2998
2999 /// member_pointer_end - Past the last member pointer type found;
3000 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3001
Douglas Gregora11693b2008-11-12 17:17:38 +00003002 /// enumeration_begin - First enumeration type found;
3003 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3004
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003005 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003006 iterator enumeration_end() { return EnumerationTypes.end(); }
3007};
3008
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003009/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003010/// the set of pointer types along with any more-qualified variants of
3011/// that type. For example, if @p Ty is "int const *", this routine
3012/// will add "int const *", "int const volatile *", "int const
3013/// restrict *", and "int const volatile restrict *" to the set of
3014/// pointer types. Returns true if the add of @p Ty itself succeeded,
3015/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003016///
3017/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003018bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003019BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3020 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003021
Douglas Gregora11693b2008-11-12 17:17:38 +00003022 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003023 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003024 return false;
3025
John McCall8ccfcb52009-09-24 19:53:00 +00003026 const PointerType *PointerTy = Ty->getAs<PointerType>();
3027 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003028
John McCall8ccfcb52009-09-24 19:53:00 +00003029 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003030 // Don't add qualified variants of arrays. For one, they're not allowed
3031 // (the qualifier would sink to the element type), and for another, the
3032 // only overload situation where it matters is subscript or pointer +- int,
3033 // and those shouldn't have qualifier variants anyway.
3034 if (PointeeTy->isArrayType())
3035 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003036 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003037 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003038 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003039 bool hasVolatile = VisibleQuals.hasVolatile();
3040 bool hasRestrict = VisibleQuals.hasRestrict();
3041
John McCall8ccfcb52009-09-24 19:53:00 +00003042 // Iterate through all strict supersets of BaseCVR.
3043 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3044 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003045 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3046 // in the types.
3047 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3048 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003049 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3050 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003051 }
3052
3053 return true;
3054}
3055
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003056/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3057/// to the set of pointer types along with any more-qualified variants of
3058/// that type. For example, if @p Ty is "int const *", this routine
3059/// will add "int const *", "int const volatile *", "int const
3060/// restrict *", and "int const volatile restrict *" to the set of
3061/// pointer types. Returns true if the add of @p Ty itself succeeded,
3062/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003063///
3064/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003065bool
3066BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3067 QualType Ty) {
3068 // Insert this type.
3069 if (!MemberPointerTypes.insert(Ty))
3070 return false;
3071
John McCall8ccfcb52009-09-24 19:53:00 +00003072 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3073 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003074
John McCall8ccfcb52009-09-24 19:53:00 +00003075 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003076 // Don't add qualified variants of arrays. For one, they're not allowed
3077 // (the qualifier would sink to the element type), and for another, the
3078 // only overload situation where it matters is subscript or pointer +- int,
3079 // and those shouldn't have qualifier variants anyway.
3080 if (PointeeTy->isArrayType())
3081 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003082 const Type *ClassTy = PointerTy->getClass();
3083
3084 // Iterate through all strict supersets of the pointee type's CVR
3085 // qualifiers.
3086 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3087 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3088 if ((CVR | BaseCVR) != CVR) continue;
3089
3090 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3091 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003092 }
3093
3094 return true;
3095}
3096
Douglas Gregora11693b2008-11-12 17:17:38 +00003097/// AddTypesConvertedFrom - Add each of the types to which the type @p
3098/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003099/// primarily interested in pointer types and enumeration types. We also
3100/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003101/// AllowUserConversions is true if we should look at the conversion
3102/// functions of a class type, and AllowExplicitConversions if we
3103/// should also include the explicit conversion functions of a class
3104/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003105void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003106BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003107 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003108 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003109 bool AllowExplicitConversions,
3110 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003111 // Only deal with canonical types.
3112 Ty = Context.getCanonicalType(Ty);
3113
3114 // Look through reference types; they aren't part of the type of an
3115 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003116 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003117 Ty = RefTy->getPointeeType();
3118
3119 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003120 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003121
Sebastian Redl65ae2002009-11-05 16:36:20 +00003122 // If we're dealing with an array type, decay to the pointer.
3123 if (Ty->isArrayType())
3124 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3125
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003126 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003127 QualType PointeeTy = PointerTy->getPointeeType();
3128
3129 // Insert our type, and its more-qualified variants, into the set
3130 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003131 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003132 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003133 } else if (Ty->isMemberPointerType()) {
3134 // Member pointers are far easier, since the pointee can't be converted.
3135 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3136 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003137 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003138 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003139 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003140 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003141 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003142 // No conversion functions in incomplete types.
3143 return;
3144 }
Mike Stump11289f42009-09-09 15:08:12 +00003145
Douglas Gregora11693b2008-11-12 17:17:38 +00003146 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003147 OverloadedFunctionDecl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003148 = ClassDecl->getVisibleConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00003149 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregora11693b2008-11-12 17:17:38 +00003150 = Conversions->function_begin();
3151 Func != Conversions->function_end(); ++Func) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003152 CXXConversionDecl *Conv;
3153 FunctionTemplateDecl *ConvTemplate;
3154 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
3155
Mike Stump11289f42009-09-09 15:08:12 +00003156 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003157 // about which builtin types we can convert to.
3158 if (ConvTemplate)
3159 continue;
3160
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003161 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003162 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003163 VisibleQuals);
3164 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003165 }
3166 }
3167 }
3168}
3169
Douglas Gregor84605ae2009-08-24 13:43:27 +00003170/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3171/// the volatile- and non-volatile-qualified assignment operators for the
3172/// given type to the candidate set.
3173static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3174 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003175 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003176 unsigned NumArgs,
3177 OverloadCandidateSet &CandidateSet) {
3178 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003179
Douglas Gregor84605ae2009-08-24 13:43:27 +00003180 // T& operator=(T&, T)
3181 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3182 ParamTypes[1] = T;
3183 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3184 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003185
Douglas Gregor84605ae2009-08-24 13:43:27 +00003186 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3187 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003188 ParamTypes[0]
3189 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003190 ParamTypes[1] = T;
3191 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003192 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003193 }
3194}
Mike Stump11289f42009-09-09 15:08:12 +00003195
Sebastian Redl1054fae2009-10-25 17:03:50 +00003196/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3197/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003198static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3199 Qualifiers VRQuals;
3200 const RecordType *TyRec;
3201 if (const MemberPointerType *RHSMPType =
3202 ArgExpr->getType()->getAs<MemberPointerType>())
3203 TyRec = cast<RecordType>(RHSMPType->getClass());
3204 else
3205 TyRec = ArgExpr->getType()->getAs<RecordType>();
3206 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003207 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003208 VRQuals.addVolatile();
3209 VRQuals.addRestrict();
3210 return VRQuals;
3211 }
3212
3213 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3214 OverloadedFunctionDecl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003215 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003216
3217 for (OverloadedFunctionDecl::function_iterator Func
3218 = Conversions->function_begin();
3219 Func != Conversions->function_end(); ++Func) {
3220 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*Func)) {
3221 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3222 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3223 CanTy = ResTypeRef->getPointeeType();
3224 // Need to go down the pointer/mempointer chain and add qualifiers
3225 // as see them.
3226 bool done = false;
3227 while (!done) {
3228 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3229 CanTy = ResTypePtr->getPointeeType();
3230 else if (const MemberPointerType *ResTypeMPtr =
3231 CanTy->getAs<MemberPointerType>())
3232 CanTy = ResTypeMPtr->getPointeeType();
3233 else
3234 done = true;
3235 if (CanTy.isVolatileQualified())
3236 VRQuals.addVolatile();
3237 if (CanTy.isRestrictQualified())
3238 VRQuals.addRestrict();
3239 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3240 return VRQuals;
3241 }
3242 }
3243 }
3244 return VRQuals;
3245}
3246
Douglas Gregord08452f2008-11-19 15:42:04 +00003247/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3248/// operator overloads to the candidate set (C++ [over.built]), based
3249/// on the operator @p Op and the arguments given. For example, if the
3250/// operator is a binary '+', this routine might add "int
3251/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003252void
Mike Stump11289f42009-09-09 15:08:12 +00003253Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003254 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003255 Expr **Args, unsigned NumArgs,
3256 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003257 // The set of "promoted arithmetic types", which are the arithmetic
3258 // types are that preserved by promotion (C++ [over.built]p2). Note
3259 // that the first few of these types are the promoted integral
3260 // types; these types need to be first.
3261 // FIXME: What about complex?
3262 const unsigned FirstIntegralType = 0;
3263 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003264 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003265 LastPromotedIntegralType = 13;
3266 const unsigned FirstPromotedArithmeticType = 7,
3267 LastPromotedArithmeticType = 16;
3268 const unsigned NumArithmeticTypes = 16;
3269 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003270 Context.BoolTy, Context.CharTy, Context.WCharTy,
3271// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003272 Context.SignedCharTy, Context.ShortTy,
3273 Context.UnsignedCharTy, Context.UnsignedShortTy,
3274 Context.IntTy, Context.LongTy, Context.LongLongTy,
3275 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3276 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3277 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003278 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3279 "Invalid first promoted integral type");
3280 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3281 == Context.UnsignedLongLongTy &&
3282 "Invalid last promoted integral type");
3283 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3284 "Invalid first promoted arithmetic type");
3285 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3286 == Context.LongDoubleTy &&
3287 "Invalid last promoted arithmetic type");
3288
Douglas Gregora11693b2008-11-12 17:17:38 +00003289 // Find all of the types that the arguments can convert to, but only
3290 // if the operator we're looking at has built-in operator candidates
3291 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003292 Qualifiers VisibleTypeConversionsQuals;
3293 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003294 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3295 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3296
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003297 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003298 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3299 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003300 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003301 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003302 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003303 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003304 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003305 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003306 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003307 true,
3308 (Op == OO_Exclaim ||
3309 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003310 Op == OO_PipePipe),
3311 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003312 }
3313
3314 bool isComparison = false;
3315 switch (Op) {
3316 case OO_None:
3317 case NUM_OVERLOADED_OPERATORS:
3318 assert(false && "Expected an overloaded operator");
3319 break;
3320
Douglas Gregord08452f2008-11-19 15:42:04 +00003321 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003322 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003323 goto UnaryStar;
3324 else
3325 goto BinaryStar;
3326 break;
3327
3328 case OO_Plus: // '+' is either unary or binary
3329 if (NumArgs == 1)
3330 goto UnaryPlus;
3331 else
3332 goto BinaryPlus;
3333 break;
3334
3335 case OO_Minus: // '-' is either unary or binary
3336 if (NumArgs == 1)
3337 goto UnaryMinus;
3338 else
3339 goto BinaryMinus;
3340 break;
3341
3342 case OO_Amp: // '&' is either unary or binary
3343 if (NumArgs == 1)
3344 goto UnaryAmp;
3345 else
3346 goto BinaryAmp;
3347
3348 case OO_PlusPlus:
3349 case OO_MinusMinus:
3350 // C++ [over.built]p3:
3351 //
3352 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3353 // is either volatile or empty, there exist candidate operator
3354 // functions of the form
3355 //
3356 // VQ T& operator++(VQ T&);
3357 // T operator++(VQ T&, int);
3358 //
3359 // C++ [over.built]p4:
3360 //
3361 // For every pair (T, VQ), where T is an arithmetic type other
3362 // than bool, and VQ is either volatile or empty, there exist
3363 // candidate operator functions of the form
3364 //
3365 // VQ T& operator--(VQ T&);
3366 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003367 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003368 Arith < NumArithmeticTypes; ++Arith) {
3369 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003370 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003371 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003372
3373 // Non-volatile version.
3374 if (NumArgs == 1)
3375 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3376 else
3377 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003378 // heuristic to reduce number of builtin candidates in the set.
3379 // Add volatile version only if there are conversions to a volatile type.
3380 if (VisibleTypeConversionsQuals.hasVolatile()) {
3381 // Volatile version
3382 ParamTypes[0]
3383 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3384 if (NumArgs == 1)
3385 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3386 else
3387 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3388 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003389 }
3390
3391 // C++ [over.built]p5:
3392 //
3393 // For every pair (T, VQ), where T is a cv-qualified or
3394 // cv-unqualified object type, and VQ is either volatile or
3395 // empty, there exist candidate operator functions of the form
3396 //
3397 // T*VQ& operator++(T*VQ&);
3398 // T*VQ& operator--(T*VQ&);
3399 // T* operator++(T*VQ&, int);
3400 // T* operator--(T*VQ&, int);
3401 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3402 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3403 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003404 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003405 continue;
3406
Mike Stump11289f42009-09-09 15:08:12 +00003407 QualType ParamTypes[2] = {
3408 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003409 };
Mike Stump11289f42009-09-09 15:08:12 +00003410
Douglas Gregord08452f2008-11-19 15:42:04 +00003411 // Without volatile
3412 if (NumArgs == 1)
3413 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3414 else
3415 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3416
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003417 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3418 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003419 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003420 ParamTypes[0]
3421 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003422 if (NumArgs == 1)
3423 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3424 else
3425 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3426 }
3427 }
3428 break;
3429
3430 UnaryStar:
3431 // C++ [over.built]p6:
3432 // For every cv-qualified or cv-unqualified object type T, there
3433 // exist candidate operator functions of the form
3434 //
3435 // T& operator*(T*);
3436 //
3437 // C++ [over.built]p7:
3438 // For every function type T, there exist candidate operator
3439 // functions of the form
3440 // T& operator*(T*);
3441 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3442 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3443 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003444 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003445 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003446 &ParamTy, Args, 1, CandidateSet);
3447 }
3448 break;
3449
3450 UnaryPlus:
3451 // C++ [over.built]p8:
3452 // For every type T, there exist candidate operator functions of
3453 // the form
3454 //
3455 // T* operator+(T*);
3456 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3457 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3458 QualType ParamTy = *Ptr;
3459 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3460 }
Mike Stump11289f42009-09-09 15:08:12 +00003461
Douglas Gregord08452f2008-11-19 15:42:04 +00003462 // Fall through
3463
3464 UnaryMinus:
3465 // C++ [over.built]p9:
3466 // For every promoted arithmetic type T, there exist candidate
3467 // operator functions of the form
3468 //
3469 // T operator+(T);
3470 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003471 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003472 Arith < LastPromotedArithmeticType; ++Arith) {
3473 QualType ArithTy = ArithmeticTypes[Arith];
3474 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3475 }
3476 break;
3477
3478 case OO_Tilde:
3479 // C++ [over.built]p10:
3480 // For every promoted integral type T, there exist candidate
3481 // operator functions of the form
3482 //
3483 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003484 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003485 Int < LastPromotedIntegralType; ++Int) {
3486 QualType IntTy = ArithmeticTypes[Int];
3487 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3488 }
3489 break;
3490
Douglas Gregora11693b2008-11-12 17:17:38 +00003491 case OO_New:
3492 case OO_Delete:
3493 case OO_Array_New:
3494 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003495 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003496 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003497 break;
3498
3499 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003500 UnaryAmp:
3501 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003502 // C++ [over.match.oper]p3:
3503 // -- For the operator ',', the unary operator '&', or the
3504 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003505 break;
3506
Douglas Gregor84605ae2009-08-24 13:43:27 +00003507 case OO_EqualEqual:
3508 case OO_ExclaimEqual:
3509 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003510 // For every pointer to member type T, there exist candidate operator
3511 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003512 //
3513 // bool operator==(T,T);
3514 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003515 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003516 MemPtr = CandidateTypes.member_pointer_begin(),
3517 MemPtrEnd = CandidateTypes.member_pointer_end();
3518 MemPtr != MemPtrEnd;
3519 ++MemPtr) {
3520 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3521 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3522 }
Mike Stump11289f42009-09-09 15:08:12 +00003523
Douglas Gregor84605ae2009-08-24 13:43:27 +00003524 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003525
Douglas Gregora11693b2008-11-12 17:17:38 +00003526 case OO_Less:
3527 case OO_Greater:
3528 case OO_LessEqual:
3529 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003530 // C++ [over.built]p15:
3531 //
3532 // For every pointer or enumeration type T, there exist
3533 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003534 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003535 // bool operator<(T, T);
3536 // bool operator>(T, T);
3537 // bool operator<=(T, T);
3538 // bool operator>=(T, T);
3539 // bool operator==(T, T);
3540 // bool operator!=(T, T);
3541 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3542 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3543 QualType ParamTypes[2] = { *Ptr, *Ptr };
3544 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3545 }
Mike Stump11289f42009-09-09 15:08:12 +00003546 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003547 = CandidateTypes.enumeration_begin();
3548 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3549 QualType ParamTypes[2] = { *Enum, *Enum };
3550 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3551 }
3552
3553 // Fall through.
3554 isComparison = true;
3555
Douglas Gregord08452f2008-11-19 15:42:04 +00003556 BinaryPlus:
3557 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003558 if (!isComparison) {
3559 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3560
3561 // C++ [over.built]p13:
3562 //
3563 // For every cv-qualified or cv-unqualified object type T
3564 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003565 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003566 // T* operator+(T*, ptrdiff_t);
3567 // T& operator[](T*, ptrdiff_t); [BELOW]
3568 // T* operator-(T*, ptrdiff_t);
3569 // T* operator+(ptrdiff_t, T*);
3570 // T& operator[](ptrdiff_t, T*); [BELOW]
3571 //
3572 // C++ [over.built]p14:
3573 //
3574 // For every T, where T is a pointer to object type, there
3575 // exist candidate operator functions of the form
3576 //
3577 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003578 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003579 = CandidateTypes.pointer_begin();
3580 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3581 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3582
3583 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3584 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3585
3586 if (Op == OO_Plus) {
3587 // T* operator+(ptrdiff_t, T*);
3588 ParamTypes[0] = ParamTypes[1];
3589 ParamTypes[1] = *Ptr;
3590 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3591 } else {
3592 // ptrdiff_t operator-(T, T);
3593 ParamTypes[1] = *Ptr;
3594 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3595 Args, 2, CandidateSet);
3596 }
3597 }
3598 }
3599 // Fall through
3600
Douglas Gregora11693b2008-11-12 17:17:38 +00003601 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003602 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003603 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003604 // C++ [over.built]p12:
3605 //
3606 // For every pair of promoted arithmetic types L and R, there
3607 // exist candidate operator functions of the form
3608 //
3609 // LR operator*(L, R);
3610 // LR operator/(L, R);
3611 // LR operator+(L, R);
3612 // LR operator-(L, R);
3613 // bool operator<(L, R);
3614 // bool operator>(L, R);
3615 // bool operator<=(L, R);
3616 // bool operator>=(L, R);
3617 // bool operator==(L, R);
3618 // bool operator!=(L, R);
3619 //
3620 // where LR is the result of the usual arithmetic conversions
3621 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003622 //
3623 // C++ [over.built]p24:
3624 //
3625 // For every pair of promoted arithmetic types L and R, there exist
3626 // candidate operator functions of the form
3627 //
3628 // LR operator?(bool, L, R);
3629 //
3630 // where LR is the result of the usual arithmetic conversions
3631 // between types L and R.
3632 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003633 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003634 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003635 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003636 Right < LastPromotedArithmeticType; ++Right) {
3637 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003638 QualType Result
3639 = isComparison
3640 ? Context.BoolTy
3641 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003642 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3643 }
3644 }
3645 break;
3646
3647 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003648 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003649 case OO_Caret:
3650 case OO_Pipe:
3651 case OO_LessLess:
3652 case OO_GreaterGreater:
3653 // C++ [over.built]p17:
3654 //
3655 // For every pair of promoted integral types L and R, there
3656 // exist candidate operator functions of the form
3657 //
3658 // LR operator%(L, R);
3659 // LR operator&(L, R);
3660 // LR operator^(L, R);
3661 // LR operator|(L, R);
3662 // L operator<<(L, R);
3663 // L operator>>(L, R);
3664 //
3665 // where LR is the result of the usual arithmetic conversions
3666 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003667 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003668 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003669 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003670 Right < LastPromotedIntegralType; ++Right) {
3671 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3672 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3673 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003674 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003675 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3676 }
3677 }
3678 break;
3679
3680 case OO_Equal:
3681 // C++ [over.built]p20:
3682 //
3683 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003684 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003685 // empty, there exist candidate operator functions of the form
3686 //
3687 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003688 for (BuiltinCandidateTypeSet::iterator
3689 Enum = CandidateTypes.enumeration_begin(),
3690 EnumEnd = CandidateTypes.enumeration_end();
3691 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003692 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003693 CandidateSet);
3694 for (BuiltinCandidateTypeSet::iterator
3695 MemPtr = CandidateTypes.member_pointer_begin(),
3696 MemPtrEnd = CandidateTypes.member_pointer_end();
3697 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003698 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003699 CandidateSet);
3700 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003701
3702 case OO_PlusEqual:
3703 case OO_MinusEqual:
3704 // C++ [over.built]p19:
3705 //
3706 // For every pair (T, VQ), where T is any type and VQ is either
3707 // volatile or empty, there exist candidate operator functions
3708 // of the form
3709 //
3710 // T*VQ& operator=(T*VQ&, T*);
3711 //
3712 // C++ [over.built]p21:
3713 //
3714 // For every pair (T, VQ), where T is a cv-qualified or
3715 // cv-unqualified object type and VQ is either volatile or
3716 // empty, there exist candidate operator functions of the form
3717 //
3718 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3719 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3720 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3721 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3722 QualType ParamTypes[2];
3723 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3724
3725 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003726 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003727 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3728 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003729
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003730 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3731 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003732 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003733 ParamTypes[0]
3734 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003735 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3736 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003737 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003738 }
3739 // Fall through.
3740
3741 case OO_StarEqual:
3742 case OO_SlashEqual:
3743 // C++ [over.built]p18:
3744 //
3745 // For every triple (L, VQ, R), where L is an arithmetic type,
3746 // VQ is either volatile or empty, and R is a promoted
3747 // arithmetic type, there exist candidate operator functions of
3748 // the form
3749 //
3750 // VQ L& operator=(VQ L&, R);
3751 // VQ L& operator*=(VQ L&, R);
3752 // VQ L& operator/=(VQ L&, R);
3753 // VQ L& operator+=(VQ L&, R);
3754 // VQ L& operator-=(VQ L&, R);
3755 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003756 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003757 Right < LastPromotedArithmeticType; ++Right) {
3758 QualType ParamTypes[2];
3759 ParamTypes[1] = ArithmeticTypes[Right];
3760
3761 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003762 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003763 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3764 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003765
3766 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003767 if (VisibleTypeConversionsQuals.hasVolatile()) {
3768 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3769 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3770 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3771 /*IsAssigmentOperator=*/Op == OO_Equal);
3772 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003773 }
3774 }
3775 break;
3776
3777 case OO_PercentEqual:
3778 case OO_LessLessEqual:
3779 case OO_GreaterGreaterEqual:
3780 case OO_AmpEqual:
3781 case OO_CaretEqual:
3782 case OO_PipeEqual:
3783 // C++ [over.built]p22:
3784 //
3785 // For every triple (L, VQ, R), where L is an integral type, VQ
3786 // is either volatile or empty, and R is a promoted integral
3787 // type, there exist candidate operator functions of the form
3788 //
3789 // VQ L& operator%=(VQ L&, R);
3790 // VQ L& operator<<=(VQ L&, R);
3791 // VQ L& operator>>=(VQ L&, R);
3792 // VQ L& operator&=(VQ L&, R);
3793 // VQ L& operator^=(VQ L&, R);
3794 // VQ L& operator|=(VQ L&, R);
3795 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003796 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003797 Right < LastPromotedIntegralType; ++Right) {
3798 QualType ParamTypes[2];
3799 ParamTypes[1] = ArithmeticTypes[Right];
3800
3801 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003802 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003803 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003804 if (VisibleTypeConversionsQuals.hasVolatile()) {
3805 // Add this built-in operator as a candidate (VQ is 'volatile').
3806 ParamTypes[0] = ArithmeticTypes[Left];
3807 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3808 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3809 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3810 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003811 }
3812 }
3813 break;
3814
Douglas Gregord08452f2008-11-19 15:42:04 +00003815 case OO_Exclaim: {
3816 // C++ [over.operator]p23:
3817 //
3818 // There also exist candidate operator functions of the form
3819 //
Mike Stump11289f42009-09-09 15:08:12 +00003820 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003821 // bool operator&&(bool, bool); [BELOW]
3822 // bool operator||(bool, bool); [BELOW]
3823 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003824 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3825 /*IsAssignmentOperator=*/false,
3826 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003827 break;
3828 }
3829
Douglas Gregora11693b2008-11-12 17:17:38 +00003830 case OO_AmpAmp:
3831 case OO_PipePipe: {
3832 // C++ [over.operator]p23:
3833 //
3834 // There also exist candidate operator functions of the form
3835 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003836 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003837 // bool operator&&(bool, bool);
3838 // bool operator||(bool, bool);
3839 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003840 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3841 /*IsAssignmentOperator=*/false,
3842 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003843 break;
3844 }
3845
3846 case OO_Subscript:
3847 // C++ [over.built]p13:
3848 //
3849 // For every cv-qualified or cv-unqualified object type T there
3850 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003851 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003852 // T* operator+(T*, ptrdiff_t); [ABOVE]
3853 // T& operator[](T*, ptrdiff_t);
3854 // T* operator-(T*, ptrdiff_t); [ABOVE]
3855 // T* operator+(ptrdiff_t, T*); [ABOVE]
3856 // T& operator[](ptrdiff_t, T*);
3857 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3858 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3859 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003860 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003861 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003862
3863 // T& operator[](T*, ptrdiff_t)
3864 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3865
3866 // T& operator[](ptrdiff_t, T*);
3867 ParamTypes[0] = ParamTypes[1];
3868 ParamTypes[1] = *Ptr;
3869 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3870 }
3871 break;
3872
3873 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003874 // C++ [over.built]p11:
3875 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3876 // C1 is the same type as C2 or is a derived class of C2, T is an object
3877 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3878 // there exist candidate operator functions of the form
3879 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3880 // where CV12 is the union of CV1 and CV2.
3881 {
3882 for (BuiltinCandidateTypeSet::iterator Ptr =
3883 CandidateTypes.pointer_begin();
3884 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3885 QualType C1Ty = (*Ptr);
3886 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003887 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003888 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003889 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003890 if (!isa<RecordType>(C1))
3891 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003892 // heuristic to reduce number of builtin candidates in the set.
3893 // Add volatile/restrict version only if there are conversions to a
3894 // volatile/restrict type.
3895 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3896 continue;
3897 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3898 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003899 }
3900 for (BuiltinCandidateTypeSet::iterator
3901 MemPtr = CandidateTypes.member_pointer_begin(),
3902 MemPtrEnd = CandidateTypes.member_pointer_end();
3903 MemPtr != MemPtrEnd; ++MemPtr) {
3904 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3905 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00003906 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003907 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3908 break;
3909 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3910 // build CV12 T&
3911 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003912 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3913 T.isVolatileQualified())
3914 continue;
3915 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3916 T.isRestrictQualified())
3917 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003918 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003919 QualType ResultTy = Context.getLValueReferenceType(T);
3920 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3921 }
3922 }
3923 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003924 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003925
3926 case OO_Conditional:
3927 // Note that we don't consider the first argument, since it has been
3928 // contextually converted to bool long ago. The candidates below are
3929 // therefore added as binary.
3930 //
3931 // C++ [over.built]p24:
3932 // For every type T, where T is a pointer or pointer-to-member type,
3933 // there exist candidate operator functions of the form
3934 //
3935 // T operator?(bool, T, T);
3936 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003937 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3938 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3939 QualType ParamTypes[2] = { *Ptr, *Ptr };
3940 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3941 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003942 for (BuiltinCandidateTypeSet::iterator Ptr =
3943 CandidateTypes.member_pointer_begin(),
3944 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3945 QualType ParamTypes[2] = { *Ptr, *Ptr };
3946 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3947 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003948 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003949 }
3950}
3951
Douglas Gregore254f902009-02-04 00:32:51 +00003952/// \brief Add function candidates found via argument-dependent lookup
3953/// to the set of overloading candidates.
3954///
3955/// This routine performs argument-dependent name lookup based on the
3956/// given function name (which may also be an operator name) and adds
3957/// all of the overload candidates found by ADL to the overload
3958/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003959void
Douglas Gregore254f902009-02-04 00:32:51 +00003960Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3961 Expr **Args, unsigned NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003962 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00003963 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003964 unsigned NumExplicitTemplateArgs,
3965 OverloadCandidateSet& CandidateSet,
3966 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003967 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003968
Douglas Gregorcabea402009-09-22 15:41:20 +00003969 // FIXME: Should we be trafficking in canonical function decls throughout?
3970
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003971 // Record all of the function candidates that we've already
3972 // added to the overload set, so that we don't add those same
3973 // candidates a second time.
3974 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3975 CandEnd = CandidateSet.end();
3976 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003977 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003978 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003979 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3980 Functions.insert(FunTmpl);
3981 }
Douglas Gregore254f902009-02-04 00:32:51 +00003982
Douglas Gregorcabea402009-09-22 15:41:20 +00003983 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00003984 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003985
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003986 // Erase all of the candidates we already knew about.
3987 // FIXME: This is suboptimal. Is there a better way?
3988 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3989 CandEnd = CandidateSet.end();
3990 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003991 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003992 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003993 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3994 Functions.erase(FunTmpl);
3995 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003996
3997 // For each of the ADL candidates we found, add it to the overload
3998 // set.
3999 for (FunctionSet::iterator Func = Functions.begin(),
4000 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00004001 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004002 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
4003 if (HasExplicitTemplateArgs)
4004 continue;
4005
4006 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4007 false, false, PartialOverloading);
4008 } else
Mike Stump11289f42009-09-09 15:08:12 +00004009 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00004010 HasExplicitTemplateArgs,
4011 ExplicitTemplateArgs,
4012 NumExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004013 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004014 }
Douglas Gregore254f902009-02-04 00:32:51 +00004015}
4016
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004017/// isBetterOverloadCandidate - Determines whether the first overload
4018/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004019bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004020Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00004021 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004022 // Define viable functions to be better candidates than non-viable
4023 // functions.
4024 if (!Cand2.Viable)
4025 return Cand1.Viable;
4026 else if (!Cand1.Viable)
4027 return false;
4028
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004029 // C++ [over.match.best]p1:
4030 //
4031 // -- if F is a static member function, ICS1(F) is defined such
4032 // that ICS1(F) is neither better nor worse than ICS1(G) for
4033 // any function G, and, symmetrically, ICS1(G) is neither
4034 // better nor worse than ICS1(F).
4035 unsigned StartArg = 0;
4036 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4037 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004038
Douglas Gregord3cb3562009-07-07 23:38:56 +00004039 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004040 // A viable function F1 is defined to be a better function than another
4041 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004042 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004043 unsigned NumArgs = Cand1.Conversions.size();
4044 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4045 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004046 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004047 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4048 Cand2.Conversions[ArgIdx])) {
4049 case ImplicitConversionSequence::Better:
4050 // Cand1 has a better conversion sequence.
4051 HasBetterConversion = true;
4052 break;
4053
4054 case ImplicitConversionSequence::Worse:
4055 // Cand1 can't be better than Cand2.
4056 return false;
4057
4058 case ImplicitConversionSequence::Indistinguishable:
4059 // Do nothing.
4060 break;
4061 }
4062 }
4063
Mike Stump11289f42009-09-09 15:08:12 +00004064 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004065 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004066 if (HasBetterConversion)
4067 return true;
4068
Mike Stump11289f42009-09-09 15:08:12 +00004069 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004070 // specialization, or, if not that,
4071 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4072 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4073 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004074
4075 // -- F1 and F2 are function template specializations, and the function
4076 // template for F1 is more specialized than the template for F2
4077 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004078 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004079 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4080 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004081 if (FunctionTemplateDecl *BetterTemplate
4082 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4083 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004084 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4085 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004086 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004087
Douglas Gregora1f013e2008-11-07 22:36:19 +00004088 // -- the context is an initialization by user-defined conversion
4089 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4090 // from the return type of F1 to the destination type (i.e.,
4091 // the type of the entity being initialized) is a better
4092 // conversion sequence than the standard conversion sequence
4093 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004094 if (Cand1.Function && Cand2.Function &&
4095 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004096 isa<CXXConversionDecl>(Cand2.Function)) {
4097 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4098 Cand2.FinalConversion)) {
4099 case ImplicitConversionSequence::Better:
4100 // Cand1 has a better conversion sequence.
4101 return true;
4102
4103 case ImplicitConversionSequence::Worse:
4104 // Cand1 can't be better than Cand2.
4105 return false;
4106
4107 case ImplicitConversionSequence::Indistinguishable:
4108 // Do nothing
4109 break;
4110 }
4111 }
4112
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004113 return false;
4114}
4115
Mike Stump11289f42009-09-09 15:08:12 +00004116/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004117/// within an overload candidate set.
4118///
4119/// \param CandidateSet the set of candidate functions.
4120///
4121/// \param Loc the location of the function name (or operator symbol) for
4122/// which overload resolution occurs.
4123///
Mike Stump11289f42009-09-09 15:08:12 +00004124/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004125/// function, Best points to the candidate function found.
4126///
4127/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00004128Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004129Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004130 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004131 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004132 // Find the best viable function.
4133 Best = CandidateSet.end();
4134 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4135 Cand != CandidateSet.end(); ++Cand) {
4136 if (Cand->Viable) {
4137 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4138 Best = Cand;
4139 }
4140 }
4141
4142 // If we didn't find any viable functions, abort.
4143 if (Best == CandidateSet.end())
4144 return OR_No_Viable_Function;
4145
4146 // Make sure that this function is better than every other viable
4147 // function. If not, we have an ambiguity.
4148 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4149 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004150 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004151 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004152 !isBetterOverloadCandidate(*Best, *Cand)) {
4153 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004154 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004155 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004156 }
Mike Stump11289f42009-09-09 15:08:12 +00004157
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004158 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004159 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004160 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004161 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004162 return OR_Deleted;
4163
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004164 // C++ [basic.def.odr]p2:
4165 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004166 // when referred to from a potentially-evaluated expression. [Note: this
4167 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004168 // (clause 13), user-defined conversions (12.3.2), allocation function for
4169 // placement new (5.3.4), as well as non-default initialization (8.5).
4170 if (Best->Function)
4171 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004172 return OR_Success;
4173}
4174
4175/// PrintOverloadCandidates - When overload resolution fails, prints
4176/// diagnostic messages containing the candidates in the candidate
4177/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00004178void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004179Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004180 bool OnlyViable,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004181 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004182 SourceLocation OpLoc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004183 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4184 LastCand = CandidateSet.end();
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004185 bool Reported = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004186 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004187 if (Cand->Viable || !OnlyViable) {
4188 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004189 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004190 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004191 // Deleted or "unavailable" function.
4192 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4193 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00004194 } else if (FunctionTemplateDecl *FunTmpl
4195 = Cand->Function->getPrimaryTemplate()) {
4196 // Function template specialization
4197 // FIXME: Give a better reason!
4198 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4199 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4200 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00004201 } else {
4202 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00004203 bool errReported = false;
4204 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4205 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4206 const ImplicitConversionSequence &Conversion =
4207 Cand->Conversions[i];
4208 if ((Conversion.ConversionKind !=
4209 ImplicitConversionSequence::BadConversion) ||
4210 Conversion.ConversionFunctionSet.size() == 0)
4211 continue;
4212 Diag(Cand->Function->getLocation(),
4213 diag::err_ovl_candidate_not_viable) << (i+1);
4214 errReported = true;
4215 for (int j = Conversion.ConversionFunctionSet.size()-1;
4216 j >= 0; j--) {
4217 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4218 Diag(Func->getLocation(), diag::err_ovl_candidate);
4219 }
4220 }
4221 }
4222 if (!errReported)
4223 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004224 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004225 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004226 // Desugar the type of the surrogate down to a function type,
4227 // retaining as many typedefs as possible while still showing
4228 // the function type (and, therefore, its parameter types).
4229 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004230 bool isLValueReference = false;
4231 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004232 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004233 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004234 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004235 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004236 isLValueReference = true;
4237 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004238 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004239 FnType = FnTypeRef->getPointeeType();
4240 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004241 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004242 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004243 FnType = FnTypePtr->getPointeeType();
4244 isPointer = true;
4245 }
4246 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00004247 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004248 // Reconstruct the pointer/reference as appropriate.
4249 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004250 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4251 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004252
Douglas Gregorab7897a2008-11-19 22:57:39 +00004253 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004254 << FnType;
Douglas Gregor66950a32009-09-30 21:46:01 +00004255 } else if (OnlyViable) {
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004256 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanian0fe5e032009-10-09 17:09:58 +00004257 "builtin-binary-operator-not-binary");
Fariborz Jahanian956127d2009-10-16 23:25:02 +00004258 std::string TypeStr("operator");
4259 TypeStr += Opc;
4260 TypeStr += "(";
4261 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4262 if (Cand->Conversions.size() == 1) {
4263 TypeStr += ")";
4264 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4265 }
4266 else {
4267 TypeStr += ", ";
4268 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4269 TypeStr += ")";
4270 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4271 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004272 }
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004273 else if (!Cand->Viable && !Reported) {
4274 // Non-viability might be due to ambiguous user-defined conversions,
4275 // needed for built-in operators. Report them as well, but only once
4276 // as we have typically many built-in candidates.
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004277 unsigned NoOperands = Cand->Conversions.size();
4278 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004279 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4280 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4281 ICS.ConversionFunctionSet.empty())
4282 continue;
4283 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4284 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4285 QualType FromTy =
4286 QualType(
4287 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4288 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4289 << FromTy << Func->getConversionType();
4290 }
4291 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4292 FunctionDecl *Func =
4293 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4294 Diag(Func->getLocation(),diag::err_ovl_candidate);
4295 }
4296 }
4297 Reported = true;
4298 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004299 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004300 }
4301}
4302
Douglas Gregorcd695e52008-11-10 20:40:00 +00004303/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4304/// an overloaded function (C++ [over.over]), where @p From is an
4305/// expression with overloaded function type and @p ToType is the type
4306/// we're trying to resolve to. For example:
4307///
4308/// @code
4309/// int f(double);
4310/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004311///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004312/// int (*pfd)(double) = f; // selects f(double)
4313/// @endcode
4314///
4315/// This routine returns the resulting FunctionDecl if it could be
4316/// resolved, and NULL otherwise. When @p Complain is true, this
4317/// routine will emit diagnostics if there is an error.
4318FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004319Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004320 bool Complain) {
4321 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004322 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004323 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004324 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004325 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004326 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004327 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004328 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004329 FunctionType = MemTypePtr->getPointeeType();
4330 IsMember = true;
4331 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004332
4333 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004334 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004335 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004336 return 0;
4337
4338 // Find the actual overloaded function declaration.
4339 OverloadedFunctionDecl *Ovl = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004340
Douglas Gregorcd695e52008-11-10 20:40:00 +00004341 // C++ [over.over]p1:
4342 // [...] [Note: any redundant set of parentheses surrounding the
4343 // overloaded function name is ignored (5.1). ]
4344 Expr *OvlExpr = From->IgnoreParens();
4345
4346 // C++ [over.over]p1:
4347 // [...] The overloaded function name can be preceded by the &
4348 // operator.
4349 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4350 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4351 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4352 }
4353
Anders Carlssonb68b0282009-10-20 22:53:47 +00004354 bool HasExplicitTemplateArgs = false;
John McCall0ad16662009-10-29 08:12:44 +00004355 const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004356 unsigned NumExplicitTemplateArgs = 0;
4357
Douglas Gregorcd695e52008-11-10 20:40:00 +00004358 // Try to dig out the overloaded function.
Douglas Gregor9b146582009-07-08 20:55:45 +00004359 FunctionTemplateDecl *FunctionTemplate = 0;
4360 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004361 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor9b146582009-07-08 20:55:45 +00004362 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
Douglas Gregord3319842009-10-24 04:59:53 +00004363 HasExplicitTemplateArgs = DR->hasExplicitTemplateArgumentList();
4364 ExplicitTemplateArgs = DR->getTemplateArgs();
4365 NumExplicitTemplateArgs = DR->getNumTemplateArgs();
Anders Carlsson6c966c42009-10-07 22:26:29 +00004366 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(OvlExpr)) {
4367 Ovl = dyn_cast<OverloadedFunctionDecl>(ME->getMemberDecl());
4368 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(ME->getMemberDecl());
Douglas Gregord3319842009-10-24 04:59:53 +00004369 HasExplicitTemplateArgs = ME->hasExplicitTemplateArgumentList();
4370 ExplicitTemplateArgs = ME->getTemplateArgs();
4371 NumExplicitTemplateArgs = ME->getNumTemplateArgs();
Anders Carlssonb68b0282009-10-20 22:53:47 +00004372 } else if (TemplateIdRefExpr *TIRE = dyn_cast<TemplateIdRefExpr>(OvlExpr)) {
4373 TemplateName Name = TIRE->getTemplateName();
4374 Ovl = Name.getAsOverloadedFunctionDecl();
4375 FunctionTemplate =
4376 dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4377
4378 HasExplicitTemplateArgs = true;
4379 ExplicitTemplateArgs = TIRE->getTemplateArgs();
4380 NumExplicitTemplateArgs = TIRE->getNumTemplateArgs();
Douglas Gregor9b146582009-07-08 20:55:45 +00004381 }
Anders Carlssonb68b0282009-10-20 22:53:47 +00004382
Mike Stump11289f42009-09-09 15:08:12 +00004383 // If there's no overloaded function declaration or function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00004384 // we're done.
4385 if (!Ovl && !FunctionTemplate)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004386 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004387
Douglas Gregor9b146582009-07-08 20:55:45 +00004388 OverloadIterator Fun;
4389 if (Ovl)
4390 Fun = Ovl;
4391 else
4392 Fun = FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00004393
Douglas Gregorcd695e52008-11-10 20:40:00 +00004394 // Look through all of the overloaded functions, searching for one
4395 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004396 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004397 bool FoundNonTemplateFunction = false;
Douglas Gregor9b146582009-07-08 20:55:45 +00004398 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004399 // C++ [over.over]p3:
4400 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004401 // targets of type "pointer-to-function" or "reference-to-function."
4402 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004403 // type "pointer-to-member-function."
4404 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004405
Mike Stump11289f42009-09-09 15:08:12 +00004406 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor9b146582009-07-08 20:55:45 +00004407 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump11289f42009-09-09 15:08:12 +00004408 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004409 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004410 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004411 // static when converting to member pointer.
4412 if (Method->isStatic() == IsMember)
4413 continue;
4414 } else if (IsMember)
4415 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004416
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004417 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004418 // If the name is a function template, template argument deduction is
4419 // done (14.8.2.2), and if the argument deduction succeeds, the
4420 // resulting template argument list is used to generate a single
4421 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004422 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004423 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004424 FunctionDecl *Specialization = 0;
4425 TemplateDeductionInfo Info(Context);
4426 if (TemplateDeductionResult Result
Anders Carlssonb68b0282009-10-20 22:53:47 +00004427 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
4428 ExplicitTemplateArgs,
4429 NumExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00004430 FunctionType, Specialization, Info)) {
4431 // FIXME: make a note of the failed deduction for diagnostics.
4432 (void)Result;
4433 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004434 // FIXME: If the match isn't exact, shouldn't we just drop this as
4435 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004436 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004437 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004438 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004439 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004440 }
4441 }
Mike Stump11289f42009-09-09 15:08:12 +00004442
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004443 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4444 // Skip non-static functions when converting to pointer, and static
4445 // when converting to member pointer.
4446 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004447 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004448
4449 // If we have explicit template arguments, skip non-templates.
4450 if (HasExplicitTemplateArgs)
4451 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004452 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004453 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004454
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004455 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004456 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004457 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004458 FoundNonTemplateFunction = true;
4459 }
Mike Stump11289f42009-09-09 15:08:12 +00004460 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004461 }
4462
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004463 // If there were 0 or 1 matches, we're done.
4464 if (Matches.empty())
4465 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004466 else if (Matches.size() == 1) {
4467 FunctionDecl *Result = *Matches.begin();
4468 MarkDeclarationReferenced(From->getLocStart(), Result);
4469 return Result;
4470 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004471
4472 // C++ [over.over]p4:
4473 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004474 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004475 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004476 // [...] and any given function template specialization F1 is
4477 // eliminated if the set contains a second function template
4478 // specialization whose function template is more specialized
4479 // than the function template of F1 according to the partial
4480 // ordering rules of 14.5.5.2.
4481
4482 // The algorithm specified above is quadratic. We instead use a
4483 // two-pass algorithm (similar to the one used to identify the
4484 // best viable function in an overload set) that identifies the
4485 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004486 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004487 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004488 FunctionDecl *Result =
4489 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4490 TPOC_Other, From->getLocStart(),
4491 PDiag(),
4492 PDiag(diag::err_addr_ovl_ambiguous)
4493 << TemplateMatches[0]->getDeclName(),
4494 PDiag(diag::err_ovl_template_candidate));
4495 MarkDeclarationReferenced(From->getLocStart(), Result);
4496 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004497 }
Mike Stump11289f42009-09-09 15:08:12 +00004498
Douglas Gregorfae1d712009-09-26 03:56:17 +00004499 // [...] any function template specializations in the set are
4500 // eliminated if the set also contains a non-template function, [...]
4501 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4502 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4503 if ((*M)->getPrimaryTemplate() == 0)
4504 RemainingMatches.push_back(*M);
4505
Mike Stump11289f42009-09-09 15:08:12 +00004506 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004507 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004508 if (RemainingMatches.size() == 1) {
4509 FunctionDecl *Result = RemainingMatches.front();
4510 MarkDeclarationReferenced(From->getLocStart(), Result);
4511 return Result;
4512 }
Mike Stump11289f42009-09-09 15:08:12 +00004513
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004514 // FIXME: We should probably return the same thing that BestViableFunction
4515 // returns (even if we issue the diagnostics here).
4516 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4517 << RemainingMatches[0]->getDeclName();
4518 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4519 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004520 return 0;
4521}
4522
Douglas Gregorcabea402009-09-22 15:41:20 +00004523/// \brief Add a single candidate to the overload set.
4524static void AddOverloadedCallCandidate(Sema &S,
4525 AnyFunctionDecl Callee,
4526 bool &ArgumentDependentLookup,
4527 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00004528 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004529 unsigned NumExplicitTemplateArgs,
4530 Expr **Args, unsigned NumArgs,
4531 OverloadCandidateSet &CandidateSet,
4532 bool PartialOverloading) {
4533 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4534 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4535 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4536 PartialOverloading);
4537
4538 if (Func->getDeclContext()->isRecord() ||
4539 Func->getDeclContext()->isFunctionOrMethod())
4540 ArgumentDependentLookup = false;
4541 return;
4542 }
4543
4544 FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4545 S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4546 ExplicitTemplateArgs,
4547 NumExplicitTemplateArgs,
4548 Args, NumArgs, CandidateSet);
4549
4550 if (FuncTemplate->getDeclContext()->isRecord())
4551 ArgumentDependentLookup = false;
4552}
4553
4554/// \brief Add the overload candidates named by callee and/or found by argument
4555/// dependent lookup to the given overload set.
4556void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4557 DeclarationName &UnqualifiedName,
4558 bool &ArgumentDependentLookup,
4559 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00004560 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004561 unsigned NumExplicitTemplateArgs,
4562 Expr **Args, unsigned NumArgs,
4563 OverloadCandidateSet &CandidateSet,
4564 bool PartialOverloading) {
4565 // Add the functions denoted by Callee to the set of candidate
4566 // functions. While we're doing so, track whether argument-dependent
4567 // lookup still applies, per:
4568 //
4569 // C++0x [basic.lookup.argdep]p3:
4570 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4571 // and let Y be the lookup set produced by argument dependent
4572 // lookup (defined as follows). If X contains
4573 //
4574 // -- a declaration of a class member, or
4575 //
4576 // -- a block-scope function declaration that is not a
4577 // using-declaration (FIXME: check for using declaration), or
4578 //
4579 // -- a declaration that is neither a function or a function
4580 // template
4581 //
4582 // then Y is empty.
4583 if (!Callee) {
4584 // Nothing to do.
4585 } else if (OverloadedFunctionDecl *Ovl
4586 = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4587 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4588 FuncEnd = Ovl->function_end();
4589 Func != FuncEnd; ++Func)
4590 AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4591 HasExplicitTemplateArgs,
4592 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4593 Args, NumArgs, CandidateSet,
4594 PartialOverloading);
4595 } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4596 AddOverloadedCallCandidate(*this,
4597 AnyFunctionDecl::getFromNamedDecl(Callee),
4598 ArgumentDependentLookup,
4599 HasExplicitTemplateArgs,
4600 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4601 Args, NumArgs, CandidateSet,
4602 PartialOverloading);
4603 // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4604 // checking dynamically.
4605
4606 if (Callee)
4607 UnqualifiedName = Callee->getDeclName();
4608
4609 if (ArgumentDependentLookup)
4610 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4611 HasExplicitTemplateArgs,
4612 ExplicitTemplateArgs,
4613 NumExplicitTemplateArgs,
4614 CandidateSet,
4615 PartialOverloading);
4616}
4617
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004618/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004619/// (which eventually refers to the declaration Func) and the call
4620/// arguments Args/NumArgs, attempt to resolve the function call down
4621/// to a specific function. If overload resolution succeeds, returns
4622/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004623/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004624/// arguments and Fn, and returns NULL.
Douglas Gregore254f902009-02-04 00:32:51 +00004625FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004626 DeclarationName UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00004627 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00004628 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004629 unsigned NumExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004630 SourceLocation LParenLoc,
4631 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004632 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004633 SourceLocation RParenLoc,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004634 bool &ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004635 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004636
4637 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004638 // functions.
4639 AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4640 HasExplicitTemplateArgs, ExplicitTemplateArgs,
4641 NumExplicitTemplateArgs, Args, NumArgs,
4642 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004643 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004644 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004645 case OR_Success:
4646 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004647
4648 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004649 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004650 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004651 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004652 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4653 break;
4654
4655 case OR_Ambiguous:
4656 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004657 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004658 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4659 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004660
4661 case OR_Deleted:
4662 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4663 << Best->Function->isDeleted()
4664 << UnqualifiedName
4665 << Fn->getSourceRange();
4666 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4667 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004668 }
4669
4670 // Overload resolution failed. Destroy all of the subexpressions and
4671 // return NULL.
4672 Fn->Destroy(Context);
4673 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4674 Args[Arg]->Destroy(Context);
4675 return 0;
4676}
4677
Douglas Gregor084d8552009-03-13 23:49:33 +00004678/// \brief Create a unary operation that may resolve to an overloaded
4679/// operator.
4680///
4681/// \param OpLoc The location of the operator itself (e.g., '*').
4682///
4683/// \param OpcIn The UnaryOperator::Opcode that describes this
4684/// operator.
4685///
4686/// \param Functions The set of non-member functions that will be
4687/// considered by overload resolution. The caller needs to build this
4688/// set based on the context using, e.g.,
4689/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4690/// set should not contain any member functions; those will be added
4691/// by CreateOverloadedUnaryOp().
4692///
4693/// \param input The input argument.
4694Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4695 unsigned OpcIn,
4696 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004697 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004698 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4699 Expr *Input = (Expr *)input.get();
4700
4701 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4702 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4703 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4704
4705 Expr *Args[2] = { Input, 0 };
4706 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004707
Douglas Gregor084d8552009-03-13 23:49:33 +00004708 // For post-increment and post-decrement, add the implicit '0' as
4709 // the second argument, so that we know this is a post-increment or
4710 // post-decrement.
4711 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4712 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004713 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004714 SourceLocation());
4715 NumArgs = 2;
4716 }
4717
4718 if (Input->isTypeDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00004719 OverloadedFunctionDecl *Overloads
Douglas Gregor084d8552009-03-13 23:49:33 +00004720 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004721 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004722 FuncEnd = Functions.end();
4723 Func != FuncEnd; ++Func)
4724 Overloads->addOverload(*Func);
4725
4726 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4727 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004728
Douglas Gregor084d8552009-03-13 23:49:33 +00004729 input.release();
4730 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4731 &Args[0], NumArgs,
4732 Context.DependentTy,
4733 OpLoc));
4734 }
4735
4736 // Build an empty overload set.
4737 OverloadCandidateSet CandidateSet;
4738
4739 // Add the candidates from the given function set.
4740 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4741
4742 // Add operator candidates that are member functions.
4743 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4744
4745 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004746 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00004747
4748 // Perform overload resolution.
4749 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004750 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004751 case OR_Success: {
4752 // We found a built-in operator or an overloaded operator.
4753 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004754
Douglas Gregor084d8552009-03-13 23:49:33 +00004755 if (FnDecl) {
4756 // We matched an overloaded operator. Build a call to that
4757 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004758
Douglas Gregor084d8552009-03-13 23:49:33 +00004759 // Convert the arguments.
4760 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4761 if (PerformObjectArgumentInitialization(Input, Method))
4762 return ExprError();
4763 } else {
4764 // Convert the arguments.
4765 if (PerformCopyInitialization(Input,
4766 FnDecl->getParamDecl(0)->getType(),
4767 "passing"))
4768 return ExprError();
4769 }
4770
4771 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004772 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004773
Douglas Gregor084d8552009-03-13 23:49:33 +00004774 // Build the actual expression node.
4775 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4776 SourceLocation());
4777 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004778
Douglas Gregor084d8552009-03-13 23:49:33 +00004779 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00004780 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004781 ExprOwningPtr<CallExpr> TheCall(this,
4782 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00004783 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004784
4785 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4786 FnDecl))
4787 return ExprError();
4788
4789 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00004790 } else {
4791 // We matched a built-in operator. Convert the arguments, then
4792 // break out so that we will build the appropriate built-in
4793 // operator node.
4794 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4795 Best->Conversions[0], "passing"))
4796 return ExprError();
4797
4798 break;
4799 }
4800 }
4801
4802 case OR_No_Viable_Function:
4803 // No viable function; fall through to handling this as a
4804 // built-in operator, which will produce an error message for us.
4805 break;
4806
4807 case OR_Ambiguous:
4808 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4809 << UnaryOperator::getOpcodeStr(Opc)
4810 << Input->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004811 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4812 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00004813 return ExprError();
4814
4815 case OR_Deleted:
4816 Diag(OpLoc, diag::err_ovl_deleted_oper)
4817 << Best->Function->isDeleted()
4818 << UnaryOperator::getOpcodeStr(Opc)
4819 << Input->getSourceRange();
4820 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4821 return ExprError();
4822 }
4823
4824 // Either we found no viable overloaded operator or we matched a
4825 // built-in operator. In either case, fall through to trying to
4826 // build a built-in operation.
4827 input.release();
4828 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4829}
4830
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004831/// \brief Create a binary operation that may resolve to an overloaded
4832/// operator.
4833///
4834/// \param OpLoc The location of the operator itself (e.g., '+').
4835///
4836/// \param OpcIn The BinaryOperator::Opcode that describes this
4837/// operator.
4838///
4839/// \param Functions The set of non-member functions that will be
4840/// considered by overload resolution. The caller needs to build this
4841/// set based on the context using, e.g.,
4842/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4843/// set should not contain any member functions; those will be added
4844/// by CreateOverloadedBinOp().
4845///
4846/// \param LHS Left-hand argument.
4847/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004848Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004849Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004850 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004851 FunctionSet &Functions,
4852 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004853 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004854 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004855
4856 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4857 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4858 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4859
4860 // If either side is type-dependent, create an appropriate dependent
4861 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004862 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00004863 if (Functions.empty()) {
4864 // If there are no functions to store, just build a dependent
4865 // BinaryOperator or CompoundAssignment.
4866 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4867 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4868 Context.DependentTy, OpLoc));
4869
4870 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4871 Context.DependentTy,
4872 Context.DependentTy,
4873 Context.DependentTy,
4874 OpLoc));
4875 }
4876
Mike Stump11289f42009-09-09 15:08:12 +00004877 OverloadedFunctionDecl *Overloads
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004878 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004879 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004880 FuncEnd = Functions.end();
4881 Func != FuncEnd; ++Func)
4882 Overloads->addOverload(*Func);
4883
4884 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4885 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004886
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004887 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004888 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004889 Context.DependentTy,
4890 OpLoc));
4891 }
4892
4893 // If this is the .* operator, which is not overloadable, just
4894 // create a built-in binary operator.
4895 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004896 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004897
4898 // If this is one of the assignment operators, we only perform
4899 // overload resolution if the left-hand side is a class or
4900 // enumeration type (C++ [expr.ass]p3).
4901 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregore9899d92009-08-26 17:08:25 +00004902 !Args[0]->getType()->isOverloadableType())
4903 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004904
Douglas Gregor084d8552009-03-13 23:49:33 +00004905 // Build an empty overload set.
4906 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004907
4908 // Add the candidates from the given function set.
4909 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4910
4911 // Add operator candidates that are member functions.
4912 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4913
4914 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004915 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004916
4917 // Perform overload resolution.
4918 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004919 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004920 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004921 // We found a built-in operator or an overloaded operator.
4922 FunctionDecl *FnDecl = Best->Function;
4923
4924 if (FnDecl) {
4925 // We matched an overloaded operator. Build a call to that
4926 // operator.
4927
4928 // Convert the arguments.
4929 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004930 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4931 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004932 "passing"))
4933 return ExprError();
4934 } else {
4935 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004936 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004937 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004938 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004939 "passing"))
4940 return ExprError();
4941 }
4942
4943 // Determine the result type
4944 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004945 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004946 ResultTy = ResultTy.getNonReferenceType();
4947
4948 // Build the actual expression node.
4949 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004950 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004951 UsualUnaryConversions(FnExpr);
4952
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00004953 ExprOwningPtr<CXXOperatorCallExpr>
4954 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4955 Args, 2, ResultTy,
4956 OpLoc));
4957
4958 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4959 FnDecl))
4960 return ExprError();
4961
4962 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004963 } else {
4964 // We matched a built-in operator. Convert the arguments, then
4965 // break out so that we will build the appropriate built-in
4966 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004967 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004968 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004969 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004970 Best->Conversions[1], "passing"))
4971 return ExprError();
4972
4973 break;
4974 }
4975 }
4976
Douglas Gregor66950a32009-09-30 21:46:01 +00004977 case OR_No_Viable_Function: {
4978 // C++ [over.match.oper]p9:
4979 // If the operator is the operator , [...] and there are no
4980 // viable functions, then the operator is assumed to be the
4981 // built-in operator and interpreted according to clause 5.
4982 if (Opc == BinaryOperator::Comma)
4983 break;
4984
Sebastian Redl027de2a2009-05-21 11:50:50 +00004985 // For class as left operand for assignment or compound assigment operator
4986 // do not fall through to handling in built-in, but report that no overloaded
4987 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00004988 OwningExprResult Result = ExprError();
4989 if (Args[0]->getType()->isRecordType() &&
4990 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004991 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4992 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004993 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00004994 } else {
4995 // No viable function; try to create a built-in operation, which will
4996 // produce an error. Then, show the non-viable candidates.
4997 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00004998 }
Douglas Gregor66950a32009-09-30 21:46:01 +00004999 assert(Result.isInvalid() &&
5000 "C++ binary operator overloading is missing candidates!");
5001 if (Result.isInvalid())
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005002 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5003 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005004 return move(Result);
5005 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005006
5007 case OR_Ambiguous:
5008 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5009 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005010 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005011 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5012 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005013 return ExprError();
5014
5015 case OR_Deleted:
5016 Diag(OpLoc, diag::err_ovl_deleted_oper)
5017 << Best->Function->isDeleted()
5018 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005019 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005020 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5021 return ExprError();
5022 }
5023
Douglas Gregor66950a32009-09-30 21:46:01 +00005024 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005025 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005026}
5027
Sebastian Redladba46e2009-10-29 20:17:01 +00005028Action::OwningExprResult
5029Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5030 SourceLocation RLoc,
5031 ExprArg Base, ExprArg Idx) {
5032 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5033 static_cast<Expr*>(Idx.get()) };
5034 DeclarationName OpName =
5035 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5036
5037 // If either side is type-dependent, create an appropriate dependent
5038 // expression.
5039 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5040
5041 OverloadedFunctionDecl *Overloads
5042 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
5043
5044 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
5045 LLoc, false, false);
5046
5047 Base.release();
5048 Idx.release();
5049 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5050 Args, 2,
5051 Context.DependentTy,
5052 RLoc));
5053 }
5054
5055 // Build an empty overload set.
5056 OverloadCandidateSet CandidateSet;
5057
5058 // Subscript can only be overloaded as a member function.
5059
5060 // Add operator candidates that are member functions.
5061 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5062
5063 // Add builtin operator candidates.
5064 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5065
5066 // Perform overload resolution.
5067 OverloadCandidateSet::iterator Best;
5068 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5069 case OR_Success: {
5070 // We found a built-in operator or an overloaded operator.
5071 FunctionDecl *FnDecl = Best->Function;
5072
5073 if (FnDecl) {
5074 // We matched an overloaded operator. Build a call to that
5075 // operator.
5076
5077 // Convert the arguments.
5078 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5079 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5080 PerformCopyInitialization(Args[1],
5081 FnDecl->getParamDecl(0)->getType(),
5082 "passing"))
5083 return ExprError();
5084
5085 // Determine the result type
5086 QualType ResultTy
5087 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5088 ResultTy = ResultTy.getNonReferenceType();
5089
5090 // Build the actual expression node.
5091 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5092 LLoc);
5093 UsualUnaryConversions(FnExpr);
5094
5095 Base.release();
5096 Idx.release();
5097 ExprOwningPtr<CXXOperatorCallExpr>
5098 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5099 FnExpr, Args, 2,
5100 ResultTy, RLoc));
5101
5102 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5103 FnDecl))
5104 return ExprError();
5105
5106 return MaybeBindToTemporary(TheCall.release());
5107 } else {
5108 // We matched a built-in operator. Convert the arguments, then
5109 // break out so that we will build the appropriate built-in
5110 // operator node.
5111 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5112 Best->Conversions[0], "passing") ||
5113 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5114 Best->Conversions[1], "passing"))
5115 return ExprError();
5116
5117 break;
5118 }
5119 }
5120
5121 case OR_No_Viable_Function: {
5122 // No viable function; try to create a built-in operation, which will
5123 // produce an error. Then, show the non-viable candidates.
5124 OwningExprResult Result =
5125 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5126 assert(Result.isInvalid() &&
5127 "C++ subscript operator overloading is missing candidates!");
5128 if (Result.isInvalid())
5129 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5130 "[]", LLoc);
5131 return move(Result);
5132 }
5133
5134 case OR_Ambiguous:
5135 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5136 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5137 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5138 "[]", LLoc);
5139 return ExprError();
5140
5141 case OR_Deleted:
5142 Diag(LLoc, diag::err_ovl_deleted_oper)
5143 << Best->Function->isDeleted() << "[]"
5144 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5145 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5146 return ExprError();
5147 }
5148
5149 // We matched a built-in operator; build it.
5150 Base.release();
5151 Idx.release();
5152 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5153 Owned(Args[1]), RLoc);
5154}
5155
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005156/// BuildCallToMemberFunction - Build a call to a member
5157/// function. MemExpr is the expression that refers to the member
5158/// function (and includes the object parameter), Args/NumArgs are the
5159/// arguments to the function call (not including the object
5160/// parameter). The caller needs to validate that the member
5161/// expression refers to a member function or an overloaded member
5162/// function.
5163Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005164Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5165 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005166 unsigned NumArgs, SourceLocation *CommaLocs,
5167 SourceLocation RParenLoc) {
5168 // Dig out the member expression. This holds both the object
5169 // argument and the member function we're referring to.
5170 MemberExpr *MemExpr = 0;
5171 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
5172 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
5173 else
5174 MemExpr = dyn_cast<MemberExpr>(MemExprE);
5175 assert(MemExpr && "Building member call without member expression");
5176
5177 // Extract the object argument.
5178 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005179
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005180 CXXMethodDecl *Method = 0;
Douglas Gregor97628d62009-08-21 00:16:32 +00005181 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
5182 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005183 // Add overload candidates
5184 OverloadCandidateSet CandidateSet;
Douglas Gregor97628d62009-08-21 00:16:32 +00005185 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005186
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005187 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
5188 Func != FuncEnd; ++Func) {
Douglas Gregord3319842009-10-24 04:59:53 +00005189 if ((Method = dyn_cast<CXXMethodDecl>(*Func))) {
5190 // If explicit template arguments were provided, we can't call a
5191 // non-template member function.
5192 if (MemExpr->hasExplicitTemplateArgumentList())
5193 continue;
5194
Mike Stump11289f42009-09-09 15:08:12 +00005195 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005196 /*SuppressUserConversions=*/false);
Douglas Gregord3319842009-10-24 04:59:53 +00005197 } else
Douglas Gregor84f14dd2009-09-01 00:37:14 +00005198 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
5199 MemExpr->hasExplicitTemplateArgumentList(),
5200 MemExpr->getTemplateArgs(),
5201 MemExpr->getNumTemplateArgs(),
5202 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005203 CandidateSet,
5204 /*SuppressUsedConversions=*/false);
5205 }
Mike Stump11289f42009-09-09 15:08:12 +00005206
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005207 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005208 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005209 case OR_Success:
5210 Method = cast<CXXMethodDecl>(Best->Function);
5211 break;
5212
5213 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005214 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005215 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005216 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005217 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5218 // FIXME: Leaking incoming expressions!
5219 return true;
5220
5221 case OR_Ambiguous:
Mike Stump11289f42009-09-09 15:08:12 +00005222 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005223 diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005224 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005225 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5226 // FIXME: Leaking incoming expressions!
5227 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005228
5229 case OR_Deleted:
Mike Stump11289f42009-09-09 15:08:12 +00005230 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00005231 diag::err_ovl_deleted_member_call)
5232 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005233 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005234 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5235 // FIXME: Leaking incoming expressions!
5236 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005237 }
5238
5239 FixOverloadedFunctionReference(MemExpr, Method);
5240 } else {
5241 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5242 }
5243
5244 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005245 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005246 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005247 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005248 Method->getResultType().getNonReferenceType(),
5249 RParenLoc));
5250
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005251 // Check for a valid return type.
5252 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5253 TheCall.get(), Method))
5254 return true;
5255
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005256 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00005257 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005258 PerformObjectArgumentInitialization(ObjectArg, Method))
5259 return true;
5260 MemExpr->setBase(ObjectArg);
5261
5262 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005263 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005264 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005265 RParenLoc))
5266 return true;
5267
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005268 if (CheckFunctionCall(Method, TheCall.get()))
5269 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00005270
5271 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005272}
5273
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005274/// BuildCallToObjectOfClassType - Build a call to an object of class
5275/// type (C++ [over.call.object]), which can end up invoking an
5276/// overloaded function call operator (@c operator()) or performing a
5277/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005278Sema::ExprResult
5279Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005280 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005281 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005282 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005283 SourceLocation RParenLoc) {
5284 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005285 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005286
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005287 // C++ [over.call.object]p1:
5288 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005289 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005290 // candidate functions includes at least the function call
5291 // operators of T. The function call operators of T are obtained by
5292 // ordinary lookup of the name operator() in the context of
5293 // (E).operator().
5294 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005295 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005296
5297 if (RequireCompleteType(LParenLoc, Object->getType(),
5298 PartialDiagnostic(diag::err_incomplete_object_call)
5299 << Object->getSourceRange()))
5300 return true;
5301
John McCall27b18f82009-11-17 02:14:36 +00005302 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5303 LookupQualifiedName(R, Record->getDecl());
5304 R.suppressDiagnostics();
5305
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005306 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00005307 Oper != OperEnd; ++Oper) {
John McCallf0f1cf02009-11-17 07:50:12 +00005308 AddMethodCandidate(*Oper, Object, Args, NumArgs, CandidateSet,
5309 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005310 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005311
Douglas Gregorab7897a2008-11-19 22:57:39 +00005312 // C++ [over.call.object]p2:
5313 // In addition, for each conversion function declared in T of the
5314 // form
5315 //
5316 // operator conversion-type-id () cv-qualifier;
5317 //
5318 // where cv-qualifier is the same cv-qualification as, or a
5319 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005320 // denotes the type "pointer to function of (P1,...,Pn) returning
5321 // R", or the type "reference to pointer to function of
5322 // (P1,...,Pn) returning R", or the type "reference to function
5323 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005324 // is also considered as a candidate function. Similarly,
5325 // surrogate call functions are added to the set of candidate
5326 // functions for each conversion function declared in an
5327 // accessible base class provided the function is not hidden
5328 // within T by another intervening declaration.
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005329 // FIXME: Look in base classes for more conversion operators!
5330 OverloadedFunctionDecl *Conversions
5331 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
5332 for (OverloadedFunctionDecl::function_iterator
5333 Func = Conversions->function_begin(),
5334 FuncEnd = Conversions->function_end();
5335 Func != FuncEnd; ++Func) {
5336 CXXConversionDecl *Conv;
5337 FunctionTemplateDecl *ConvTemplate;
5338 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Mike Stump11289f42009-09-09 15:08:12 +00005339
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005340 // Skip over templated conversion functions; they aren't
5341 // surrogates.
5342 if (ConvTemplate)
5343 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005344
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005345 // Strip the reference type (if any) and then the pointer type (if
5346 // any) to get down to what might be a function type.
5347 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5348 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5349 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005350
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005351 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
5352 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005353 }
Mike Stump11289f42009-09-09 15:08:12 +00005354
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005355 // Perform overload resolution.
5356 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005357 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005358 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005359 // Overload resolution succeeded; we'll build the appropriate call
5360 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005361 break;
5362
5363 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005364 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00005365 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00005366 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00005367 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005368 break;
5369
5370 case OR_Ambiguous:
5371 Diag(Object->getSourceRange().getBegin(),
5372 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005373 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005374 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5375 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005376
5377 case OR_Deleted:
5378 Diag(Object->getSourceRange().getBegin(),
5379 diag::err_ovl_deleted_object_call)
5380 << Best->Function->isDeleted()
5381 << Object->getType() << Object->getSourceRange();
5382 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5383 break;
Mike Stump11289f42009-09-09 15:08:12 +00005384 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005385
Douglas Gregorab7897a2008-11-19 22:57:39 +00005386 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005387 // We had an error; delete all of the subexpressions and return
5388 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005389 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005390 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005391 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005392 return true;
5393 }
5394
Douglas Gregorab7897a2008-11-19 22:57:39 +00005395 if (Best->Function == 0) {
5396 // Since there is no function declaration, this is one of the
5397 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00005398 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00005399 = cast<CXXConversionDecl>(
5400 Best->Conversions[0].UserDefined.ConversionFunction);
5401
5402 // We selected one of the surrogate functions that converts the
5403 // object parameter to a function pointer. Perform the conversion
5404 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005405
5406 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005407 // and then call it.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005408 CXXMemberCallExpr *CE =
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005409 BuildCXXMemberCallExpr(Object, Conv);
5410
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005411 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005412 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5413 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005414 }
5415
5416 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5417 // that calls this method, using Object for the implicit object
5418 // parameter and passing along the remaining arguments.
5419 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00005420 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005421
5422 unsigned NumArgsInProto = Proto->getNumArgs();
5423 unsigned NumArgsToCheck = NumArgs;
5424
5425 // Build the full argument list for the method call (the
5426 // implicit object parameter is placed at the beginning of the
5427 // list).
5428 Expr **MethodArgs;
5429 if (NumArgs < NumArgsInProto) {
5430 NumArgsToCheck = NumArgsInProto;
5431 MethodArgs = new Expr*[NumArgsInProto + 1];
5432 } else {
5433 MethodArgs = new Expr*[NumArgs + 1];
5434 }
5435 MethodArgs[0] = Object;
5436 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5437 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00005438
5439 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00005440 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005441 UsualUnaryConversions(NewFn);
5442
5443 // Once we've built TheCall, all of the expressions are properly
5444 // owned.
5445 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005446 ExprOwningPtr<CXXOperatorCallExpr>
5447 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005448 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005449 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005450 delete [] MethodArgs;
5451
Anders Carlsson3d5829c2009-10-13 21:49:31 +00005452 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5453 Method))
5454 return true;
5455
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005456 // We may have default arguments. If so, we need to allocate more
5457 // slots in the call for them.
5458 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005459 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005460 else if (NumArgs > NumArgsInProto)
5461 NumArgsToCheck = NumArgsInProto;
5462
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005463 bool IsError = false;
5464
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005465 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005466 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005467 TheCall->setArg(0, Object);
5468
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005469
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005470 // Check the argument types.
5471 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005472 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005473 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005474 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00005475
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005476 // Pass the argument.
5477 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005478 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005479 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00005480 OwningExprResult DefArg
5481 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5482 if (DefArg.isInvalid()) {
5483 IsError = true;
5484 break;
5485 }
5486
5487 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005488 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005489
5490 TheCall->setArg(i + 1, Arg);
5491 }
5492
5493 // If this is a variadic call, handle args passed through "...".
5494 if (Proto->isVariadic()) {
5495 // Promote the arguments (C99 6.5.2.2p7).
5496 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5497 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005498 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005499 TheCall->setArg(i + 1, Arg);
5500 }
5501 }
5502
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005503 if (IsError) return true;
5504
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005505 if (CheckFunctionCall(Method, TheCall.get()))
5506 return true;
5507
Anders Carlsson1c83deb2009-08-16 03:53:54 +00005508 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005509}
5510
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005511/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00005512/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005513/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00005514Sema::OwningExprResult
5515Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5516 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005517 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00005518
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005519 // C++ [over.ref]p1:
5520 //
5521 // [...] An expression x->m is interpreted as (x.operator->())->m
5522 // for a class object x of type T if T::operator->() exists and if
5523 // the operator is selected as the best match function by the
5524 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005525 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5526 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005527 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00005528
Eli Friedman132e70b2009-11-18 01:28:03 +00005529 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5530 PDiag(diag::err_typecheck_incomplete_tag)
5531 << Base->getSourceRange()))
5532 return ExprError();
5533
John McCall27b18f82009-11-17 02:14:36 +00005534 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5535 LookupQualifiedName(R, BaseRecord->getDecl());
5536 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00005537
5538 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5539 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00005540 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005541 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005542
5543 // Perform overload resolution.
5544 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005545 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005546 case OR_Success:
5547 // Overload resolution succeeded; we'll build the call below.
5548 break;
5549
5550 case OR_No_Viable_Function:
5551 if (CandidateSet.empty())
5552 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00005553 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005554 else
5555 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00005556 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005557 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00005558 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005559
5560 case OR_Ambiguous:
5561 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005562 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005563 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005564 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005565
5566 case OR_Deleted:
5567 Diag(OpLoc, diag::err_ovl_deleted_oper)
5568 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005569 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005570 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005571 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005572 }
5573
5574 // Convert the object parameter.
5575 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005576 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005577 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005578
5579 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005580 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005581
5582 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005583 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5584 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005585 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005586
5587 QualType ResultTy = Method->getResultType().getNonReferenceType();
5588 ExprOwningPtr<CXXOperatorCallExpr>
5589 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5590 &Base, 1, ResultTy, OpLoc));
5591
5592 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5593 Method))
5594 return ExprError();
5595 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005596}
5597
Douglas Gregorcd695e52008-11-10 20:40:00 +00005598/// FixOverloadedFunctionReference - E is an expression that refers to
5599/// a C++ overloaded function (possibly with some parentheses and
5600/// perhaps a '&' around it). We have resolved the overloaded function
5601/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005602/// refer (possibly indirectly) to Fn. Returns the new expr.
5603Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005604 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005605 Expr *NewExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00005606 PE->setSubExpr(NewExpr);
5607 PE->setType(NewExpr->getType());
5608 } else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5609 Expr *NewExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
5610 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
5611 NewExpr->getType()) &&
5612 "Implicit cast type cannot be determined from overload");
5613 ICE->setSubExpr(NewExpr);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005614 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005615 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005616 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005617 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5618 if (Method->isStatic()) {
5619 // Do nothing: static member functions aren't any different
5620 // from non-member functions.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005621 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr())) {
5622 if (DRE->getQualifier()) {
5623 // We have taken the address of a pointer to member
5624 // function. Perform the computation here so that we get the
5625 // appropriate pointer to member type.
5626 DRE->setDecl(Fn);
5627 DRE->setType(Fn->getType());
5628 QualType ClassType
5629 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5630 E->setType(Context.getMemberPointerType(Fn->getType(),
5631 ClassType.getTypePtr()));
5632 return E;
5633 }
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005634 }
Douglas Gregor6a573fe2009-10-22 18:02:20 +00005635 // FIXME: TemplateIdRefExpr referring to a member function template
5636 // specialization!
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005637 }
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005638 Expr *NewExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5639 UnOp->setSubExpr(NewExpr);
5640 UnOp->setType(Context.getPointerType(NewExpr->getType()));
5641
5642 return UnOp;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005643 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor9b146582009-07-08 20:55:45 +00005644 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Douglas Gregor091f0422009-10-23 22:18:25 +00005645 isa<FunctionTemplateDecl>(DR->getDecl()) ||
5646 isa<FunctionDecl>(DR->getDecl())) &&
5647 "Expected function or function template");
Douglas Gregorcd695e52008-11-10 20:40:00 +00005648 DR->setDecl(Fn);
5649 E->setType(Fn->getType());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005650 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5651 MemExpr->setMemberDecl(Fn);
5652 E->setType(Fn->getType());
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005653 } else if (TemplateIdRefExpr *TID = dyn_cast<TemplateIdRefExpr>(E)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005654 E = DeclRefExpr::Create(Context,
5655 TID->getQualifier(), TID->getQualifierRange(),
5656 Fn, TID->getTemplateNameLoc(),
5657 true,
5658 TID->getLAngleLoc(),
5659 TID->getTemplateArgs(),
5660 TID->getNumTemplateArgs(),
5661 TID->getRAngleLoc(),
5662 Fn->getType(),
5663 /*FIXME?*/false, /*FIXME?*/false);
Douglas Gregor6a573fe2009-10-22 18:02:20 +00005664
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005665 // FIXME: Don't destroy TID here, since we need its template arguments
5666 // to survive.
5667 // TID->Destroy(Context);
Douglas Gregor091f0422009-10-23 22:18:25 +00005668 } else if (isa<UnresolvedFunctionNameExpr>(E)) {
5669 return DeclRefExpr::Create(Context,
5670 /*Qualifier=*/0,
5671 /*QualifierRange=*/SourceRange(),
5672 Fn, E->getLocStart(),
5673 Fn->getType(), false, false);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005674 } else {
5675 assert(false && "Invalid reference to overloaded function");
5676 }
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005677
5678 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005679}
5680
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005681} // end namespace clang