blob: 9d0958c46e1c1454a60cc2cbcc3c06744b5b4617 [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 Gregor0a70c4d2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000027#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,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000042 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000043 ICC_Qualification_Adjustment,
44 ICC_Promotion,
45 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000046 ICC_Promotion,
47 ICC_Conversion,
48 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000049 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
53 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000054 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000055 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000056 ICC_Conversion
57 };
58 return Category[(int)Kind];
59}
60
61/// GetConversionRank - Retrieve the implicit conversion rank
62/// corresponding to the given implicit conversion kind.
63ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
64 static const ImplicitConversionRank
65 Rank[(int)ICK_Num_Conversion_Kinds] = {
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
70 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000071 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000072 ICR_Promotion,
73 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000074 ICR_Promotion,
75 ICR_Conversion,
76 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000077 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
81 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000082 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000083 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084 ICR_Conversion
85 };
86 return Rank[(int)Kind];
87}
88
89/// GetImplicitConversionName - Return the name of this kind of
90/// implicit conversion.
91const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +000092 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000093 "No conversion",
94 "Lvalue-to-rvalue",
95 "Array-to-pointer",
96 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000097 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000098 "Qualification",
99 "Integral promotion",
100 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000101 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000102 "Integral conversion",
103 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000104 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000105 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000106 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000107 "Pointer conversion",
108 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000109 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000110 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000111 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000112 };
113 return Name[Kind];
114}
115
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000116/// StandardConversionSequence - Set the standard conversion
117/// sequence to the identity conversion.
118void StandardConversionSequence::setAsIdentityConversion() {
119 First = ICK_Identity;
120 Second = ICK_Identity;
121 Third = ICK_Identity;
122 Deprecated = false;
123 ReferenceBinding = false;
124 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000125 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000126 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000127}
128
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000129/// getRank - Retrieve the rank of this standard conversion sequence
130/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
131/// implicit conversions.
132ImplicitConversionRank StandardConversionSequence::getRank() const {
133 ImplicitConversionRank Rank = ICR_Exact_Match;
134 if (GetConversionRank(First) > Rank)
135 Rank = GetConversionRank(First);
136 if (GetConversionRank(Second) > Rank)
137 Rank = GetConversionRank(Second);
138 if (GetConversionRank(Third) > Rank)
139 Rank = GetConversionRank(Third);
140 return Rank;
141}
142
143/// isPointerConversionToBool - Determines whether this conversion is
144/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000145/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000146/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000147bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000148 // 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.
John McCall0d1da222010-01-12 00:44:57 +0000152 if (getToType()->isBooleanType() &&
153 (getFromType()->isPointerType() || getFromType()->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 {
John McCall0d1da222010-01-12 00:44:57 +0000167 QualType FromType = getFromType();
168 QualType ToType = getToType();
Douglas Gregor5c407d92008-10-23 00:40:37 +0000169
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
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000176 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
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;
John McCall0d1da222010-01-12 00:44:57 +0000250 case AmbiguousConversion:
251 fprintf(stderr, "Ambiguous conversion");
252 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000253 case BadConversion:
254 fprintf(stderr, "Bad conversion");
255 break;
256 }
257
258 fprintf(stderr, "\n");
259}
260
John McCall0d1da222010-01-12 00:44:57 +0000261void AmbiguousConversionSequence::construct() {
262 new (&conversions()) ConversionSet();
263}
264
265void AmbiguousConversionSequence::destruct() {
266 conversions().~ConversionSet();
267}
268
269void
270AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
271 FromTypePtr = O.FromTypePtr;
272 ToTypePtr = O.ToTypePtr;
273 new (&conversions()) ConversionSet(O.conversions());
274}
275
276
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000277// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000278// overload of the declarations in Old. This routine returns false if
279// New and Old cannot be overloaded, e.g., if New has the same
280// signature as some function in Old (C++ 1.3.10) or if the Old
281// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000282// it does return false, MatchedDecl will point to the decl that New
283// cannot be overloaded with. This decl may be a UsingShadowDecl on
284// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000285//
286// Example: Given the following input:
287//
288// void f(int, float); // #1
289// void f(int, int); // #2
290// int f(int, int); // #3
291//
292// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000293// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000294//
John McCall3d988d92009-12-02 08:47:38 +0000295// When we process #2, Old contains only the FunctionDecl for #1. By
296// comparing the parameter types, we see that #1 and #2 are overloaded
297// (since they have different signatures), so this routine returns
298// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000299//
John McCall3d988d92009-12-02 08:47:38 +0000300// When we process #3, Old is an overload set containing #1 and #2. We
301// compare the signatures of #3 to #1 (they're overloaded, so we do
302// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
303// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000304// signature), IsOverload returns false and MatchedDecl will be set to
305// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000306Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000307Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
308 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000309 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000310 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000311 NamedDecl *OldD = (*I)->getUnderlyingDecl();
312 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000313 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000314 Match = *I;
315 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000316 }
John McCall3d988d92009-12-02 08:47:38 +0000317 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000318 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000319 Match = *I;
320 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000321 }
John McCall84d87672009-12-10 09:41:52 +0000322 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
323 // We can overload with these, which can show up when doing
324 // redeclaration checks for UsingDecls.
325 assert(Old.getLookupKind() == LookupUsingDeclName);
326 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
327 // Optimistically assume that an unresolved using decl will
328 // overload; if it doesn't, we'll have to diagnose during
329 // template instantiation.
330 } else {
John McCall1f82f242009-11-18 22:49:29 +0000331 // (C++ 13p1):
332 // Only function declarations can be overloaded; object and type
333 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000334 Match = *I;
335 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000336 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000337 }
John McCall1f82f242009-11-18 22:49:29 +0000338
John McCalldaa3d6b2009-12-09 03:35:25 +0000339 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000340}
341
342bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
343 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
344 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
345
346 // C++ [temp.fct]p2:
347 // A function template can be overloaded with other function templates
348 // and with normal (non-template) functions.
349 if ((OldTemplate == 0) != (NewTemplate == 0))
350 return true;
351
352 // Is the function New an overload of the function Old?
353 QualType OldQType = Context.getCanonicalType(Old->getType());
354 QualType NewQType = Context.getCanonicalType(New->getType());
355
356 // Compare the signatures (C++ 1.3.10) of the two functions to
357 // determine whether they are overloads. If we find any mismatch
358 // in the signature, they are overloads.
359
360 // If either of these functions is a K&R-style function (no
361 // prototype), then we consider them to have matching signatures.
362 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
363 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
364 return false;
365
366 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
367 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
368
369 // The signature of a function includes the types of its
370 // parameters (C++ 1.3.10), which includes the presence or absence
371 // of the ellipsis; see C++ DR 357).
372 if (OldQType != NewQType &&
373 (OldType->getNumArgs() != NewType->getNumArgs() ||
374 OldType->isVariadic() != NewType->isVariadic() ||
375 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
376 NewType->arg_type_begin())))
377 return true;
378
379 // C++ [temp.over.link]p4:
380 // The signature of a function template consists of its function
381 // signature, its return type and its template parameter list. The names
382 // of the template parameters are significant only for establishing the
383 // relationship between the template parameters and the rest of the
384 // signature.
385 //
386 // We check the return type and template parameter lists for function
387 // templates first; the remaining checks follow.
388 if (NewTemplate &&
389 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
390 OldTemplate->getTemplateParameters(),
391 false, TPL_TemplateMatch) ||
392 OldType->getResultType() != NewType->getResultType()))
393 return true;
394
395 // If the function is a class member, its signature includes the
396 // cv-qualifiers (if any) on the function itself.
397 //
398 // As part of this, also check whether one of the member functions
399 // is static, in which case they are not overloads (C++
400 // 13.1p2). While not part of the definition of the signature,
401 // this check is important to determine whether these functions
402 // can be overloaded.
403 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
404 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
405 if (OldMethod && NewMethod &&
406 !OldMethod->isStatic() && !NewMethod->isStatic() &&
407 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
408 return true;
409
410 // The signatures match; this is not an overload.
411 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000412}
413
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000414/// TryImplicitConversion - Attempt to perform an implicit conversion
415/// from the given expression (Expr) to the given type (ToType). This
416/// function returns an implicit conversion sequence that can be used
417/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000418///
419/// void f(float f);
420/// void g(int i) { f(i); }
421///
422/// this routine would produce an implicit conversion sequence to
423/// describe the initialization of f from i, which will be a standard
424/// conversion sequence containing an lvalue-to-rvalue conversion (C++
425/// 4.1) followed by a floating-integral conversion (C++ 4.9).
426//
427/// Note that this routine only determines how the conversion can be
428/// performed; it does not actually perform the conversion. As such,
429/// it will not produce any diagnostics if no conversion is available,
430/// but will instead return an implicit conversion sequence of kind
431/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000432///
433/// If @p SuppressUserConversions, then user-defined conversions are
434/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000435/// If @p AllowExplicit, then explicit user-defined conversions are
436/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000437/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
438/// no matter its actual lvalueness.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000439/// If @p UserCast, the implicit conversion is being done for a user-specified
440/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000441ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000442Sema::TryImplicitConversion(Expr* From, QualType ToType,
443 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000444 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000445 bool InOverloadResolution,
446 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000447 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000448 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000449 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000450 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
John McCall0d1da222010-01-12 00:44:57 +0000451 ICS.setStandard();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000452 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000453 (UserDefResult = IsUserDefinedConversion(From, ToType,
454 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000455 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000456 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000457 ForceRValue, UserCast)) == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000458 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000459 // C++ [over.ics.user]p4:
460 // A conversion of an expression of class type to the same class
461 // type is given Exact Match rank, and a conversion of an
462 // expression of class type to a base class of that type is
463 // given Conversion rank, in spite of the fact that a copy
464 // constructor (i.e., a user-defined conversion function) is
465 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000466 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000467 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000468 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000469 = Context.getCanonicalType(From->getType().getUnqualifiedType());
470 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000471 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000472 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000473 // Turn this into a "standard" conversion sequence, so that it
474 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000475 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000476 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000477 ICS.Standard.setFromType(From->getType());
478 ICS.Standard.setToType(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000479 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000480 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000481 ICS.Standard.Second = ICK_Derived_To_Base;
482 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000483 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000484
485 // C++ [over.best.ics]p4:
486 // However, when considering the argument of a user-defined
487 // conversion function that is a candidate by 13.3.1.3 when
488 // invoked for the copying of the temporary in the second step
489 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
490 // 13.3.1.6 in all cases, only standard conversion sequences and
491 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000492 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall0d1da222010-01-12 00:44:57 +0000493 ICS.setBad();
John McCall6a61b522010-01-13 09:16:55 +0000494 ICS.Bad.init(BadConversionSequence::suppressed_user, From, ToType);
495 }
John McCalle8c8cd22010-01-13 22:30:33 +0000496 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000497 ICS.setAmbiguous();
498 ICS.Ambiguous.setFromType(From->getType());
499 ICS.Ambiguous.setToType(ToType);
500 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
501 Cand != Conversions.end(); ++Cand)
502 if (Cand->Viable)
503 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000504 } else {
John McCall0d1da222010-01-12 00:44:57 +0000505 ICS.setBad();
John McCall6a61b522010-01-13 09:16:55 +0000506 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000507 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000508
509 return ICS;
510}
511
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000512/// \brief Determine whether the conversion from FromType to ToType is a valid
513/// conversion that strips "noreturn" off the nested function type.
514static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
515 QualType ToType, QualType &ResultTy) {
516 if (Context.hasSameUnqualifiedType(FromType, ToType))
517 return false;
518
519 // Strip the noreturn off the type we're converting from; noreturn can
520 // safely be removed.
521 FromType = Context.getNoReturnType(FromType, false);
522 if (!Context.hasSameUnqualifiedType(FromType, ToType))
523 return false;
524
525 ResultTy = FromType;
526 return true;
527}
528
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000529/// IsStandardConversion - Determines whether there is a standard
530/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
531/// expression From to the type ToType. Standard conversion sequences
532/// only consider non-class types; for conversions that involve class
533/// types, use TryImplicitConversion. If a conversion exists, SCS will
534/// contain the standard conversion sequence required to perform this
535/// conversion and this routine will return true. Otherwise, this
536/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000537bool
538Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000539 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000540 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000541 QualType FromType = From->getType();
542
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000543 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000544 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000545 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000546 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000547 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000548 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000549
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000550 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000551 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000552 if (FromType->isRecordType() || ToType->isRecordType()) {
553 if (getLangOptions().CPlusPlus)
554 return false;
555
Mike Stump11289f42009-09-09 15:08:12 +0000556 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000557 }
558
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000559 // The first conversion can be an lvalue-to-rvalue conversion,
560 // array-to-pointer conversion, or function-to-pointer conversion
561 // (C++ 4p1).
562
Mike Stump11289f42009-09-09 15:08:12 +0000563 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000564 // An lvalue (3.10) of a non-function, non-array type T can be
565 // converted to an rvalue.
566 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000567 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000568 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000569 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000570 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000571
572 // If T is a non-class type, the type of the rvalue is the
573 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000574 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
575 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000576 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000577 } else if (FromType->isArrayType()) {
578 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000579 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000580
581 // An lvalue or rvalue of type "array of N T" or "array of unknown
582 // bound of T" can be converted to an rvalue of type "pointer to
583 // T" (C++ 4.2p1).
584 FromType = Context.getArrayDecayedType(FromType);
585
586 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
587 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000588 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000589
590 // For the purpose of ranking in overload resolution
591 // (13.3.3.1.1), this conversion is considered an
592 // array-to-pointer conversion followed by a qualification
593 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000594 SCS.Second = ICK_Identity;
595 SCS.Third = ICK_Qualification;
John McCall0d1da222010-01-12 00:44:57 +0000596 SCS.setToType(ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000597 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000598 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000599 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
600 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000601 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000602
603 // An lvalue of function type T can be converted to an rvalue of
604 // type "pointer to T." The result is a pointer to the
605 // function. (C++ 4.3p1).
606 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000607 } else if (FunctionDecl *Fn
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000608 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000609 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000610 SCS.First = ICK_Function_To_Pointer;
611
612 // We were able to resolve the address of the overloaded function,
613 // so we can convert to the type of that function.
614 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000615 if (ToType->isLValueReferenceType())
616 FromType = Context.getLValueReferenceType(FromType);
617 else if (ToType->isRValueReferenceType())
618 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000619 else if (ToType->isMemberPointerType()) {
620 // Resolve address only succeeds if both sides are member pointers,
621 // but it doesn't have to be the same class. See DR 247.
622 // Note that this means that the type of &Derived::fn can be
623 // Ret (Base::*)(Args) if the fn overload actually found is from the
624 // base class, even if it was brought into the derived class via a
625 // using declaration. The standard isn't clear on this issue at all.
626 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
627 FromType = Context.getMemberPointerType(FromType,
628 Context.getTypeDeclType(M->getParent()).getTypePtr());
629 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000630 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000631 } else {
632 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000633 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000634 }
635
636 // The second conversion can be an integral promotion, floating
637 // point promotion, integral conversion, floating point conversion,
638 // floating-integral conversion, pointer conversion,
639 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000640 // For overloading in C, this can also be a "compatible-type"
641 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000642 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000643 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000644 // The unqualified versions of the types are the same: there's no
645 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000646 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000647 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000648 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000649 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000650 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000651 } else if (IsFloatingPointPromotion(FromType, ToType)) {
652 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000653 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000654 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000655 } else if (IsComplexPromotion(FromType, ToType)) {
656 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000657 SCS.Second = ICK_Complex_Promotion;
658 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000659 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000660 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000661 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000662 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000663 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000664 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
665 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000666 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000667 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000668 } else if (FromType->isComplexType() && ToType->isComplexType()) {
669 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000670 SCS.Second = ICK_Complex_Conversion;
671 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000672 } else if ((FromType->isFloatingType() &&
673 ToType->isIntegralType() && (!ToType->isBooleanType() &&
674 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000675 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000676 ToType->isFloatingType())) {
677 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000678 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000679 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000680 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
681 (ToType->isComplexType() && FromType->isArithmeticType())) {
682 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000683 SCS.Second = ICK_Complex_Real;
684 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000685 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
686 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000687 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000688 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000689 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000690 } else if (IsMemberPointerConversion(From, FromType, ToType,
691 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000692 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000693 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000694 } else if (ToType->isBooleanType() &&
695 (FromType->isArithmeticType() ||
696 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000697 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000698 FromType->isBlockPointerType() ||
699 FromType->isMemberPointerType() ||
700 FromType->isNullPtrType())) {
701 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000702 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000703 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000704 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000705 Context.typesAreCompatible(ToType, FromType)) {
706 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000707 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000708 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
709 // Treat a conversion that strips "noreturn" as an identity conversion.
710 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000711 } else {
712 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000713 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000714 }
715
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000716 QualType CanonFrom;
717 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000718 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000719 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000720 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000721 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000722 CanonFrom = Context.getCanonicalType(FromType);
723 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000724 } else {
725 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000726 SCS.Third = ICK_Identity;
727
Mike Stump11289f42009-09-09 15:08:12 +0000728 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000729 // [...] Any difference in top-level cv-qualification is
730 // subsumed by the initialization itself and does not constitute
731 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000732 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000733 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000734 if (CanonFrom.getLocalUnqualifiedType()
735 == CanonTo.getLocalUnqualifiedType() &&
736 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000737 FromType = ToType;
738 CanonFrom = CanonTo;
739 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000740 }
741
742 // If we have not converted the argument type to the parameter type,
743 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000744 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000745 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000746
John McCall0d1da222010-01-12 00:44:57 +0000747 SCS.setToType(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000748 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000749}
750
751/// IsIntegralPromotion - Determines whether the conversion from the
752/// expression From (whose potentially-adjusted type is FromType) to
753/// ToType is an integral promotion (C++ 4.5). If so, returns true and
754/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000755bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000756 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000757 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000758 if (!To) {
759 return false;
760 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000761
762 // An rvalue of type char, signed char, unsigned char, short int, or
763 // unsigned short int can be converted to an rvalue of type int if
764 // int can represent all the values of the source type; otherwise,
765 // the source rvalue can be converted to an rvalue of type unsigned
766 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000767 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000768 if (// We can promote any signed, promotable integer type to an int
769 (FromType->isSignedIntegerType() ||
770 // We can promote any unsigned integer type whose size is
771 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000772 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000773 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000774 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000775 }
776
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000777 return To->getKind() == BuiltinType::UInt;
778 }
779
780 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
781 // can be converted to an rvalue of the first of the following types
782 // that can represent all the values of its underlying type: int,
783 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000784
785 // We pre-calculate the promotion type for enum types.
786 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
787 if (ToType->isIntegerType())
788 return Context.hasSameUnqualifiedType(ToType,
789 FromEnumType->getDecl()->getPromotionType());
790
791 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000792 // Determine whether the type we're converting from is signed or
793 // unsigned.
794 bool FromIsSigned;
795 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000796
797 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
798 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000799
800 // The types we'll try to promote to, in the appropriate
801 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000802 QualType PromoteTypes[6] = {
803 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000804 Context.LongTy, Context.UnsignedLongTy ,
805 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000806 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000807 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000808 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
809 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000810 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000811 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
812 // We found the type that we can promote to. If this is the
813 // type we wanted, we have a promotion. Otherwise, no
814 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000815 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816 }
817 }
818 }
819
820 // An rvalue for an integral bit-field (9.6) can be converted to an
821 // rvalue of type int if int can represent all the values of the
822 // bit-field; otherwise, it can be converted to unsigned int if
823 // unsigned int can represent all the values of the bit-field. If
824 // the bit-field is larger yet, no integral promotion applies to
825 // it. If the bit-field has an enumerated type, it is treated as any
826 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000827 // FIXME: We should delay checking of bit-fields until we actually perform the
828 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000829 using llvm::APSInt;
830 if (From)
831 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000832 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000833 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
834 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
835 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
836 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000837
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000838 // Are we promoting to an int from a bitfield that fits in an int?
839 if (BitWidth < ToSize ||
840 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
841 return To->getKind() == BuiltinType::Int;
842 }
Mike Stump11289f42009-09-09 15:08:12 +0000843
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000844 // Are we promoting to an unsigned int from an unsigned bitfield
845 // that fits into an unsigned int?
846 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
847 return To->getKind() == BuiltinType::UInt;
848 }
Mike Stump11289f42009-09-09 15:08:12 +0000849
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000850 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000851 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000852 }
Mike Stump11289f42009-09-09 15:08:12 +0000853
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000854 // An rvalue of type bool can be converted to an rvalue of type int,
855 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000856 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000857 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000858 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000859
860 return false;
861}
862
863/// IsFloatingPointPromotion - Determines whether the conversion from
864/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
865/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000866bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000867 /// An rvalue of type float can be converted to an rvalue of type
868 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000869 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
870 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000871 if (FromBuiltin->getKind() == BuiltinType::Float &&
872 ToBuiltin->getKind() == BuiltinType::Double)
873 return true;
874
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000875 // C99 6.3.1.5p1:
876 // When a float is promoted to double or long double, or a
877 // double is promoted to long double [...].
878 if (!getLangOptions().CPlusPlus &&
879 (FromBuiltin->getKind() == BuiltinType::Float ||
880 FromBuiltin->getKind() == BuiltinType::Double) &&
881 (ToBuiltin->getKind() == BuiltinType::LongDouble))
882 return true;
883 }
884
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000885 return false;
886}
887
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000888/// \brief Determine if a conversion is a complex promotion.
889///
890/// A complex promotion is defined as a complex -> complex conversion
891/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000892/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000893bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000894 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000895 if (!FromComplex)
896 return false;
897
John McCall9dd450b2009-09-21 23:43:11 +0000898 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000899 if (!ToComplex)
900 return false;
901
902 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000903 ToComplex->getElementType()) ||
904 IsIntegralPromotion(0, FromComplex->getElementType(),
905 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000906}
907
Douglas Gregor237f96c2008-11-26 23:31:11 +0000908/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
909/// the pointer type FromPtr to a pointer to type ToPointee, with the
910/// same type qualifiers as FromPtr has on its pointee type. ToType,
911/// if non-empty, will be a pointer to ToType that may or may not have
912/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000913static QualType
914BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000915 QualType ToPointee, QualType ToType,
916 ASTContext &Context) {
917 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
918 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000919 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000920
921 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000922 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000923 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000924 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000925 return ToType;
926
927 // Build a pointer to ToPointee. It has the right qualifiers
928 // already.
929 return Context.getPointerType(ToPointee);
930 }
931
932 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000933 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000934 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
935 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000936}
937
Fariborz Jahanian01cbe442009-12-16 23:13:33 +0000938/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
939/// the FromType, which is an objective-c pointer, to ToType, which may or may
940/// not have the right set of qualifiers.
941static QualType
942BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
943 QualType ToType,
944 ASTContext &Context) {
945 QualType CanonFromType = Context.getCanonicalType(FromType);
946 QualType CanonToType = Context.getCanonicalType(ToType);
947 Qualifiers Quals = CanonFromType.getQualifiers();
948
949 // Exact qualifier match -> return the pointer type we're converting to.
950 if (CanonToType.getLocalQualifiers() == Quals)
951 return ToType;
952
953 // Just build a canonical type that has the right qualifiers.
954 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
955}
956
Mike Stump11289f42009-09-09 15:08:12 +0000957static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000958 bool InOverloadResolution,
959 ASTContext &Context) {
960 // Handle value-dependent integral null pointer constants correctly.
961 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
962 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
963 Expr->getType()->isIntegralType())
964 return !InOverloadResolution;
965
Douglas Gregor56751b52009-09-25 04:25:58 +0000966 return Expr->isNullPointerConstant(Context,
967 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
968 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000969}
Mike Stump11289f42009-09-09 15:08:12 +0000970
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000971/// IsPointerConversion - Determines whether the conversion of the
972/// expression From, which has the (possibly adjusted) type FromType,
973/// can be converted to the type ToType via a pointer conversion (C++
974/// 4.10). If so, returns true and places the converted type (that
975/// might differ from ToType in its cv-qualifiers at some level) into
976/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000977///
Douglas Gregora29dc052008-11-27 01:19:21 +0000978/// This routine also supports conversions to and from block pointers
979/// and conversions with Objective-C's 'id', 'id<protocols...>', and
980/// pointers to interfaces. FIXME: Once we've determined the
981/// appropriate overloading rules for Objective-C, we may want to
982/// split the Objective-C checks into a different routine; however,
983/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000984/// conversions, so for now they live here. IncompatibleObjC will be
985/// set if the conversion is an allowed Objective-C conversion that
986/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000987bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000988 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000989 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000990 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000991 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000992 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
993 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000994
Mike Stump11289f42009-09-09 15:08:12 +0000995 // Conversion from a null pointer constant to any Objective-C pointer type.
996 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000997 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000998 ConvertedType = ToType;
999 return true;
1000 }
1001
Douglas Gregor231d1c62008-11-27 00:15:41 +00001002 // Blocks: Block pointers can be converted to void*.
1003 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001004 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001005 ConvertedType = ToType;
1006 return true;
1007 }
1008 // Blocks: A null pointer constant can be converted to a block
1009 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001010 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001011 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001012 ConvertedType = ToType;
1013 return true;
1014 }
1015
Sebastian Redl576fd422009-05-10 18:38:11 +00001016 // If the left-hand-side is nullptr_t, the right side can be a null
1017 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001018 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001019 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001020 ConvertedType = ToType;
1021 return true;
1022 }
1023
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001024 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001025 if (!ToTypePtr)
1026 return false;
1027
1028 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001029 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001030 ConvertedType = ToType;
1031 return true;
1032 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001033
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001034 // Beyond this point, both types need to be pointers
1035 // , including objective-c pointers.
1036 QualType ToPointeeType = ToTypePtr->getPointeeType();
1037 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1038 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1039 ToType, Context);
1040 return true;
1041
1042 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001043 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001044 if (!FromTypePtr)
1045 return false;
1046
1047 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001048
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001049 // An rvalue of type "pointer to cv T," where T is an object type,
1050 // can be converted to an rvalue of type "pointer to cv void" (C++
1051 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001052 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001053 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001054 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001055 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001056 return true;
1057 }
1058
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001059 // When we're overloading in C, we allow a special kind of pointer
1060 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001061 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001062 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001063 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001064 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001065 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001066 return true;
1067 }
1068
Douglas Gregor5c407d92008-10-23 00:40:37 +00001069 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001070 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001071 // An rvalue of type "pointer to cv D," where D is a class type,
1072 // can be converted to an rvalue of type "pointer to cv B," where
1073 // B is a base class (clause 10) of D. If B is an inaccessible
1074 // (clause 11) or ambiguous (10.2) base class of D, a program that
1075 // necessitates this conversion is ill-formed. The result of the
1076 // conversion is a pointer to the base class sub-object of the
1077 // derived class object. The null pointer value is converted to
1078 // the null pointer value of the destination type.
1079 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001080 // Note that we do not check for ambiguity or inaccessibility
1081 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001082 if (getLangOptions().CPlusPlus &&
1083 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001084 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001085 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001086 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001087 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001088 ToType, Context);
1089 return true;
1090 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001091
Douglas Gregora119f102008-12-19 19:13:09 +00001092 return false;
1093}
1094
1095/// isObjCPointerConversion - Determines whether this is an
1096/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1097/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001098bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001099 QualType& ConvertedType,
1100 bool &IncompatibleObjC) {
1101 if (!getLangOptions().ObjC1)
1102 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001103
Steve Naroff7cae42b2009-07-10 23:34:53 +00001104 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001105 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001106 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001107 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001108
Steve Naroff7cae42b2009-07-10 23:34:53 +00001109 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001110 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001111 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001112 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001113 ConvertedType = ToType;
1114 return true;
1115 }
1116 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001117 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001118 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001119 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001120 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001121 ConvertedType = ToType;
1122 return true;
1123 }
1124 // Objective C++: We're able to convert from a pointer to an
1125 // interface to a pointer to a different interface.
1126 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1127 ConvertedType = ToType;
1128 return true;
1129 }
1130
1131 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1132 // Okay: this is some kind of implicit downcast of Objective-C
1133 // interfaces, which is permitted. However, we're going to
1134 // complain about it.
1135 IncompatibleObjC = true;
1136 ConvertedType = FromType;
1137 return true;
1138 }
Mike Stump11289f42009-09-09 15:08:12 +00001139 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001140 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001141 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001142 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001143 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001144 else if (const BlockPointerType *ToBlockPtr =
1145 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001146 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001147 // to a block pointer type.
1148 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1149 ConvertedType = ToType;
1150 return true;
1151 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001152 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001153 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001154 else if (FromType->getAs<BlockPointerType>() &&
1155 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1156 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001157 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001158 ConvertedType = ToType;
1159 return true;
1160 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001161 else
Douglas Gregora119f102008-12-19 19:13:09 +00001162 return false;
1163
Douglas Gregor033f56d2008-12-23 00:53:59 +00001164 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001165 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001166 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001167 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001168 FromPointeeType = FromBlockPtr->getPointeeType();
1169 else
Douglas Gregora119f102008-12-19 19:13:09 +00001170 return false;
1171
Douglas Gregora119f102008-12-19 19:13:09 +00001172 // If we have pointers to pointers, recursively check whether this
1173 // is an Objective-C conversion.
1174 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1175 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1176 IncompatibleObjC)) {
1177 // We always complain about this conversion.
1178 IncompatibleObjC = true;
1179 ConvertedType = ToType;
1180 return true;
1181 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001182 // Allow conversion of pointee being objective-c pointer to another one;
1183 // as in I* to id.
1184 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1185 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1186 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1187 IncompatibleObjC)) {
1188 ConvertedType = ToType;
1189 return true;
1190 }
1191
Douglas Gregor033f56d2008-12-23 00:53:59 +00001192 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001193 // differences in the argument and result types are in Objective-C
1194 // pointer conversions. If so, we permit the conversion (but
1195 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001196 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001197 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001198 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001199 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001200 if (FromFunctionType && ToFunctionType) {
1201 // If the function types are exactly the same, this isn't an
1202 // Objective-C pointer conversion.
1203 if (Context.getCanonicalType(FromPointeeType)
1204 == Context.getCanonicalType(ToPointeeType))
1205 return false;
1206
1207 // Perform the quick checks that will tell us whether these
1208 // function types are obviously different.
1209 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1210 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1211 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1212 return false;
1213
1214 bool HasObjCConversion = false;
1215 if (Context.getCanonicalType(FromFunctionType->getResultType())
1216 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1217 // Okay, the types match exactly. Nothing to do.
1218 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1219 ToFunctionType->getResultType(),
1220 ConvertedType, IncompatibleObjC)) {
1221 // Okay, we have an Objective-C pointer conversion.
1222 HasObjCConversion = true;
1223 } else {
1224 // Function types are too different. Abort.
1225 return false;
1226 }
Mike Stump11289f42009-09-09 15:08:12 +00001227
Douglas Gregora119f102008-12-19 19:13:09 +00001228 // Check argument types.
1229 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1230 ArgIdx != NumArgs; ++ArgIdx) {
1231 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1232 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1233 if (Context.getCanonicalType(FromArgType)
1234 == Context.getCanonicalType(ToArgType)) {
1235 // Okay, the types match exactly. Nothing to do.
1236 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1237 ConvertedType, IncompatibleObjC)) {
1238 // Okay, we have an Objective-C pointer conversion.
1239 HasObjCConversion = true;
1240 } else {
1241 // Argument types are too different. Abort.
1242 return false;
1243 }
1244 }
1245
1246 if (HasObjCConversion) {
1247 // We had an Objective-C conversion. Allow this pointer
1248 // conversion, but complain about it.
1249 ConvertedType = ToType;
1250 IncompatibleObjC = true;
1251 return true;
1252 }
1253 }
1254
Sebastian Redl72b597d2009-01-25 19:43:20 +00001255 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001256}
1257
Douglas Gregor39c16d42008-10-24 04:54:22 +00001258/// CheckPointerConversion - Check the pointer conversion from the
1259/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001260/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001261/// conversions for which IsPointerConversion has already returned
1262/// true. It returns true and produces a diagnostic if there was an
1263/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001264bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001265 CastExpr::CastKind &Kind,
1266 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001267 QualType FromType = From->getType();
1268
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001269 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1270 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001271 QualType FromPointeeType = FromPtrType->getPointeeType(),
1272 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001273
Douglas Gregor39c16d42008-10-24 04:54:22 +00001274 if (FromPointeeType->isRecordType() &&
1275 ToPointeeType->isRecordType()) {
1276 // We must have a derived-to-base conversion. Check an
1277 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001278 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1279 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001280 From->getSourceRange(),
1281 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001282 return true;
1283
1284 // The conversion was successful.
1285 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001286 }
1287 }
Mike Stump11289f42009-09-09 15:08:12 +00001288 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001289 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001290 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001291 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001292 // Objective-C++ conversions are always okay.
1293 // FIXME: We should have a different class of conversions for the
1294 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001295 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001296 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001297
Steve Naroff7cae42b2009-07-10 23:34:53 +00001298 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001299 return false;
1300}
1301
Sebastian Redl72b597d2009-01-25 19:43:20 +00001302/// IsMemberPointerConversion - Determines whether the conversion of the
1303/// expression From, which has the (possibly adjusted) type FromType, can be
1304/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1305/// If so, returns true and places the converted type (that might differ from
1306/// ToType in its cv-qualifiers at some level) into ConvertedType.
1307bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001308 QualType ToType,
1309 bool InOverloadResolution,
1310 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001311 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001312 if (!ToTypePtr)
1313 return false;
1314
1315 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001316 if (From->isNullPointerConstant(Context,
1317 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1318 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001319 ConvertedType = ToType;
1320 return true;
1321 }
1322
1323 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001324 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001325 if (!FromTypePtr)
1326 return false;
1327
1328 // A pointer to member of B can be converted to a pointer to member of D,
1329 // where D is derived from B (C++ 4.11p2).
1330 QualType FromClass(FromTypePtr->getClass(), 0);
1331 QualType ToClass(ToTypePtr->getClass(), 0);
1332 // FIXME: What happens when these are dependent? Is this function even called?
1333
1334 if (IsDerivedFrom(ToClass, FromClass)) {
1335 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1336 ToClass.getTypePtr());
1337 return true;
1338 }
1339
1340 return false;
1341}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001342
Sebastian Redl72b597d2009-01-25 19:43:20 +00001343/// CheckMemberPointerConversion - Check the member pointer conversion from the
1344/// expression From to the type ToType. This routine checks for ambiguous or
1345/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1346/// for which IsMemberPointerConversion has already returned true. It returns
1347/// true and produces a diagnostic if there was an error, or returns false
1348/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001349bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001350 CastExpr::CastKind &Kind,
1351 bool IgnoreBaseAccess) {
1352 (void)IgnoreBaseAccess;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001353 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001354 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001355 if (!FromPtrType) {
1356 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001357 assert(From->isNullPointerConstant(Context,
1358 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001359 "Expr must be null pointer constant!");
1360 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001361 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001362 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001363
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001364 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001365 assert(ToPtrType && "No member pointer cast has a target type "
1366 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001367
Sebastian Redled8f2002009-01-28 18:33:18 +00001368 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1369 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001370
Sebastian Redled8f2002009-01-28 18:33:18 +00001371 // FIXME: What about dependent types?
1372 assert(FromClass->isRecordType() && "Pointer into non-class.");
1373 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001374
Douglas Gregor36d1b142009-10-06 17:59:45 +00001375 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1376 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001377 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1378 assert(DerivationOkay &&
1379 "Should not have been called if derivation isn't OK.");
1380 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001381
Sebastian Redled8f2002009-01-28 18:33:18 +00001382 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1383 getUnqualifiedType())) {
1384 // Derivation is ambiguous. Redo the check to find the exact paths.
1385 Paths.clear();
1386 Paths.setRecordingPaths(true);
1387 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1388 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1389 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001390
Sebastian Redled8f2002009-01-28 18:33:18 +00001391 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1392 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1393 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1394 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001395 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001396
Douglas Gregor89ee6822009-02-28 01:32:25 +00001397 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001398 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1399 << FromClass << ToClass << QualType(VBase, 0)
1400 << From->getSourceRange();
1401 return true;
1402 }
1403
Anders Carlssond7923c62009-08-22 23:33:40 +00001404 // Must be a base to derived member conversion.
1405 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001406 return false;
1407}
1408
Douglas Gregor9a657932008-10-21 23:43:52 +00001409/// IsQualificationConversion - Determines whether the conversion from
1410/// an rvalue of type FromType to ToType is a qualification conversion
1411/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001412bool
1413Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001414 FromType = Context.getCanonicalType(FromType);
1415 ToType = Context.getCanonicalType(ToType);
1416
1417 // If FromType and ToType are the same type, this is not a
1418 // qualification conversion.
1419 if (FromType == ToType)
1420 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001421
Douglas Gregor9a657932008-10-21 23:43:52 +00001422 // (C++ 4.4p4):
1423 // A conversion can add cv-qualifiers at levels other than the first
1424 // in multi-level pointers, subject to the following rules: [...]
1425 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001426 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001427 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001428 // Within each iteration of the loop, we check the qualifiers to
1429 // determine if this still looks like a qualification
1430 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001431 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001432 // until there are no more pointers or pointers-to-members left to
1433 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001434 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001435
1436 // -- for every j > 0, if const is in cv 1,j then const is in cv
1437 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001438 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001439 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001440
Douglas Gregor9a657932008-10-21 23:43:52 +00001441 // -- if the cv 1,j and cv 2,j are different, then const is in
1442 // every cv for 0 < k < j.
1443 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001444 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001445 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001446
Douglas Gregor9a657932008-10-21 23:43:52 +00001447 // Keep track of whether all prior cv-qualifiers in the "to" type
1448 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001449 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001450 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001451 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001452
1453 // We are left with FromType and ToType being the pointee types
1454 // after unwrapping the original FromType and ToType the same number
1455 // of types. If we unwrapped any pointers, and if FromType and
1456 // ToType have the same unqualified type (since we checked
1457 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001458 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001459}
1460
Douglas Gregor576e98c2009-01-30 23:27:23 +00001461/// Determines whether there is a user-defined conversion sequence
1462/// (C++ [over.ics.user]) that converts expression From to the type
1463/// ToType. If such a conversion exists, User will contain the
1464/// user-defined conversion sequence that performs such a conversion
1465/// and this routine will return true. Otherwise, this routine returns
1466/// false and User is unspecified.
1467///
1468/// \param AllowConversionFunctions true if the conversion should
1469/// consider conversion functions at all. If false, only constructors
1470/// will be considered.
1471///
1472/// \param AllowExplicit true if the conversion should consider C++0x
1473/// "explicit" conversion functions as well as non-explicit conversion
1474/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001475///
1476/// \param ForceRValue true if the expression should be treated as an rvalue
1477/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001478/// \param UserCast true if looking for user defined conversion for a static
1479/// cast.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001480OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1481 UserDefinedConversionSequence& User,
1482 OverloadCandidateSet& CandidateSet,
1483 bool AllowConversionFunctions,
1484 bool AllowExplicit,
1485 bool ForceRValue,
1486 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001487 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001488 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1489 // We're not going to find any constructors.
1490 } else if (CXXRecordDecl *ToRecordDecl
1491 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001492 // C++ [over.match.ctor]p1:
1493 // When objects of class type are direct-initialized (8.5), or
1494 // copy-initialized from an expression of the same or a
1495 // derived class type (8.5), overload resolution selects the
1496 // constructor. [...] For copy-initialization, the candidate
1497 // functions are all the converting constructors (12.3.1) of
1498 // that class. The argument list is the expression-list within
1499 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001500 bool SuppressUserConversions = !UserCast;
1501 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1502 IsDerivedFrom(From->getType(), ToType)) {
1503 SuppressUserConversions = false;
1504 AllowConversionFunctions = false;
1505 }
1506
Mike Stump11289f42009-09-09 15:08:12 +00001507 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001508 = Context.DeclarationNames.getCXXConstructorName(
1509 Context.getCanonicalType(ToType).getUnqualifiedType());
1510 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001511 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001512 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001513 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001514 // Find the constructor (which may be a template).
1515 CXXConstructorDecl *Constructor = 0;
1516 FunctionTemplateDecl *ConstructorTmpl
1517 = dyn_cast<FunctionTemplateDecl>(*Con);
1518 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001519 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001520 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1521 else
1522 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001523
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001524 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001525 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001526 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00001527 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1528 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001529 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001530 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001531 // Allow one user-defined conversion when user specifies a
1532 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001533 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001534 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001535 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001536 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001537 }
1538 }
1539
Douglas Gregor576e98c2009-01-30 23:27:23 +00001540 if (!AllowConversionFunctions) {
1541 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001542 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1543 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001544 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001545 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001546 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001547 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001548 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001549 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1550 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001551 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001552 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001553 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001554 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00001555 NamedDecl *D = *I;
1556 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1557 if (isa<UsingShadowDecl>(D))
1558 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1559
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001560 CXXConversionDecl *Conv;
1561 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001562 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001563 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1564 else
John McCalld14a8642009-11-21 08:51:07 +00001565 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001566
1567 if (AllowExplicit || !Conv->isExplicit()) {
1568 if (ConvTemplate)
John McCall6e9f8f62009-12-03 04:06:58 +00001569 AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1570 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001571 else
John McCall6e9f8f62009-12-03 04:06:58 +00001572 AddConversionCandidate(Conv, ActingContext, From, ToType,
1573 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001574 }
1575 }
1576 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001577 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001578
1579 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001580 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001581 case OR_Success:
1582 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001583 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001584 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1585 // C++ [over.ics.user]p1:
1586 // If the user-defined conversion is specified by a
1587 // constructor (12.3.1), the initial standard conversion
1588 // sequence converts the source type to the type required by
1589 // the argument of the constructor.
1590 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001591 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001592 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001593 User.EllipsisConversion = true;
1594 else {
1595 User.Before = Best->Conversions[0].Standard;
1596 User.EllipsisConversion = false;
1597 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001598 User.ConversionFunction = Constructor;
1599 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001600 User.After.setFromType(
1601 ThisType->getAs<PointerType>()->getPointeeType());
1602 User.After.setToType(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001603 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001604 } else if (CXXConversionDecl *Conversion
1605 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1606 // C++ [over.ics.user]p1:
1607 //
1608 // [...] If the user-defined conversion is specified by a
1609 // conversion function (12.3.2), the initial standard
1610 // conversion sequence converts the source type to the
1611 // implicit object parameter of the conversion function.
1612 User.Before = Best->Conversions[0].Standard;
1613 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001614 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001615
1616 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001617 // The second standard conversion sequence converts the
1618 // result of the user-defined conversion to the target type
1619 // for the sequence. Since an implicit conversion sequence
1620 // is an initialization, the special rules for
1621 // initialization by user-defined conversion apply when
1622 // selecting the best user-defined conversion for a
1623 // user-defined conversion sequence (see 13.3.3 and
1624 // 13.3.3.1).
1625 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001626 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001627 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001628 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001629 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001630 }
Mike Stump11289f42009-09-09 15:08:12 +00001631
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001632 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001633 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001634 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001635 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001636 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001637
1638 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001639 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001640 }
1641
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001642 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001643}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001644
1645bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001646Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001647 ImplicitConversionSequence ICS;
1648 OverloadCandidateSet CandidateSet;
1649 OverloadingResult OvResult =
1650 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1651 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001652 if (OvResult == OR_Ambiguous)
1653 Diag(From->getSourceRange().getBegin(),
1654 diag::err_typecheck_ambiguous_condition)
1655 << From->getType() << ToType << From->getSourceRange();
1656 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1657 Diag(From->getSourceRange().getBegin(),
1658 diag::err_typecheck_nonviable_condition)
1659 << From->getType() << ToType << From->getSourceRange();
1660 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001661 return false;
John McCallad907772010-01-12 07:18:19 +00001662 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001663 return true;
1664}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001665
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001666/// CompareImplicitConversionSequences - Compare two implicit
1667/// conversion sequences to determine whether one is better than the
1668/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001669ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001670Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1671 const ImplicitConversionSequence& ICS2)
1672{
1673 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1674 // conversion sequences (as defined in 13.3.3.1)
1675 // -- a standard conversion sequence (13.3.3.1.1) is a better
1676 // conversion sequence than a user-defined conversion sequence or
1677 // an ellipsis conversion sequence, and
1678 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1679 // conversion sequence than an ellipsis conversion sequence
1680 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001681 //
John McCall0d1da222010-01-12 00:44:57 +00001682 // C++0x [over.best.ics]p10:
1683 // For the purpose of ranking implicit conversion sequences as
1684 // described in 13.3.3.2, the ambiguous conversion sequence is
1685 // treated as a user-defined sequence that is indistinguishable
1686 // from any other user-defined conversion sequence.
1687 if (ICS1.getKind() < ICS2.getKind()) {
1688 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1689 return ImplicitConversionSequence::Better;
1690 } else if (ICS2.getKind() < ICS1.getKind()) {
1691 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1692 return ImplicitConversionSequence::Worse;
1693 }
1694
1695 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1696 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001697
1698 // Two implicit conversion sequences of the same form are
1699 // indistinguishable conversion sequences unless one of the
1700 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001701 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001702 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001703 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001704 // User-defined conversion sequence U1 is a better conversion
1705 // sequence than another user-defined conversion sequence U2 if
1706 // they contain the same user-defined conversion function or
1707 // constructor and if the second standard conversion sequence of
1708 // U1 is better than the second standard conversion sequence of
1709 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001710 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001711 ICS2.UserDefined.ConversionFunction)
1712 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1713 ICS2.UserDefined.After);
1714 }
1715
1716 return ImplicitConversionSequence::Indistinguishable;
1717}
1718
1719/// CompareStandardConversionSequences - Compare two standard
1720/// conversion sequences to determine whether one is better than the
1721/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001722ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001723Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1724 const StandardConversionSequence& SCS2)
1725{
1726 // Standard conversion sequence S1 is a better conversion sequence
1727 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1728
1729 // -- S1 is a proper subsequence of S2 (comparing the conversion
1730 // sequences in the canonical form defined by 13.3.3.1.1,
1731 // excluding any Lvalue Transformation; the identity conversion
1732 // sequence is considered to be a subsequence of any
1733 // non-identity conversion sequence) or, if not that,
1734 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1735 // Neither is a proper subsequence of the other. Do nothing.
1736 ;
1737 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1738 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001739 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001740 SCS1.Third == ICK_Identity))
1741 // SCS1 is a proper subsequence of SCS2.
1742 return ImplicitConversionSequence::Better;
1743 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1744 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001745 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001746 SCS2.Third == ICK_Identity))
1747 // SCS2 is a proper subsequence of SCS1.
1748 return ImplicitConversionSequence::Worse;
1749
1750 // -- the rank of S1 is better than the rank of S2 (by the rules
1751 // defined below), or, if not that,
1752 ImplicitConversionRank Rank1 = SCS1.getRank();
1753 ImplicitConversionRank Rank2 = SCS2.getRank();
1754 if (Rank1 < Rank2)
1755 return ImplicitConversionSequence::Better;
1756 else if (Rank2 < Rank1)
1757 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001758
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001759 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1760 // are indistinguishable unless one of the following rules
1761 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001762
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001763 // A conversion that is not a conversion of a pointer, or
1764 // pointer to member, to bool is better than another conversion
1765 // that is such a conversion.
1766 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1767 return SCS2.isPointerConversionToBool()
1768 ? ImplicitConversionSequence::Better
1769 : ImplicitConversionSequence::Worse;
1770
Douglas Gregor5c407d92008-10-23 00:40:37 +00001771 // C++ [over.ics.rank]p4b2:
1772 //
1773 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001774 // conversion of B* to A* is better than conversion of B* to
1775 // void*, and conversion of A* to void* is better than conversion
1776 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001777 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001778 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001779 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001780 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001781 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1782 // Exactly one of the conversion sequences is a conversion to
1783 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001784 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1785 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001786 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1787 // Neither conversion sequence converts to a void pointer; compare
1788 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001789 if (ImplicitConversionSequence::CompareKind DerivedCK
1790 = CompareDerivedToBaseConversions(SCS1, SCS2))
1791 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001792 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1793 // Both conversion sequences are conversions to void
1794 // pointers. Compare the source types to determine if there's an
1795 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001796 QualType FromType1 = SCS1.getFromType();
1797 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001798
1799 // Adjust the types we're converting from via the array-to-pointer
1800 // conversion, if we need to.
1801 if (SCS1.First == ICK_Array_To_Pointer)
1802 FromType1 = Context.getArrayDecayedType(FromType1);
1803 if (SCS2.First == ICK_Array_To_Pointer)
1804 FromType2 = Context.getArrayDecayedType(FromType2);
1805
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001806 QualType FromPointee1
1807 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1808 QualType FromPointee2
1809 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001810
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001811 if (IsDerivedFrom(FromPointee2, FromPointee1))
1812 return ImplicitConversionSequence::Better;
1813 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1814 return ImplicitConversionSequence::Worse;
1815
1816 // Objective-C++: If one interface is more specific than the
1817 // other, it is the better one.
1818 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1819 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1820 if (FromIface1 && FromIface1) {
1821 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1822 return ImplicitConversionSequence::Better;
1823 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1824 return ImplicitConversionSequence::Worse;
1825 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001826 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001827
1828 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1829 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001830 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001831 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001832 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001833
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001834 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001835 // C++0x [over.ics.rank]p3b4:
1836 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1837 // implicit object parameter of a non-static member function declared
1838 // without a ref-qualifier, and S1 binds an rvalue reference to an
1839 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001840 // FIXME: We don't know if we're dealing with the implicit object parameter,
1841 // or if the member function in this case has a ref qualifier.
1842 // (Of course, we don't have ref qualifiers yet.)
1843 if (SCS1.RRefBinding != SCS2.RRefBinding)
1844 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1845 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001846
1847 // C++ [over.ics.rank]p3b4:
1848 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1849 // which the references refer are the same type except for
1850 // top-level cv-qualifiers, and the type to which the reference
1851 // initialized by S2 refers is more cv-qualified than the type
1852 // to which the reference initialized by S1 refers.
John McCall0d1da222010-01-12 00:44:57 +00001853 QualType T1 = SCS1.getToType();
1854 QualType T2 = SCS2.getToType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001855 T1 = Context.getCanonicalType(T1);
1856 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001857 Qualifiers T1Quals, T2Quals;
1858 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1859 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1860 if (UnqualT1 == UnqualT2) {
1861 // If the type is an array type, promote the element qualifiers to the type
1862 // for comparison.
1863 if (isa<ArrayType>(T1) && T1Quals)
1864 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1865 if (isa<ArrayType>(T2) && T2Quals)
1866 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001867 if (T2.isMoreQualifiedThan(T1))
1868 return ImplicitConversionSequence::Better;
1869 else if (T1.isMoreQualifiedThan(T2))
1870 return ImplicitConversionSequence::Worse;
1871 }
1872 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001873
1874 return ImplicitConversionSequence::Indistinguishable;
1875}
1876
1877/// CompareQualificationConversions - Compares two standard conversion
1878/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001879/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1880ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001881Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001882 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001883 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001884 // -- S1 and S2 differ only in their qualification conversion and
1885 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1886 // cv-qualification signature of type T1 is a proper subset of
1887 // the cv-qualification signature of type T2, and S1 is not the
1888 // deprecated string literal array-to-pointer conversion (4.2).
1889 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1890 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1891 return ImplicitConversionSequence::Indistinguishable;
1892
1893 // FIXME: the example in the standard doesn't use a qualification
1894 // conversion (!)
1895 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1896 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1897 T1 = Context.getCanonicalType(T1);
1898 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001899 Qualifiers T1Quals, T2Quals;
1900 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1901 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001902
1903 // If the types are the same, we won't learn anything by unwrapped
1904 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00001905 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001906 return ImplicitConversionSequence::Indistinguishable;
1907
Chandler Carruth607f38e2009-12-29 07:16:59 +00001908 // If the type is an array type, promote the element qualifiers to the type
1909 // for comparison.
1910 if (isa<ArrayType>(T1) && T1Quals)
1911 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1912 if (isa<ArrayType>(T2) && T2Quals)
1913 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1914
Mike Stump11289f42009-09-09 15:08:12 +00001915 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001916 = ImplicitConversionSequence::Indistinguishable;
1917 while (UnwrapSimilarPointerTypes(T1, T2)) {
1918 // Within each iteration of the loop, we check the qualifiers to
1919 // determine if this still looks like a qualification
1920 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001921 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001922 // until there are no more pointers or pointers-to-members left
1923 // to unwrap. This essentially mimics what
1924 // IsQualificationConversion does, but here we're checking for a
1925 // strict subset of qualifiers.
1926 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1927 // The qualifiers are the same, so this doesn't tell us anything
1928 // about how the sequences rank.
1929 ;
1930 else if (T2.isMoreQualifiedThan(T1)) {
1931 // T1 has fewer qualifiers, so it could be the better sequence.
1932 if (Result == ImplicitConversionSequence::Worse)
1933 // Neither has qualifiers that are a subset of the other's
1934 // qualifiers.
1935 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001936
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001937 Result = ImplicitConversionSequence::Better;
1938 } else if (T1.isMoreQualifiedThan(T2)) {
1939 // T2 has fewer qualifiers, so it could be the better sequence.
1940 if (Result == ImplicitConversionSequence::Better)
1941 // Neither has qualifiers that are a subset of the other's
1942 // qualifiers.
1943 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001944
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001945 Result = ImplicitConversionSequence::Worse;
1946 } else {
1947 // Qualifiers are disjoint.
1948 return ImplicitConversionSequence::Indistinguishable;
1949 }
1950
1951 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001952 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001953 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001954 }
1955
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001956 // Check that the winning standard conversion sequence isn't using
1957 // the deprecated string literal array to pointer conversion.
1958 switch (Result) {
1959 case ImplicitConversionSequence::Better:
1960 if (SCS1.Deprecated)
1961 Result = ImplicitConversionSequence::Indistinguishable;
1962 break;
1963
1964 case ImplicitConversionSequence::Indistinguishable:
1965 break;
1966
1967 case ImplicitConversionSequence::Worse:
1968 if (SCS2.Deprecated)
1969 Result = ImplicitConversionSequence::Indistinguishable;
1970 break;
1971 }
1972
1973 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001974}
1975
Douglas Gregor5c407d92008-10-23 00:40:37 +00001976/// CompareDerivedToBaseConversions - Compares two standard conversion
1977/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001978/// various kinds of derived-to-base conversions (C++
1979/// [over.ics.rank]p4b3). As part of these checks, we also look at
1980/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001981ImplicitConversionSequence::CompareKind
1982Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1983 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00001984 QualType FromType1 = SCS1.getFromType();
1985 QualType ToType1 = SCS1.getToType();
1986 QualType FromType2 = SCS2.getFromType();
1987 QualType ToType2 = SCS2.getToType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001988
1989 // Adjust the types we're converting from via the array-to-pointer
1990 // conversion, if we need to.
1991 if (SCS1.First == ICK_Array_To_Pointer)
1992 FromType1 = Context.getArrayDecayedType(FromType1);
1993 if (SCS2.First == ICK_Array_To_Pointer)
1994 FromType2 = Context.getArrayDecayedType(FromType2);
1995
1996 // Canonicalize all of the types.
1997 FromType1 = Context.getCanonicalType(FromType1);
1998 ToType1 = Context.getCanonicalType(ToType1);
1999 FromType2 = Context.getCanonicalType(FromType2);
2000 ToType2 = Context.getCanonicalType(ToType2);
2001
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002002 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002003 //
2004 // If class B is derived directly or indirectly from class A and
2005 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002006 //
2007 // For Objective-C, we let A, B, and C also be Objective-C
2008 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002009
2010 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002011 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002012 SCS2.Second == ICK_Pointer_Conversion &&
2013 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2014 FromType1->isPointerType() && FromType2->isPointerType() &&
2015 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002016 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002017 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002018 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002019 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002020 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002021 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002022 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002023 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002024
John McCall9dd450b2009-09-21 23:43:11 +00002025 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2026 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2027 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2028 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002029
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002030 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002031 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2032 if (IsDerivedFrom(ToPointee1, ToPointee2))
2033 return ImplicitConversionSequence::Better;
2034 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2035 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002036
2037 if (ToIface1 && ToIface2) {
2038 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2039 return ImplicitConversionSequence::Better;
2040 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2041 return ImplicitConversionSequence::Worse;
2042 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002043 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002044
2045 // -- conversion of B* to A* is better than conversion of C* to A*,
2046 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2047 if (IsDerivedFrom(FromPointee2, FromPointee1))
2048 return ImplicitConversionSequence::Better;
2049 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2050 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002051
Douglas Gregor237f96c2008-11-26 23:31:11 +00002052 if (FromIface1 && FromIface2) {
2053 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2054 return ImplicitConversionSequence::Better;
2055 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2056 return ImplicitConversionSequence::Worse;
2057 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002058 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002059 }
2060
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002061 // Compare based on reference bindings.
2062 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
2063 SCS1.Second == ICK_Derived_To_Base) {
2064 // -- binding of an expression of type C to a reference of type
2065 // B& is better than binding an expression of type C to a
2066 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002067 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2068 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002069 if (IsDerivedFrom(ToType1, ToType2))
2070 return ImplicitConversionSequence::Better;
2071 else if (IsDerivedFrom(ToType2, ToType1))
2072 return ImplicitConversionSequence::Worse;
2073 }
2074
Douglas Gregor2fe98832008-11-03 19:09:14 +00002075 // -- binding of an expression of type B to a reference of type
2076 // A& is better than binding an expression of type C to a
2077 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002078 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2079 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002080 if (IsDerivedFrom(FromType2, FromType1))
2081 return ImplicitConversionSequence::Better;
2082 else if (IsDerivedFrom(FromType1, FromType2))
2083 return ImplicitConversionSequence::Worse;
2084 }
2085 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002086
2087 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002088 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2089 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2090 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2091 const MemberPointerType * FromMemPointer1 =
2092 FromType1->getAs<MemberPointerType>();
2093 const MemberPointerType * ToMemPointer1 =
2094 ToType1->getAs<MemberPointerType>();
2095 const MemberPointerType * FromMemPointer2 =
2096 FromType2->getAs<MemberPointerType>();
2097 const MemberPointerType * ToMemPointer2 =
2098 ToType2->getAs<MemberPointerType>();
2099 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2100 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2101 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2102 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2103 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2104 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2105 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2106 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002107 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002108 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2109 if (IsDerivedFrom(ToPointee1, ToPointee2))
2110 return ImplicitConversionSequence::Worse;
2111 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2112 return ImplicitConversionSequence::Better;
2113 }
2114 // conversion of B::* to C::* is better than conversion of A::* to C::*
2115 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2116 if (IsDerivedFrom(FromPointee1, FromPointee2))
2117 return ImplicitConversionSequence::Better;
2118 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2119 return ImplicitConversionSequence::Worse;
2120 }
2121 }
2122
Douglas Gregor2fe98832008-11-03 19:09:14 +00002123 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2124 SCS1.Second == ICK_Derived_To_Base) {
2125 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002126 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2127 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002128 if (IsDerivedFrom(ToType1, ToType2))
2129 return ImplicitConversionSequence::Better;
2130 else if (IsDerivedFrom(ToType2, ToType1))
2131 return ImplicitConversionSequence::Worse;
2132 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002133
Douglas Gregor2fe98832008-11-03 19:09:14 +00002134 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002135 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2136 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002137 if (IsDerivedFrom(FromType2, FromType1))
2138 return ImplicitConversionSequence::Better;
2139 else if (IsDerivedFrom(FromType1, FromType2))
2140 return ImplicitConversionSequence::Worse;
2141 }
2142 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002143
Douglas Gregor5c407d92008-10-23 00:40:37 +00002144 return ImplicitConversionSequence::Indistinguishable;
2145}
2146
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002147/// TryCopyInitialization - Try to copy-initialize a value of type
2148/// ToType from the expression From. Return the implicit conversion
2149/// sequence required to pass this argument, which may be a bad
2150/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002151/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002152/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2153/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002154ImplicitConversionSequence
2155Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002156 bool SuppressUserConversions, bool ForceRValue,
2157 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002158 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002159 ImplicitConversionSequence ICS;
John McCall6a61b522010-01-13 09:16:55 +00002160 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002161 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002162 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002163 SuppressUserConversions,
2164 /*AllowExplicit=*/false,
2165 ForceRValue,
2166 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002167 return ICS;
2168 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002169 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002170 SuppressUserConversions,
2171 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002172 ForceRValue,
2173 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002174 }
2175}
2176
Sebastian Redl42e92c42009-04-12 17:16:29 +00002177/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2178/// the expression @p From. Returns true (and emits a diagnostic) if there was
2179/// an error, returns false if the initialization succeeded. Elidable should
2180/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2181/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002182bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002183 AssignmentAction Action, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002184 if (!getLangOptions().CPlusPlus) {
2185 // In C, argument passing is the same as performing an assignment.
2186 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002187
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002188 AssignConvertType ConvTy =
2189 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002190 if (ConvTy != Compatible &&
2191 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2192 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002193
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002194 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002195 FromType, From, Action);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002196 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002197
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002198 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002199 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002200 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002201 /*SuppressUserConversions=*/false,
2202 /*AllowExplicit=*/false,
2203 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002204
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002205 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002206 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002207 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002208 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002209 return Diag(From->getSourceRange().getBegin(),
2210 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002211 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002212 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002213}
2214
Douglas Gregor436424c2008-11-18 23:14:02 +00002215/// TryObjectArgumentInitialization - Try to initialize the object
2216/// parameter of the given member function (@c Method) from the
2217/// expression @p From.
2218ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002219Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002220 CXXMethodDecl *Method,
2221 CXXRecordDecl *ActingContext) {
2222 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002223 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2224 // const volatile object.
2225 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2226 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2227 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002228
2229 // Set up the conversion sequence as a "bad" conversion, to allow us
2230 // to exit early.
2231 ImplicitConversionSequence ICS;
2232 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002233 ICS.setBad();
Douglas Gregor436424c2008-11-18 23:14:02 +00002234
2235 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002236 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002237 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002238 FromType = PT->getPointeeType();
2239
2240 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002241
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002242 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002243 // where X is the class of which the function is a member
2244 // (C++ [over.match.funcs]p4). However, when finding an implicit
2245 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002246 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002247 // (C++ [over.match.funcs]p5). We perform a simplified version of
2248 // reference binding here, that allows class rvalues to bind to
2249 // non-constant references.
2250
2251 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2252 // with the implicit object parameter (C++ [over.match.funcs]p5).
2253 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002254 if (ImplicitParamType.getCVRQualifiers()
2255 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002256 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall47000992010-01-14 03:28:57 +00002257 ICS.Bad.init(BadConversionSequence::bad_qualifiers,
2258 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002259 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002260 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002261
2262 // Check that we have either the same type or a derived type. It
2263 // affects the conversion rank.
2264 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002265 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002266 ICS.Standard.Second = ICK_Identity;
2267 else if (IsDerivedFrom(FromType, ClassType))
2268 ICS.Standard.Second = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002269 else {
2270 ICS.Bad.init(BadConversionSequence::unrelated_class, FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002271 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002272 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002273
2274 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002275 ICS.setStandard();
2276 ICS.Standard.setFromType(FromType);
2277 ICS.Standard.setToType(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002278 ICS.Standard.ReferenceBinding = true;
2279 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002280 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002281 return ICS;
2282}
2283
2284/// PerformObjectArgumentInitialization - Perform initialization of
2285/// the implicit object parameter for the given Method with the given
2286/// expression.
2287bool
2288Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002289 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002290 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002291 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002292
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002293 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002294 FromRecordType = PT->getPointeeType();
2295 DestType = Method->getThisType(Context);
2296 } else {
2297 FromRecordType = From->getType();
2298 DestType = ImplicitParamRecordType;
2299 }
2300
John McCall6e9f8f62009-12-03 04:06:58 +00002301 // Note that we always use the true parent context when performing
2302 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002303 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002304 = TryObjectArgumentInitialization(From->getType(), Method,
2305 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002306 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002307 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002308 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002309 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002310
Douglas Gregor436424c2008-11-18 23:14:02 +00002311 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002312 CheckDerivedToBaseConversion(FromRecordType,
2313 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002314 From->getSourceRange().getBegin(),
2315 From->getSourceRange()))
2316 return true;
2317
Mike Stump11289f42009-09-09 15:08:12 +00002318 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002319 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002320 return false;
2321}
2322
Douglas Gregor5fb53972009-01-14 15:45:31 +00002323/// TryContextuallyConvertToBool - Attempt to contextually convert the
2324/// expression From to bool (C++0x [conv]p3).
2325ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002326 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002327 // FIXME: Are these flags correct?
2328 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002329 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002330 /*ForceRValue=*/false,
2331 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002332}
2333
2334/// PerformContextuallyConvertToBool - Perform a contextual conversion
2335/// of the expression From to bool (C++0x [conv]p3).
2336bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2337 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002338 if (!ICS.isBad())
2339 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002340
Fariborz Jahanian76197412009-11-18 18:26:29 +00002341 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002342 return Diag(From->getSourceRange().getBegin(),
2343 diag::err_typecheck_bool_condition)
2344 << From->getType() << From->getSourceRange();
2345 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002346}
2347
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002348/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002349/// candidate functions, using the given function call arguments. If
2350/// @p SuppressUserConversions, then don't allow user-defined
2351/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002352/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2353/// hacky way to implement the overloading rules for elidable copy
2354/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002355///
2356/// \para PartialOverloading true if we are performing "partial" overloading
2357/// based on an incomplete set of function arguments. This feature is used by
2358/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002359void
2360Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002361 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002362 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002363 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002364 bool ForceRValue,
2365 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002366 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002367 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002368 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002369 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002370 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002371
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002372 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002373 if (!isa<CXXConstructorDecl>(Method)) {
2374 // If we get here, it's because we're calling a member function
2375 // that is named without a member access expression (e.g.,
2376 // "this->f") that was either written explicitly or created
2377 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002378 // function, e.g., X::f(). We use an empty type for the implied
2379 // object argument (C++ [over.call.func]p3), and the acting context
2380 // is irrelevant.
2381 AddMethodCandidate(Method, Method->getParent(),
2382 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002383 SuppressUserConversions, ForceRValue);
2384 return;
2385 }
2386 // We treat a constructor like a non-member function, since its object
2387 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002388 }
2389
Douglas Gregorff7028a2009-11-13 23:59:09 +00002390 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002391 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002392
Douglas Gregor27381f32009-11-23 12:27:39 +00002393 // Overload resolution is always an unevaluated context.
2394 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2395
Douglas Gregorffe14e32009-11-14 01:20:54 +00002396 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2397 // C++ [class.copy]p3:
2398 // A member function template is never instantiated to perform the copy
2399 // of a class object to an object of its class type.
2400 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2401 if (NumArgs == 1 &&
2402 Constructor->isCopyConstructorLikeSpecialization() &&
2403 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2404 return;
2405 }
2406
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002407 // Add this candidate
2408 CandidateSet.push_back(OverloadCandidate());
2409 OverloadCandidate& Candidate = CandidateSet.back();
2410 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002411 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002412 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002413 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002414
2415 unsigned NumArgsInProto = Proto->getNumArgs();
2416
2417 // (C++ 13.3.2p2): A candidate function having fewer than m
2418 // parameters is viable only if it has an ellipsis in its parameter
2419 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002420 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2421 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002422 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002423 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002424 return;
2425 }
2426
2427 // (C++ 13.3.2p2): A candidate function having more than m parameters
2428 // is viable only if the (m+1)st parameter has a default argument
2429 // (8.3.6). For the purposes of overload resolution, the
2430 // parameter list is truncated on the right, so that there are
2431 // exactly m parameters.
2432 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002433 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002434 // Not enough arguments.
2435 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002436 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002437 return;
2438 }
2439
2440 // Determine the implicit conversion sequences for each of the
2441 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002442 Candidate.Conversions.resize(NumArgs);
2443 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2444 if (ArgIdx < NumArgsInProto) {
2445 // (C++ 13.3.2p3): for F to be a viable function, there shall
2446 // exist for each argument an implicit conversion sequence
2447 // (13.3.3.1) that converts that argument to the corresponding
2448 // parameter of F.
2449 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002450 Candidate.Conversions[ArgIdx]
2451 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002452 SuppressUserConversions, ForceRValue,
2453 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002454 if (Candidate.Conversions[ArgIdx].isBad()) {
2455 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002456 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002457 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002458 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002459 } else {
2460 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2461 // argument for which there is no corresponding parameter is
2462 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002463 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002464 }
2465 }
2466}
2467
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002468/// \brief Add all of the function declarations in the given function set to
2469/// the overload canddiate set.
2470void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2471 Expr **Args, unsigned NumArgs,
2472 OverloadCandidateSet& CandidateSet,
2473 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002474 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002475 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002476 F != FEnd; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002477 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002478 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2479 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2480 AddMethodCandidate(cast<CXXMethodDecl>(FD),
John McCall6e9f8f62009-12-03 04:06:58 +00002481 cast<CXXMethodDecl>(FD)->getParent(),
2482 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002483 CandidateSet, SuppressUserConversions);
2484 else
2485 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2486 SuppressUserConversions);
2487 } else {
2488 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2489 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2490 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2491 AddMethodTemplateCandidate(FunTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002492 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002493 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002494 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002495 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002496 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002497 else
2498 AddTemplateOverloadCandidate(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002499 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002500 Args, NumArgs, CandidateSet,
2501 SuppressUserConversions);
2502 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002503 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002504}
2505
John McCallf0f1cf02009-11-17 07:50:12 +00002506/// AddMethodCandidate - Adds a named decl (which is some kind of
2507/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002508void Sema::AddMethodCandidate(NamedDecl *Decl,
2509 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002510 Expr **Args, unsigned NumArgs,
2511 OverloadCandidateSet& CandidateSet,
2512 bool SuppressUserConversions, bool ForceRValue) {
John McCall6e9f8f62009-12-03 04:06:58 +00002513 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002514
2515 if (isa<UsingShadowDecl>(Decl))
2516 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2517
2518 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2519 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2520 "Expected a member function template");
John McCall6e9f8f62009-12-03 04:06:58 +00002521 AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2522 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002523 CandidateSet,
2524 SuppressUserConversions,
2525 ForceRValue);
2526 } else {
John McCall6e9f8f62009-12-03 04:06:58 +00002527 AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2528 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002529 CandidateSet, SuppressUserConversions, ForceRValue);
2530 }
2531}
2532
Douglas Gregor436424c2008-11-18 23:14:02 +00002533/// AddMethodCandidate - Adds the given C++ member function to the set
2534/// of candidate functions, using the given function call arguments
2535/// and the object argument (@c Object). For example, in a call
2536/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2537/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2538/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002539/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2540/// a slightly hacky way to implement the overloading rules for elidable copy
2541/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002542void
John McCall6e9f8f62009-12-03 04:06:58 +00002543Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2544 QualType ObjectType, Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002545 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002546 bool SuppressUserConversions, bool ForceRValue) {
2547 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002548 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002549 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002550 assert(!isa<CXXConstructorDecl>(Method) &&
2551 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002552
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002553 if (!CandidateSet.isNewCandidate(Method))
2554 return;
2555
Douglas Gregor27381f32009-11-23 12:27:39 +00002556 // Overload resolution is always an unevaluated context.
2557 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2558
Douglas Gregor436424c2008-11-18 23:14:02 +00002559 // Add this candidate
2560 CandidateSet.push_back(OverloadCandidate());
2561 OverloadCandidate& Candidate = CandidateSet.back();
2562 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002563 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002564 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002565
2566 unsigned NumArgsInProto = Proto->getNumArgs();
2567
2568 // (C++ 13.3.2p2): A candidate function having fewer than m
2569 // parameters is viable only if it has an ellipsis in its parameter
2570 // list (8.3.5).
2571 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2572 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002573 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002574 return;
2575 }
2576
2577 // (C++ 13.3.2p2): A candidate function having more than m parameters
2578 // is viable only if the (m+1)st parameter has a default argument
2579 // (8.3.6). For the purposes of overload resolution, the
2580 // parameter list is truncated on the right, so that there are
2581 // exactly m parameters.
2582 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2583 if (NumArgs < MinRequiredArgs) {
2584 // Not enough arguments.
2585 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002586 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002587 return;
2588 }
2589
2590 Candidate.Viable = true;
2591 Candidate.Conversions.resize(NumArgs + 1);
2592
John McCall6e9f8f62009-12-03 04:06:58 +00002593 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002594 // The implicit object argument is ignored.
2595 Candidate.IgnoreObjectArgument = true;
2596 else {
2597 // Determine the implicit conversion sequence for the object
2598 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002599 Candidate.Conversions[0]
2600 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002601 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002602 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002603 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002604 return;
2605 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002606 }
2607
2608 // Determine the implicit conversion sequences for each of the
2609 // arguments.
2610 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2611 if (ArgIdx < NumArgsInProto) {
2612 // (C++ 13.3.2p3): for F to be a viable function, there shall
2613 // exist for each argument an implicit conversion sequence
2614 // (13.3.3.1) that converts that argument to the corresponding
2615 // parameter of F.
2616 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002617 Candidate.Conversions[ArgIdx + 1]
2618 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002619 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002620 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002621 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002622 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002623 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002624 break;
2625 }
2626 } else {
2627 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2628 // argument for which there is no corresponding parameter is
2629 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002630 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002631 }
2632 }
2633}
2634
Douglas Gregor97628d62009-08-21 00:16:32 +00002635/// \brief Add a C++ member function template as a candidate to the candidate
2636/// set, using template argument deduction to produce an appropriate member
2637/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002638void
Douglas Gregor97628d62009-08-21 00:16:32 +00002639Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002640 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002641 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002642 QualType ObjectType,
2643 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002644 OverloadCandidateSet& CandidateSet,
2645 bool SuppressUserConversions,
2646 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002647 if (!CandidateSet.isNewCandidate(MethodTmpl))
2648 return;
2649
Douglas Gregor97628d62009-08-21 00:16:32 +00002650 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002651 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002652 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002653 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002654 // candidate functions in the usual way.113) A given name can refer to one
2655 // or more function templates and also to a set of overloaded non-template
2656 // functions. In such a case, the candidate functions generated from each
2657 // function template are combined with the set of non-template candidate
2658 // functions.
2659 TemplateDeductionInfo Info(Context);
2660 FunctionDecl *Specialization = 0;
2661 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002662 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002663 Args, NumArgs, Specialization, Info)) {
2664 // FIXME: Record what happened with template argument deduction, so
2665 // that we can give the user a beautiful diagnostic.
2666 (void)Result;
2667 return;
2668 }
Mike Stump11289f42009-09-09 15:08:12 +00002669
Douglas Gregor97628d62009-08-21 00:16:32 +00002670 // Add the function template specialization produced by template argument
2671 // deduction as a candidate.
2672 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002673 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002674 "Specialization is not a member function?");
John McCall6e9f8f62009-12-03 04:06:58 +00002675 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2676 ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002677 CandidateSet, SuppressUserConversions, ForceRValue);
2678}
2679
Douglas Gregor05155d82009-08-21 23:19:43 +00002680/// \brief Add a C++ function template specialization as a candidate
2681/// in the candidate set, using template argument deduction to produce
2682/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002683void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002684Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002685 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002686 Expr **Args, unsigned NumArgs,
2687 OverloadCandidateSet& CandidateSet,
2688 bool SuppressUserConversions,
2689 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002690 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2691 return;
2692
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002693 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002694 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002695 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002696 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002697 // candidate functions in the usual way.113) A given name can refer to one
2698 // or more function templates and also to a set of overloaded non-template
2699 // functions. In such a case, the candidate functions generated from each
2700 // function template are combined with the set of non-template candidate
2701 // functions.
2702 TemplateDeductionInfo Info(Context);
2703 FunctionDecl *Specialization = 0;
2704 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002705 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002706 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002707 // FIXME: Record what happened with template argument deduction, so
2708 // that we can give the user a beautiful diagnostic.
John McCalld681c392009-12-16 08:11:27 +00002709 (void) Result;
2710
2711 CandidateSet.push_back(OverloadCandidate());
2712 OverloadCandidate &Candidate = CandidateSet.back();
2713 Candidate.Function = FunctionTemplate->getTemplatedDecl();
2714 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002715 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00002716 Candidate.IsSurrogate = false;
2717 Candidate.IgnoreObjectArgument = false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002718 return;
2719 }
Mike Stump11289f42009-09-09 15:08:12 +00002720
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002721 // Add the function template specialization produced by template argument
2722 // deduction as a candidate.
2723 assert(Specialization && "Missing function template specialization?");
2724 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2725 SuppressUserConversions, ForceRValue);
2726}
Mike Stump11289f42009-09-09 15:08:12 +00002727
Douglas Gregora1f013e2008-11-07 22:36:19 +00002728/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002729/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002730/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002731/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002732/// (which may or may not be the same type as the type that the
2733/// conversion function produces).
2734void
2735Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002736 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002737 Expr *From, QualType ToType,
2738 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002739 assert(!Conversion->getDescribedFunctionTemplate() &&
2740 "Conversion function templates use AddTemplateConversionCandidate");
2741
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002742 if (!CandidateSet.isNewCandidate(Conversion))
2743 return;
2744
Douglas Gregor27381f32009-11-23 12:27:39 +00002745 // Overload resolution is always an unevaluated context.
2746 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2747
Douglas Gregora1f013e2008-11-07 22:36:19 +00002748 // Add this candidate
2749 CandidateSet.push_back(OverloadCandidate());
2750 OverloadCandidate& Candidate = CandidateSet.back();
2751 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002752 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002753 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002754 Candidate.FinalConversion.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002755 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
2756 Candidate.FinalConversion.setToType(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00002757
Douglas Gregor436424c2008-11-18 23:14:02 +00002758 // Determine the implicit conversion sequence for the implicit
2759 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002760 Candidate.Viable = true;
2761 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002762 Candidate.Conversions[0]
2763 = TryObjectArgumentInitialization(From->getType(), Conversion,
2764 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002765 // Conversion functions to a different type in the base class is visible in
2766 // the derived class. So, a derived to base conversion should not participate
2767 // in overload resolution.
2768 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2769 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00002770 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002771 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002772 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002773 return;
2774 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002775
2776 // We won't go through a user-define type conversion function to convert a
2777 // derived to base as such conversions are given Conversion Rank. They only
2778 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2779 QualType FromCanon
2780 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2781 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2782 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2783 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002784 Candidate.FailureKind = ovl_fail_bad_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002785 return;
2786 }
2787
Douglas Gregora1f013e2008-11-07 22:36:19 +00002788
2789 // To determine what the conversion from the result of calling the
2790 // conversion function to the type we're eventually trying to
2791 // convert to (ToType), we need to synthesize a call to the
2792 // conversion function and attempt copy initialization from it. This
2793 // makes sure that we get the right semantics with respect to
2794 // lvalues/rvalues and the type. Fortunately, we can allocate this
2795 // call on the stack and we don't need its arguments to be
2796 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002797 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002798 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002799 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002800 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002801 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002802
2803 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002804 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2805 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002806 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002807 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002808 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002809 ImplicitConversionSequence ICS =
2810 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002811 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002812 /*ForceRValue=*/false,
2813 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002814
John McCall0d1da222010-01-12 00:44:57 +00002815 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002816 case ImplicitConversionSequence::StandardConversion:
2817 Candidate.FinalConversion = ICS.Standard;
2818 break;
2819
2820 case ImplicitConversionSequence::BadConversion:
2821 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002822 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002823 break;
2824
2825 default:
Mike Stump11289f42009-09-09 15:08:12 +00002826 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002827 "Can only end up with a standard conversion sequence or failure");
2828 }
2829}
2830
Douglas Gregor05155d82009-08-21 23:19:43 +00002831/// \brief Adds a conversion function template specialization
2832/// candidate to the overload set, using template argument deduction
2833/// to deduce the template arguments of the conversion function
2834/// template from the type that we are converting to (C++
2835/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002836void
Douglas Gregor05155d82009-08-21 23:19:43 +00002837Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6e9f8f62009-12-03 04:06:58 +00002838 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002839 Expr *From, QualType ToType,
2840 OverloadCandidateSet &CandidateSet) {
2841 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2842 "Only conversion function templates permitted here");
2843
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002844 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2845 return;
2846
Douglas Gregor05155d82009-08-21 23:19:43 +00002847 TemplateDeductionInfo Info(Context);
2848 CXXConversionDecl *Specialization = 0;
2849 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002850 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002851 Specialization, Info)) {
2852 // FIXME: Record what happened with template argument deduction, so
2853 // that we can give the user a beautiful diagnostic.
2854 (void)Result;
2855 return;
2856 }
Mike Stump11289f42009-09-09 15:08:12 +00002857
Douglas Gregor05155d82009-08-21 23:19:43 +00002858 // Add the conversion function template specialization produced by
2859 // template argument deduction as a candidate.
2860 assert(Specialization && "Missing function template specialization?");
John McCall6e9f8f62009-12-03 04:06:58 +00002861 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002862}
2863
Douglas Gregorab7897a2008-11-19 22:57:39 +00002864/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2865/// converts the given @c Object to a function pointer via the
2866/// conversion function @c Conversion, and then attempts to call it
2867/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2868/// the type of function that we'll eventually be calling.
2869void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002870 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002871 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002872 QualType ObjectType,
2873 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002874 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002875 if (!CandidateSet.isNewCandidate(Conversion))
2876 return;
2877
Douglas Gregor27381f32009-11-23 12:27:39 +00002878 // Overload resolution is always an unevaluated context.
2879 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2880
Douglas Gregorab7897a2008-11-19 22:57:39 +00002881 CandidateSet.push_back(OverloadCandidate());
2882 OverloadCandidate& Candidate = CandidateSet.back();
2883 Candidate.Function = 0;
2884 Candidate.Surrogate = Conversion;
2885 Candidate.Viable = true;
2886 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002887 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002888 Candidate.Conversions.resize(NumArgs + 1);
2889
2890 // Determine the implicit conversion sequence for the implicit
2891 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002892 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002893 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002894 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002895 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002896 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002897 return;
2898 }
2899
2900 // The first conversion is actually a user-defined conversion whose
2901 // first conversion is ObjectInit's standard conversion (which is
2902 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00002903 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002904 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002905 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002906 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002907 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002908 = Candidate.Conversions[0].UserDefined.Before;
2909 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2910
Mike Stump11289f42009-09-09 15:08:12 +00002911 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002912 unsigned NumArgsInProto = Proto->getNumArgs();
2913
2914 // (C++ 13.3.2p2): A candidate function having fewer than m
2915 // parameters is viable only if it has an ellipsis in its parameter
2916 // list (8.3.5).
2917 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2918 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002919 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002920 return;
2921 }
2922
2923 // Function types don't have any default arguments, so just check if
2924 // we have enough arguments.
2925 if (NumArgs < NumArgsInProto) {
2926 // Not enough arguments.
2927 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002928 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002929 return;
2930 }
2931
2932 // Determine the implicit conversion sequences for each of the
2933 // arguments.
2934 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2935 if (ArgIdx < NumArgsInProto) {
2936 // (C++ 13.3.2p3): for F to be a viable function, there shall
2937 // exist for each argument an implicit conversion sequence
2938 // (13.3.3.1) that converts that argument to the corresponding
2939 // parameter of F.
2940 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002941 Candidate.Conversions[ArgIdx + 1]
2942 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002943 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002944 /*ForceRValue=*/false,
2945 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00002946 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002947 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002948 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002949 break;
2950 }
2951 } else {
2952 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2953 // argument for which there is no corresponding parameter is
2954 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002955 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002956 }
2957 }
2958}
2959
Mike Stump87c57ac2009-05-16 07:39:55 +00002960// FIXME: This will eventually be removed, once we've migrated all of the
2961// operator overloading logic over to the scheme used by binary operators, which
2962// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002963void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002964 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002965 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002966 OverloadCandidateSet& CandidateSet,
2967 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002968 FunctionSet Functions;
2969
2970 QualType T1 = Args[0]->getType();
2971 QualType T2;
2972 if (NumArgs > 1)
2973 T2 = Args[1]->getType();
2974
2975 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002976 if (S)
2977 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002978 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002979 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2980 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002981 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002982}
2983
2984/// \brief Add overload candidates for overloaded operators that are
2985/// member functions.
2986///
2987/// Add the overloaded operator candidates that are member functions
2988/// for the operator Op that was used in an operator expression such
2989/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2990/// CandidateSet will store the added overload candidates. (C++
2991/// [over.match.oper]).
2992void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2993 SourceLocation OpLoc,
2994 Expr **Args, unsigned NumArgs,
2995 OverloadCandidateSet& CandidateSet,
2996 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002997 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2998
2999 // C++ [over.match.oper]p3:
3000 // For a unary operator @ with an operand of a type whose
3001 // cv-unqualified version is T1, and for a binary operator @ with
3002 // a left operand of a type whose cv-unqualified version is T1 and
3003 // a right operand of a type whose cv-unqualified version is T2,
3004 // three sets of candidate functions, designated member
3005 // candidates, non-member candidates and built-in candidates, are
3006 // constructed as follows:
3007 QualType T1 = Args[0]->getType();
3008 QualType T2;
3009 if (NumArgs > 1)
3010 T2 = Args[1]->getType();
3011
3012 // -- If T1 is a class type, the set of member candidates is the
3013 // result of the qualified lookup of T1::operator@
3014 // (13.3.1.1.1); otherwise, the set of member candidates is
3015 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003016 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003017 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003018 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003019 return;
Mike Stump11289f42009-09-09 15:08:12 +00003020
John McCall27b18f82009-11-17 02:14:36 +00003021 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3022 LookupQualifiedName(Operators, T1Rec->getDecl());
3023 Operators.suppressDiagnostics();
3024
Mike Stump11289f42009-09-09 15:08:12 +00003025 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003026 OperEnd = Operators.end();
3027 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003028 ++Oper)
John McCall6e9f8f62009-12-03 04:06:58 +00003029 AddMethodCandidate(*Oper, Args[0]->getType(),
3030 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003031 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003032 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003033}
3034
Douglas Gregora11693b2008-11-12 17:17:38 +00003035/// AddBuiltinCandidate - Add a candidate for a built-in
3036/// operator. ResultTy and ParamTys are the result and parameter types
3037/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003038/// arguments being passed to the candidate. IsAssignmentOperator
3039/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003040/// operator. NumContextualBoolArguments is the number of arguments
3041/// (at the beginning of the argument list) that will be contextually
3042/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003043void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003044 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003045 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003046 bool IsAssignmentOperator,
3047 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003048 // Overload resolution is always an unevaluated context.
3049 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3050
Douglas Gregora11693b2008-11-12 17:17:38 +00003051 // Add this candidate
3052 CandidateSet.push_back(OverloadCandidate());
3053 OverloadCandidate& Candidate = CandidateSet.back();
3054 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003055 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003056 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003057 Candidate.BuiltinTypes.ResultTy = ResultTy;
3058 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3059 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3060
3061 // Determine the implicit conversion sequences for each of the
3062 // arguments.
3063 Candidate.Viable = true;
3064 Candidate.Conversions.resize(NumArgs);
3065 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003066 // C++ [over.match.oper]p4:
3067 // For the built-in assignment operators, conversions of the
3068 // left operand are restricted as follows:
3069 // -- no temporaries are introduced to hold the left operand, and
3070 // -- no user-defined conversions are applied to the left
3071 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003072 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003073 //
3074 // We block these conversions by turning off user-defined
3075 // conversions, since that is the only way that initialization of
3076 // a reference to a non-class type can occur from something that
3077 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003078 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003079 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003080 "Contextual conversion to bool requires bool type");
3081 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3082 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003083 Candidate.Conversions[ArgIdx]
3084 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003085 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003086 /*ForceRValue=*/false,
3087 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003088 }
John McCall0d1da222010-01-12 00:44:57 +00003089 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003090 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003091 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003092 break;
3093 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003094 }
3095}
3096
3097/// BuiltinCandidateTypeSet - A set of types that will be used for the
3098/// candidate operator functions for built-in operators (C++
3099/// [over.built]). The types are separated into pointer types and
3100/// enumeration types.
3101class BuiltinCandidateTypeSet {
3102 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003103 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003104
3105 /// PointerTypes - The set of pointer types that will be used in the
3106 /// built-in candidates.
3107 TypeSet PointerTypes;
3108
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003109 /// MemberPointerTypes - The set of member pointer types that will be
3110 /// used in the built-in candidates.
3111 TypeSet MemberPointerTypes;
3112
Douglas Gregora11693b2008-11-12 17:17:38 +00003113 /// EnumerationTypes - The set of enumeration types that will be
3114 /// used in the built-in candidates.
3115 TypeSet EnumerationTypes;
3116
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003117 /// Sema - The semantic analysis instance where we are building the
3118 /// candidate type set.
3119 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003120
Douglas Gregora11693b2008-11-12 17:17:38 +00003121 /// Context - The AST context in which we will build the type sets.
3122 ASTContext &Context;
3123
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003124 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3125 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003126 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003127
3128public:
3129 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003130 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003131
Mike Stump11289f42009-09-09 15:08:12 +00003132 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003133 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003134
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003135 void AddTypesConvertedFrom(QualType Ty,
3136 SourceLocation Loc,
3137 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003138 bool AllowExplicitConversions,
3139 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003140
3141 /// pointer_begin - First pointer type found;
3142 iterator pointer_begin() { return PointerTypes.begin(); }
3143
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003144 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003145 iterator pointer_end() { return PointerTypes.end(); }
3146
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003147 /// member_pointer_begin - First member pointer type found;
3148 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3149
3150 /// member_pointer_end - Past the last member pointer type found;
3151 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3152
Douglas Gregora11693b2008-11-12 17:17:38 +00003153 /// enumeration_begin - First enumeration type found;
3154 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3155
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003156 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003157 iterator enumeration_end() { return EnumerationTypes.end(); }
3158};
3159
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003160/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003161/// the set of pointer types along with any more-qualified variants of
3162/// that type. For example, if @p Ty is "int const *", this routine
3163/// will add "int const *", "int const volatile *", "int const
3164/// restrict *", and "int const volatile restrict *" to the set of
3165/// pointer types. Returns true if the add of @p Ty itself succeeded,
3166/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003167///
3168/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003169bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003170BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3171 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003172
Douglas Gregora11693b2008-11-12 17:17:38 +00003173 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003174 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003175 return false;
3176
John McCall8ccfcb52009-09-24 19:53:00 +00003177 const PointerType *PointerTy = Ty->getAs<PointerType>();
3178 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003179
John McCall8ccfcb52009-09-24 19:53:00 +00003180 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003181 // Don't add qualified variants of arrays. For one, they're not allowed
3182 // (the qualifier would sink to the element type), and for another, the
3183 // only overload situation where it matters is subscript or pointer +- int,
3184 // and those shouldn't have qualifier variants anyway.
3185 if (PointeeTy->isArrayType())
3186 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003187 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003188 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003189 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003190 bool hasVolatile = VisibleQuals.hasVolatile();
3191 bool hasRestrict = VisibleQuals.hasRestrict();
3192
John McCall8ccfcb52009-09-24 19:53:00 +00003193 // Iterate through all strict supersets of BaseCVR.
3194 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3195 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003196 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3197 // in the types.
3198 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3199 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003200 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3201 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003202 }
3203
3204 return true;
3205}
3206
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003207/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3208/// to the set of pointer types along with any more-qualified variants of
3209/// that type. For example, if @p Ty is "int const *", this routine
3210/// will add "int const *", "int const volatile *", "int const
3211/// restrict *", and "int const volatile restrict *" to the set of
3212/// pointer types. Returns true if the add of @p Ty itself succeeded,
3213/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003214///
3215/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003216bool
3217BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3218 QualType Ty) {
3219 // Insert this type.
3220 if (!MemberPointerTypes.insert(Ty))
3221 return false;
3222
John McCall8ccfcb52009-09-24 19:53:00 +00003223 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3224 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003225
John McCall8ccfcb52009-09-24 19:53:00 +00003226 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003227 // Don't add qualified variants of arrays. For one, they're not allowed
3228 // (the qualifier would sink to the element type), and for another, the
3229 // only overload situation where it matters is subscript or pointer +- int,
3230 // and those shouldn't have qualifier variants anyway.
3231 if (PointeeTy->isArrayType())
3232 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003233 const Type *ClassTy = PointerTy->getClass();
3234
3235 // Iterate through all strict supersets of the pointee type's CVR
3236 // qualifiers.
3237 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3238 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3239 if ((CVR | BaseCVR) != CVR) continue;
3240
3241 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3242 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003243 }
3244
3245 return true;
3246}
3247
Douglas Gregora11693b2008-11-12 17:17:38 +00003248/// AddTypesConvertedFrom - Add each of the types to which the type @p
3249/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003250/// primarily interested in pointer types and enumeration types. We also
3251/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003252/// AllowUserConversions is true if we should look at the conversion
3253/// functions of a class type, and AllowExplicitConversions if we
3254/// should also include the explicit conversion functions of a class
3255/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003256void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003257BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003258 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003259 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003260 bool AllowExplicitConversions,
3261 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003262 // Only deal with canonical types.
3263 Ty = Context.getCanonicalType(Ty);
3264
3265 // Look through reference types; they aren't part of the type of an
3266 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003267 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003268 Ty = RefTy->getPointeeType();
3269
3270 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003271 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003272
Sebastian Redl65ae2002009-11-05 16:36:20 +00003273 // If we're dealing with an array type, decay to the pointer.
3274 if (Ty->isArrayType())
3275 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3276
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003277 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003278 QualType PointeeTy = PointerTy->getPointeeType();
3279
3280 // Insert our type, and its more-qualified variants, into the set
3281 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003282 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003283 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003284 } else if (Ty->isMemberPointerType()) {
3285 // Member pointers are far easier, since the pointee can't be converted.
3286 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3287 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003288 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003289 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003290 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003291 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003292 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003293 // No conversion functions in incomplete types.
3294 return;
3295 }
Mike Stump11289f42009-09-09 15:08:12 +00003296
Douglas Gregora11693b2008-11-12 17:17:38 +00003297 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003298 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003299 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003300 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003301 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003302
Mike Stump11289f42009-09-09 15:08:12 +00003303 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003304 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003305 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003306 continue;
3307
John McCalld14a8642009-11-21 08:51:07 +00003308 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003309 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003310 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003311 VisibleQuals);
3312 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003313 }
3314 }
3315 }
3316}
3317
Douglas Gregor84605ae2009-08-24 13:43:27 +00003318/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3319/// the volatile- and non-volatile-qualified assignment operators for the
3320/// given type to the candidate set.
3321static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3322 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003323 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003324 unsigned NumArgs,
3325 OverloadCandidateSet &CandidateSet) {
3326 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003327
Douglas Gregor84605ae2009-08-24 13:43:27 +00003328 // T& operator=(T&, T)
3329 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3330 ParamTypes[1] = T;
3331 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3332 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003333
Douglas Gregor84605ae2009-08-24 13:43:27 +00003334 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3335 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003336 ParamTypes[0]
3337 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003338 ParamTypes[1] = T;
3339 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003340 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003341 }
3342}
Mike Stump11289f42009-09-09 15:08:12 +00003343
Sebastian Redl1054fae2009-10-25 17:03:50 +00003344/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3345/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003346static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3347 Qualifiers VRQuals;
3348 const RecordType *TyRec;
3349 if (const MemberPointerType *RHSMPType =
3350 ArgExpr->getType()->getAs<MemberPointerType>())
3351 TyRec = cast<RecordType>(RHSMPType->getClass());
3352 else
3353 TyRec = ArgExpr->getType()->getAs<RecordType>();
3354 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003355 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003356 VRQuals.addVolatile();
3357 VRQuals.addRestrict();
3358 return VRQuals;
3359 }
3360
3361 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003362 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003363 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003364
John McCallad371252010-01-20 00:46:10 +00003365 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003366 E = Conversions->end(); I != E; ++I) {
3367 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003368 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3369 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3370 CanTy = ResTypeRef->getPointeeType();
3371 // Need to go down the pointer/mempointer chain and add qualifiers
3372 // as see them.
3373 bool done = false;
3374 while (!done) {
3375 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3376 CanTy = ResTypePtr->getPointeeType();
3377 else if (const MemberPointerType *ResTypeMPtr =
3378 CanTy->getAs<MemberPointerType>())
3379 CanTy = ResTypeMPtr->getPointeeType();
3380 else
3381 done = true;
3382 if (CanTy.isVolatileQualified())
3383 VRQuals.addVolatile();
3384 if (CanTy.isRestrictQualified())
3385 VRQuals.addRestrict();
3386 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3387 return VRQuals;
3388 }
3389 }
3390 }
3391 return VRQuals;
3392}
3393
Douglas Gregord08452f2008-11-19 15:42:04 +00003394/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3395/// operator overloads to the candidate set (C++ [over.built]), based
3396/// on the operator @p Op and the arguments given. For example, if the
3397/// operator is a binary '+', this routine might add "int
3398/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003399void
Mike Stump11289f42009-09-09 15:08:12 +00003400Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003401 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003402 Expr **Args, unsigned NumArgs,
3403 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003404 // The set of "promoted arithmetic types", which are the arithmetic
3405 // types are that preserved by promotion (C++ [over.built]p2). Note
3406 // that the first few of these types are the promoted integral
3407 // types; these types need to be first.
3408 // FIXME: What about complex?
3409 const unsigned FirstIntegralType = 0;
3410 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003411 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003412 LastPromotedIntegralType = 13;
3413 const unsigned FirstPromotedArithmeticType = 7,
3414 LastPromotedArithmeticType = 16;
3415 const unsigned NumArithmeticTypes = 16;
3416 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003417 Context.BoolTy, Context.CharTy, Context.WCharTy,
3418// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003419 Context.SignedCharTy, Context.ShortTy,
3420 Context.UnsignedCharTy, Context.UnsignedShortTy,
3421 Context.IntTy, Context.LongTy, Context.LongLongTy,
3422 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3423 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3424 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003425 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3426 "Invalid first promoted integral type");
3427 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3428 == Context.UnsignedLongLongTy &&
3429 "Invalid last promoted integral type");
3430 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3431 "Invalid first promoted arithmetic type");
3432 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3433 == Context.LongDoubleTy &&
3434 "Invalid last promoted arithmetic type");
3435
Douglas Gregora11693b2008-11-12 17:17:38 +00003436 // Find all of the types that the arguments can convert to, but only
3437 // if the operator we're looking at has built-in operator candidates
3438 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003439 Qualifiers VisibleTypeConversionsQuals;
3440 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003441 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3442 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3443
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003444 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003445 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3446 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003447 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003448 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003449 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003450 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003451 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003452 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003453 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003454 true,
3455 (Op == OO_Exclaim ||
3456 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003457 Op == OO_PipePipe),
3458 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003459 }
3460
3461 bool isComparison = false;
3462 switch (Op) {
3463 case OO_None:
3464 case NUM_OVERLOADED_OPERATORS:
3465 assert(false && "Expected an overloaded operator");
3466 break;
3467
Douglas Gregord08452f2008-11-19 15:42:04 +00003468 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003469 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003470 goto UnaryStar;
3471 else
3472 goto BinaryStar;
3473 break;
3474
3475 case OO_Plus: // '+' is either unary or binary
3476 if (NumArgs == 1)
3477 goto UnaryPlus;
3478 else
3479 goto BinaryPlus;
3480 break;
3481
3482 case OO_Minus: // '-' is either unary or binary
3483 if (NumArgs == 1)
3484 goto UnaryMinus;
3485 else
3486 goto BinaryMinus;
3487 break;
3488
3489 case OO_Amp: // '&' is either unary or binary
3490 if (NumArgs == 1)
3491 goto UnaryAmp;
3492 else
3493 goto BinaryAmp;
3494
3495 case OO_PlusPlus:
3496 case OO_MinusMinus:
3497 // C++ [over.built]p3:
3498 //
3499 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3500 // is either volatile or empty, there exist candidate operator
3501 // functions of the form
3502 //
3503 // VQ T& operator++(VQ T&);
3504 // T operator++(VQ T&, int);
3505 //
3506 // C++ [over.built]p4:
3507 //
3508 // For every pair (T, VQ), where T is an arithmetic type other
3509 // than bool, and VQ is either volatile or empty, there exist
3510 // candidate operator functions of the form
3511 //
3512 // VQ T& operator--(VQ T&);
3513 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003514 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003515 Arith < NumArithmeticTypes; ++Arith) {
3516 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003517 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003518 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003519
3520 // Non-volatile version.
3521 if (NumArgs == 1)
3522 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3523 else
3524 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003525 // heuristic to reduce number of builtin candidates in the set.
3526 // Add volatile version only if there are conversions to a volatile type.
3527 if (VisibleTypeConversionsQuals.hasVolatile()) {
3528 // Volatile version
3529 ParamTypes[0]
3530 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3531 if (NumArgs == 1)
3532 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3533 else
3534 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3535 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003536 }
3537
3538 // C++ [over.built]p5:
3539 //
3540 // For every pair (T, VQ), where T is a cv-qualified or
3541 // cv-unqualified object type, and VQ is either volatile or
3542 // empty, there exist candidate operator functions of the form
3543 //
3544 // T*VQ& operator++(T*VQ&);
3545 // T*VQ& operator--(T*VQ&);
3546 // T* operator++(T*VQ&, int);
3547 // T* operator--(T*VQ&, int);
3548 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3549 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3550 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003551 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003552 continue;
3553
Mike Stump11289f42009-09-09 15:08:12 +00003554 QualType ParamTypes[2] = {
3555 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003556 };
Mike Stump11289f42009-09-09 15:08:12 +00003557
Douglas Gregord08452f2008-11-19 15:42:04 +00003558 // Without volatile
3559 if (NumArgs == 1)
3560 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3561 else
3562 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3563
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003564 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3565 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003566 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003567 ParamTypes[0]
3568 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003569 if (NumArgs == 1)
3570 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3571 else
3572 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3573 }
3574 }
3575 break;
3576
3577 UnaryStar:
3578 // C++ [over.built]p6:
3579 // For every cv-qualified or cv-unqualified object type T, there
3580 // exist candidate operator functions of the form
3581 //
3582 // T& operator*(T*);
3583 //
3584 // C++ [over.built]p7:
3585 // For every function type T, there exist candidate operator
3586 // functions of the form
3587 // T& operator*(T*);
3588 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3589 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3590 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003591 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003592 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003593 &ParamTy, Args, 1, CandidateSet);
3594 }
3595 break;
3596
3597 UnaryPlus:
3598 // C++ [over.built]p8:
3599 // For every type T, there exist candidate operator functions of
3600 // the form
3601 //
3602 // T* operator+(T*);
3603 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3604 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3605 QualType ParamTy = *Ptr;
3606 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3607 }
Mike Stump11289f42009-09-09 15:08:12 +00003608
Douglas Gregord08452f2008-11-19 15:42:04 +00003609 // Fall through
3610
3611 UnaryMinus:
3612 // C++ [over.built]p9:
3613 // For every promoted arithmetic type T, there exist candidate
3614 // operator functions of the form
3615 //
3616 // T operator+(T);
3617 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003618 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003619 Arith < LastPromotedArithmeticType; ++Arith) {
3620 QualType ArithTy = ArithmeticTypes[Arith];
3621 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3622 }
3623 break;
3624
3625 case OO_Tilde:
3626 // C++ [over.built]p10:
3627 // For every promoted integral type T, there exist candidate
3628 // operator functions of the form
3629 //
3630 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003631 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003632 Int < LastPromotedIntegralType; ++Int) {
3633 QualType IntTy = ArithmeticTypes[Int];
3634 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3635 }
3636 break;
3637
Douglas Gregora11693b2008-11-12 17:17:38 +00003638 case OO_New:
3639 case OO_Delete:
3640 case OO_Array_New:
3641 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003642 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003643 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003644 break;
3645
3646 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003647 UnaryAmp:
3648 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003649 // C++ [over.match.oper]p3:
3650 // -- For the operator ',', the unary operator '&', or the
3651 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003652 break;
3653
Douglas Gregor84605ae2009-08-24 13:43:27 +00003654 case OO_EqualEqual:
3655 case OO_ExclaimEqual:
3656 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003657 // For every pointer to member type T, there exist candidate operator
3658 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003659 //
3660 // bool operator==(T,T);
3661 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003662 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003663 MemPtr = CandidateTypes.member_pointer_begin(),
3664 MemPtrEnd = CandidateTypes.member_pointer_end();
3665 MemPtr != MemPtrEnd;
3666 ++MemPtr) {
3667 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3668 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3669 }
Mike Stump11289f42009-09-09 15:08:12 +00003670
Douglas Gregor84605ae2009-08-24 13:43:27 +00003671 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003672
Douglas Gregora11693b2008-11-12 17:17:38 +00003673 case OO_Less:
3674 case OO_Greater:
3675 case OO_LessEqual:
3676 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003677 // C++ [over.built]p15:
3678 //
3679 // For every pointer or enumeration type T, there exist
3680 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003681 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003682 // bool operator<(T, T);
3683 // bool operator>(T, T);
3684 // bool operator<=(T, T);
3685 // bool operator>=(T, T);
3686 // bool operator==(T, T);
3687 // bool operator!=(T, T);
3688 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3689 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3690 QualType ParamTypes[2] = { *Ptr, *Ptr };
3691 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3692 }
Mike Stump11289f42009-09-09 15:08:12 +00003693 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003694 = CandidateTypes.enumeration_begin();
3695 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3696 QualType ParamTypes[2] = { *Enum, *Enum };
3697 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3698 }
3699
3700 // Fall through.
3701 isComparison = true;
3702
Douglas Gregord08452f2008-11-19 15:42:04 +00003703 BinaryPlus:
3704 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003705 if (!isComparison) {
3706 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3707
3708 // C++ [over.built]p13:
3709 //
3710 // For every cv-qualified or cv-unqualified object type T
3711 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003712 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003713 // T* operator+(T*, ptrdiff_t);
3714 // T& operator[](T*, ptrdiff_t); [BELOW]
3715 // T* operator-(T*, ptrdiff_t);
3716 // T* operator+(ptrdiff_t, T*);
3717 // T& operator[](ptrdiff_t, T*); [BELOW]
3718 //
3719 // C++ [over.built]p14:
3720 //
3721 // For every T, where T is a pointer to object type, there
3722 // exist candidate operator functions of the form
3723 //
3724 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003725 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003726 = CandidateTypes.pointer_begin();
3727 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3728 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3729
3730 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3731 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3732
3733 if (Op == OO_Plus) {
3734 // T* operator+(ptrdiff_t, T*);
3735 ParamTypes[0] = ParamTypes[1];
3736 ParamTypes[1] = *Ptr;
3737 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3738 } else {
3739 // ptrdiff_t operator-(T, T);
3740 ParamTypes[1] = *Ptr;
3741 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3742 Args, 2, CandidateSet);
3743 }
3744 }
3745 }
3746 // Fall through
3747
Douglas Gregora11693b2008-11-12 17:17:38 +00003748 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003749 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003750 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003751 // C++ [over.built]p12:
3752 //
3753 // For every pair of promoted arithmetic types L and R, there
3754 // exist candidate operator functions of the form
3755 //
3756 // LR operator*(L, R);
3757 // LR operator/(L, R);
3758 // LR operator+(L, R);
3759 // LR operator-(L, R);
3760 // bool operator<(L, R);
3761 // bool operator>(L, R);
3762 // bool operator<=(L, R);
3763 // bool operator>=(L, R);
3764 // bool operator==(L, R);
3765 // bool operator!=(L, R);
3766 //
3767 // where LR is the result of the usual arithmetic conversions
3768 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003769 //
3770 // C++ [over.built]p24:
3771 //
3772 // For every pair of promoted arithmetic types L and R, there exist
3773 // candidate operator functions of the form
3774 //
3775 // LR operator?(bool, L, R);
3776 //
3777 // where LR is the result of the usual arithmetic conversions
3778 // between types L and R.
3779 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003780 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003781 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003782 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003783 Right < LastPromotedArithmeticType; ++Right) {
3784 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003785 QualType Result
3786 = isComparison
3787 ? Context.BoolTy
3788 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003789 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3790 }
3791 }
3792 break;
3793
3794 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003795 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003796 case OO_Caret:
3797 case OO_Pipe:
3798 case OO_LessLess:
3799 case OO_GreaterGreater:
3800 // C++ [over.built]p17:
3801 //
3802 // For every pair of promoted integral types L and R, there
3803 // exist candidate operator functions of the form
3804 //
3805 // LR operator%(L, R);
3806 // LR operator&(L, R);
3807 // LR operator^(L, R);
3808 // LR operator|(L, R);
3809 // L operator<<(L, R);
3810 // L operator>>(L, R);
3811 //
3812 // where LR is the result of the usual arithmetic conversions
3813 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003814 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003815 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003816 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003817 Right < LastPromotedIntegralType; ++Right) {
3818 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3819 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3820 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003821 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003822 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3823 }
3824 }
3825 break;
3826
3827 case OO_Equal:
3828 // C++ [over.built]p20:
3829 //
3830 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003831 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003832 // empty, there exist candidate operator functions of the form
3833 //
3834 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003835 for (BuiltinCandidateTypeSet::iterator
3836 Enum = CandidateTypes.enumeration_begin(),
3837 EnumEnd = CandidateTypes.enumeration_end();
3838 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003839 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003840 CandidateSet);
3841 for (BuiltinCandidateTypeSet::iterator
3842 MemPtr = CandidateTypes.member_pointer_begin(),
3843 MemPtrEnd = CandidateTypes.member_pointer_end();
3844 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003845 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003846 CandidateSet);
3847 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003848
3849 case OO_PlusEqual:
3850 case OO_MinusEqual:
3851 // C++ [over.built]p19:
3852 //
3853 // For every pair (T, VQ), where T is any type and VQ is either
3854 // volatile or empty, there exist candidate operator functions
3855 // of the form
3856 //
3857 // T*VQ& operator=(T*VQ&, T*);
3858 //
3859 // C++ [over.built]p21:
3860 //
3861 // For every pair (T, VQ), where T is a cv-qualified or
3862 // cv-unqualified object type and VQ is either volatile or
3863 // empty, there exist candidate operator functions of the form
3864 //
3865 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3866 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3867 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3868 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3869 QualType ParamTypes[2];
3870 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3871
3872 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003873 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003874 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3875 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003876
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003877 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3878 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003879 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003880 ParamTypes[0]
3881 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003882 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3883 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003884 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003885 }
3886 // Fall through.
3887
3888 case OO_StarEqual:
3889 case OO_SlashEqual:
3890 // C++ [over.built]p18:
3891 //
3892 // For every triple (L, VQ, R), where L is an arithmetic type,
3893 // VQ is either volatile or empty, and R is a promoted
3894 // arithmetic type, there exist candidate operator functions of
3895 // the form
3896 //
3897 // VQ L& operator=(VQ L&, R);
3898 // VQ L& operator*=(VQ L&, R);
3899 // VQ L& operator/=(VQ L&, R);
3900 // VQ L& operator+=(VQ L&, R);
3901 // VQ L& operator-=(VQ L&, R);
3902 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003903 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003904 Right < LastPromotedArithmeticType; ++Right) {
3905 QualType ParamTypes[2];
3906 ParamTypes[1] = ArithmeticTypes[Right];
3907
3908 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003909 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003910 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3911 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003912
3913 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003914 if (VisibleTypeConversionsQuals.hasVolatile()) {
3915 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3916 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3917 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3918 /*IsAssigmentOperator=*/Op == OO_Equal);
3919 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003920 }
3921 }
3922 break;
3923
3924 case OO_PercentEqual:
3925 case OO_LessLessEqual:
3926 case OO_GreaterGreaterEqual:
3927 case OO_AmpEqual:
3928 case OO_CaretEqual:
3929 case OO_PipeEqual:
3930 // C++ [over.built]p22:
3931 //
3932 // For every triple (L, VQ, R), where L is an integral type, VQ
3933 // is either volatile or empty, and R is a promoted integral
3934 // type, there exist candidate operator functions of the form
3935 //
3936 // VQ L& operator%=(VQ L&, R);
3937 // VQ L& operator<<=(VQ L&, R);
3938 // VQ L& operator>>=(VQ L&, R);
3939 // VQ L& operator&=(VQ L&, R);
3940 // VQ L& operator^=(VQ L&, R);
3941 // VQ L& operator|=(VQ L&, R);
3942 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003943 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003944 Right < LastPromotedIntegralType; ++Right) {
3945 QualType ParamTypes[2];
3946 ParamTypes[1] = ArithmeticTypes[Right];
3947
3948 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003949 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003950 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003951 if (VisibleTypeConversionsQuals.hasVolatile()) {
3952 // Add this built-in operator as a candidate (VQ is 'volatile').
3953 ParamTypes[0] = ArithmeticTypes[Left];
3954 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3955 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3956 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3957 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003958 }
3959 }
3960 break;
3961
Douglas Gregord08452f2008-11-19 15:42:04 +00003962 case OO_Exclaim: {
3963 // C++ [over.operator]p23:
3964 //
3965 // There also exist candidate operator functions of the form
3966 //
Mike Stump11289f42009-09-09 15:08:12 +00003967 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003968 // bool operator&&(bool, bool); [BELOW]
3969 // bool operator||(bool, bool); [BELOW]
3970 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003971 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3972 /*IsAssignmentOperator=*/false,
3973 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003974 break;
3975 }
3976
Douglas Gregora11693b2008-11-12 17:17:38 +00003977 case OO_AmpAmp:
3978 case OO_PipePipe: {
3979 // C++ [over.operator]p23:
3980 //
3981 // There also exist candidate operator functions of the form
3982 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003983 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003984 // bool operator&&(bool, bool);
3985 // bool operator||(bool, bool);
3986 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003987 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3988 /*IsAssignmentOperator=*/false,
3989 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003990 break;
3991 }
3992
3993 case OO_Subscript:
3994 // C++ [over.built]p13:
3995 //
3996 // For every cv-qualified or cv-unqualified object type T there
3997 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003998 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003999 // T* operator+(T*, ptrdiff_t); [ABOVE]
4000 // T& operator[](T*, ptrdiff_t);
4001 // T* operator-(T*, ptrdiff_t); [ABOVE]
4002 // T* operator+(ptrdiff_t, T*); [ABOVE]
4003 // T& operator[](ptrdiff_t, T*);
4004 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4005 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4006 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004007 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004008 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004009
4010 // T& operator[](T*, ptrdiff_t)
4011 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4012
4013 // T& operator[](ptrdiff_t, T*);
4014 ParamTypes[0] = ParamTypes[1];
4015 ParamTypes[1] = *Ptr;
4016 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4017 }
4018 break;
4019
4020 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004021 // C++ [over.built]p11:
4022 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4023 // C1 is the same type as C2 or is a derived class of C2, T is an object
4024 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4025 // there exist candidate operator functions of the form
4026 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4027 // where CV12 is the union of CV1 and CV2.
4028 {
4029 for (BuiltinCandidateTypeSet::iterator Ptr =
4030 CandidateTypes.pointer_begin();
4031 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4032 QualType C1Ty = (*Ptr);
4033 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004034 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004035 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004036 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004037 if (!isa<RecordType>(C1))
4038 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004039 // heuristic to reduce number of builtin candidates in the set.
4040 // Add volatile/restrict version only if there are conversions to a
4041 // volatile/restrict type.
4042 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4043 continue;
4044 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4045 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004046 }
4047 for (BuiltinCandidateTypeSet::iterator
4048 MemPtr = CandidateTypes.member_pointer_begin(),
4049 MemPtrEnd = CandidateTypes.member_pointer_end();
4050 MemPtr != MemPtrEnd; ++MemPtr) {
4051 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4052 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004053 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004054 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4055 break;
4056 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4057 // build CV12 T&
4058 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004059 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4060 T.isVolatileQualified())
4061 continue;
4062 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4063 T.isRestrictQualified())
4064 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004065 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004066 QualType ResultTy = Context.getLValueReferenceType(T);
4067 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4068 }
4069 }
4070 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004071 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004072
4073 case OO_Conditional:
4074 // Note that we don't consider the first argument, since it has been
4075 // contextually converted to bool long ago. The candidates below are
4076 // therefore added as binary.
4077 //
4078 // C++ [over.built]p24:
4079 // For every type T, where T is a pointer or pointer-to-member type,
4080 // there exist candidate operator functions of the form
4081 //
4082 // T operator?(bool, T, T);
4083 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004084 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4085 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4086 QualType ParamTypes[2] = { *Ptr, *Ptr };
4087 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4088 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004089 for (BuiltinCandidateTypeSet::iterator Ptr =
4090 CandidateTypes.member_pointer_begin(),
4091 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4092 QualType ParamTypes[2] = { *Ptr, *Ptr };
4093 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4094 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004095 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004096 }
4097}
4098
Douglas Gregore254f902009-02-04 00:32:51 +00004099/// \brief Add function candidates found via argument-dependent lookup
4100/// to the set of overloading candidates.
4101///
4102/// This routine performs argument-dependent name lookup based on the
4103/// given function name (which may also be an operator name) and adds
4104/// all of the overload candidates found by ADL to the overload
4105/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004106void
Douglas Gregore254f902009-02-04 00:32:51 +00004107Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4108 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004109 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004110 OverloadCandidateSet& CandidateSet,
4111 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004112 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00004113
Douglas Gregorcabea402009-09-22 15:41:20 +00004114 // FIXME: Should we be trafficking in canonical function decls throughout?
4115
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004116 // Record all of the function candidates that we've already
4117 // added to the overload set, so that we don't add those same
4118 // candidates a second time.
4119 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4120 CandEnd = CandidateSet.end();
4121 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004122 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004123 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004124 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4125 Functions.insert(FunTmpl);
4126 }
Douglas Gregore254f902009-02-04 00:32:51 +00004127
Douglas Gregorcabea402009-09-22 15:41:20 +00004128 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00004129 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00004130
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004131 // Erase all of the candidates we already knew about.
4132 // FIXME: This is suboptimal. Is there a better way?
4133 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4134 CandEnd = CandidateSet.end();
4135 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004136 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004137 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004138 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4139 Functions.erase(FunTmpl);
4140 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004141
4142 // For each of the ADL candidates we found, add it to the overload
4143 // set.
4144 for (FunctionSet::iterator Func = Functions.begin(),
4145 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00004146 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004147 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCall6b51f282009-11-23 01:53:49 +00004148 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004149 continue;
4150
4151 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4152 false, false, PartialOverloading);
4153 } else
Mike Stump11289f42009-09-09 15:08:12 +00004154 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00004155 ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004156 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004157 }
Douglas Gregore254f902009-02-04 00:32:51 +00004158}
4159
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004160/// isBetterOverloadCandidate - Determines whether the first overload
4161/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004162bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004163Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00004164 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004165 // Define viable functions to be better candidates than non-viable
4166 // functions.
4167 if (!Cand2.Viable)
4168 return Cand1.Viable;
4169 else if (!Cand1.Viable)
4170 return false;
4171
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004172 // C++ [over.match.best]p1:
4173 //
4174 // -- if F is a static member function, ICS1(F) is defined such
4175 // that ICS1(F) is neither better nor worse than ICS1(G) for
4176 // any function G, and, symmetrically, ICS1(G) is neither
4177 // better nor worse than ICS1(F).
4178 unsigned StartArg = 0;
4179 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4180 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004181
Douglas Gregord3cb3562009-07-07 23:38:56 +00004182 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004183 // A viable function F1 is defined to be a better function than another
4184 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004185 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004186 unsigned NumArgs = Cand1.Conversions.size();
4187 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4188 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004189 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004190 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4191 Cand2.Conversions[ArgIdx])) {
4192 case ImplicitConversionSequence::Better:
4193 // Cand1 has a better conversion sequence.
4194 HasBetterConversion = true;
4195 break;
4196
4197 case ImplicitConversionSequence::Worse:
4198 // Cand1 can't be better than Cand2.
4199 return false;
4200
4201 case ImplicitConversionSequence::Indistinguishable:
4202 // Do nothing.
4203 break;
4204 }
4205 }
4206
Mike Stump11289f42009-09-09 15:08:12 +00004207 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004208 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004209 if (HasBetterConversion)
4210 return true;
4211
Mike Stump11289f42009-09-09 15:08:12 +00004212 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004213 // specialization, or, if not that,
4214 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4215 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4216 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004217
4218 // -- F1 and F2 are function template specializations, and the function
4219 // template for F1 is more specialized than the template for F2
4220 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004221 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004222 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4223 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004224 if (FunctionTemplateDecl *BetterTemplate
4225 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4226 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004227 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4228 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004229 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004230
Douglas Gregora1f013e2008-11-07 22:36:19 +00004231 // -- the context is an initialization by user-defined conversion
4232 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4233 // from the return type of F1 to the destination type (i.e.,
4234 // the type of the entity being initialized) is a better
4235 // conversion sequence than the standard conversion sequence
4236 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004237 if (Cand1.Function && Cand2.Function &&
4238 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004239 isa<CXXConversionDecl>(Cand2.Function)) {
4240 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4241 Cand2.FinalConversion)) {
4242 case ImplicitConversionSequence::Better:
4243 // Cand1 has a better conversion sequence.
4244 return true;
4245
4246 case ImplicitConversionSequence::Worse:
4247 // Cand1 can't be better than Cand2.
4248 return false;
4249
4250 case ImplicitConversionSequence::Indistinguishable:
4251 // Do nothing
4252 break;
4253 }
4254 }
4255
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004256 return false;
4257}
4258
Mike Stump11289f42009-09-09 15:08:12 +00004259/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004260/// within an overload candidate set.
4261///
4262/// \param CandidateSet the set of candidate functions.
4263///
4264/// \param Loc the location of the function name (or operator symbol) for
4265/// which overload resolution occurs.
4266///
Mike Stump11289f42009-09-09 15:08:12 +00004267/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004268/// function, Best points to the candidate function found.
4269///
4270/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004271OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4272 SourceLocation Loc,
4273 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004274 // Find the best viable function.
4275 Best = CandidateSet.end();
4276 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4277 Cand != CandidateSet.end(); ++Cand) {
4278 if (Cand->Viable) {
4279 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4280 Best = Cand;
4281 }
4282 }
4283
4284 // If we didn't find any viable functions, abort.
4285 if (Best == CandidateSet.end())
4286 return OR_No_Viable_Function;
4287
4288 // Make sure that this function is better than every other viable
4289 // function. If not, we have an ambiguity.
4290 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4291 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004292 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004293 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004294 !isBetterOverloadCandidate(*Best, *Cand)) {
4295 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004296 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004297 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004298 }
Mike Stump11289f42009-09-09 15:08:12 +00004299
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004300 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004301 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004302 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004303 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004304 return OR_Deleted;
4305
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004306 // C++ [basic.def.odr]p2:
4307 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004308 // when referred to from a potentially-evaluated expression. [Note: this
4309 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004310 // (clause 13), user-defined conversions (12.3.2), allocation function for
4311 // placement new (5.3.4), as well as non-default initialization (8.5).
4312 if (Best->Function)
4313 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004314 return OR_Success;
4315}
4316
John McCall53262c92010-01-12 02:15:36 +00004317namespace {
4318
4319enum OverloadCandidateKind {
4320 oc_function,
4321 oc_method,
4322 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004323 oc_function_template,
4324 oc_method_template,
4325 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004326 oc_implicit_default_constructor,
4327 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004328 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004329};
4330
John McCalle1ac8d12010-01-13 00:25:19 +00004331OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4332 FunctionDecl *Fn,
4333 std::string &Description) {
4334 bool isTemplate = false;
4335
4336 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4337 isTemplate = true;
4338 Description = S.getTemplateArgumentBindingsText(
4339 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4340 }
John McCallfd0b2f82010-01-06 09:43:14 +00004341
4342 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004343 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004344 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004345
John McCall53262c92010-01-12 02:15:36 +00004346 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4347 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004348 }
4349
4350 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4351 // This actually gets spelled 'candidate function' for now, but
4352 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004353 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004354 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004355
4356 assert(Meth->isCopyAssignment()
4357 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004358 return oc_implicit_copy_assignment;
4359 }
4360
John McCalle1ac8d12010-01-13 00:25:19 +00004361 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004362}
4363
4364} // end anonymous namespace
4365
4366// Notes the location of an overload candidate.
4367void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004368 std::string FnDesc;
4369 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4370 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4371 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004372}
4373
John McCall0d1da222010-01-12 00:44:57 +00004374/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4375/// "lead" diagnostic; it will be given two arguments, the source and
4376/// target types of the conversion.
4377void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4378 SourceLocation CaretLoc,
4379 const PartialDiagnostic &PDiag) {
4380 Diag(CaretLoc, PDiag)
4381 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4382 for (AmbiguousConversionSequence::const_iterator
4383 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4384 NoteOverloadCandidate(*I);
4385 }
John McCall12f97bc2010-01-08 04:41:39 +00004386}
4387
John McCall0d1da222010-01-12 00:44:57 +00004388namespace {
4389
John McCall6a61b522010-01-13 09:16:55 +00004390void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4391 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4392 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004393 assert(Cand->Function && "for now, candidate must be a function");
4394 FunctionDecl *Fn = Cand->Function;
4395
4396 // There's a conversion slot for the object argument if this is a
4397 // non-constructor method. Note that 'I' corresponds the
4398 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004399 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004400 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004401 if (I == 0)
4402 isObjectArgument = true;
4403 else
4404 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004405 }
4406
John McCalle1ac8d12010-01-13 00:25:19 +00004407 std::string FnDesc;
4408 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4409
John McCall6a61b522010-01-13 09:16:55 +00004410 Expr *FromExpr = Conv.Bad.FromExpr;
4411 QualType FromTy = Conv.Bad.getFromType();
4412 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004413
John McCall47000992010-01-14 03:28:57 +00004414 // Do some hand-waving analysis to see if the non-viability is due to a
4415 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4416 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4417 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4418 CToTy = RT->getPointeeType();
4419 else {
4420 // TODO: detect and diagnose the full richness of const mismatches.
4421 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4422 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4423 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4424 }
4425
4426 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4427 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4428 // It is dumb that we have to do this here.
4429 while (isa<ArrayType>(CFromTy))
4430 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4431 while (isa<ArrayType>(CToTy))
4432 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4433
4434 Qualifiers FromQs = CFromTy.getQualifiers();
4435 Qualifiers ToQs = CToTy.getQualifiers();
4436
4437 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4438 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4439 << (unsigned) FnKind << FnDesc
4440 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4441 << FromTy
4442 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4443 << (unsigned) isObjectArgument << I+1;
4444 return;
4445 }
4446
4447 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4448 assert(CVR && "unexpected qualifiers mismatch");
4449
4450 if (isObjectArgument) {
4451 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4452 << (unsigned) FnKind << FnDesc
4453 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4454 << FromTy << (CVR - 1);
4455 } else {
4456 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4457 << (unsigned) FnKind << FnDesc
4458 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4459 << FromTy << (CVR - 1) << I+1;
4460 }
4461 return;
4462 }
4463
4464 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004465 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4466 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004467 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004468 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004469}
4470
4471void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4472 unsigned NumFormalArgs) {
4473 // TODO: treat calls to a missing default constructor as a special case
4474
4475 FunctionDecl *Fn = Cand->Function;
4476 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4477
4478 unsigned MinParams = Fn->getMinRequiredArguments();
4479
4480 // at least / at most / exactly
4481 unsigned mode, modeCount;
4482 if (NumFormalArgs < MinParams) {
4483 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4484 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4485 mode = 0; // "at least"
4486 else
4487 mode = 2; // "exactly"
4488 modeCount = MinParams;
4489 } else {
4490 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4491 if (MinParams != FnTy->getNumArgs())
4492 mode = 1; // "at most"
4493 else
4494 mode = 2; // "exactly"
4495 modeCount = FnTy->getNumArgs();
4496 }
4497
4498 std::string Description;
4499 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4500
4501 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4502 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004503}
4504
4505void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4506 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004507 FunctionDecl *Fn = Cand->Function;
4508
John McCall12f97bc2010-01-08 04:41:39 +00004509 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004510 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004511 std::string FnDesc;
4512 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004513
4514 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004515 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004516 return;
John McCall12f97bc2010-01-08 04:41:39 +00004517 }
4518
John McCalle1ac8d12010-01-13 00:25:19 +00004519 // We don't really have anything else to say about viable candidates.
4520 if (Cand->Viable) {
4521 S.NoteOverloadCandidate(Fn);
4522 return;
4523 }
John McCall0d1da222010-01-12 00:44:57 +00004524
John McCall6a61b522010-01-13 09:16:55 +00004525 switch (Cand->FailureKind) {
4526 case ovl_fail_too_many_arguments:
4527 case ovl_fail_too_few_arguments:
4528 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004529
John McCall6a61b522010-01-13 09:16:55 +00004530 case ovl_fail_bad_deduction:
4531 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004532
John McCall6a61b522010-01-13 09:16:55 +00004533 case ovl_fail_bad_conversion:
4534 for (unsigned I = 0, N = Cand->Conversions.size(); I != N; ++I)
4535 if (Cand->Conversions[I].isBad())
4536 return DiagnoseBadConversion(S, Cand, I);
4537
4538 // FIXME: this currently happens when we're called from SemaInit
4539 // when user-conversion overload fails. Figure out how to handle
4540 // those conditions and diagnose them well.
4541 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004542 }
John McCalld3224162010-01-08 00:58:21 +00004543}
4544
4545void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4546 // Desugar the type of the surrogate down to a function type,
4547 // retaining as many typedefs as possible while still showing
4548 // the function type (and, therefore, its parameter types).
4549 QualType FnType = Cand->Surrogate->getConversionType();
4550 bool isLValueReference = false;
4551 bool isRValueReference = false;
4552 bool isPointer = false;
4553 if (const LValueReferenceType *FnTypeRef =
4554 FnType->getAs<LValueReferenceType>()) {
4555 FnType = FnTypeRef->getPointeeType();
4556 isLValueReference = true;
4557 } else if (const RValueReferenceType *FnTypeRef =
4558 FnType->getAs<RValueReferenceType>()) {
4559 FnType = FnTypeRef->getPointeeType();
4560 isRValueReference = true;
4561 }
4562 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4563 FnType = FnTypePtr->getPointeeType();
4564 isPointer = true;
4565 }
4566 // Desugar down to a function type.
4567 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4568 // Reconstruct the pointer/reference as appropriate.
4569 if (isPointer) FnType = S.Context.getPointerType(FnType);
4570 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4571 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4572
4573 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4574 << FnType;
4575}
4576
4577void NoteBuiltinOperatorCandidate(Sema &S,
4578 const char *Opc,
4579 SourceLocation OpLoc,
4580 OverloadCandidate *Cand) {
4581 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4582 std::string TypeStr("operator");
4583 TypeStr += Opc;
4584 TypeStr += "(";
4585 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4586 if (Cand->Conversions.size() == 1) {
4587 TypeStr += ")";
4588 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4589 } else {
4590 TypeStr += ", ";
4591 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4592 TypeStr += ")";
4593 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4594 }
4595}
4596
4597void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4598 OverloadCandidate *Cand) {
4599 unsigned NoOperands = Cand->Conversions.size();
4600 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4601 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00004602 if (ICS.isBad()) break; // all meaningless after first invalid
4603 if (!ICS.isAmbiguous()) continue;
4604
4605 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4606 PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00004607 }
4608}
4609
John McCall3712d9e2010-01-15 23:32:50 +00004610SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4611 if (Cand->Function)
4612 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00004613 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00004614 return Cand->Surrogate->getLocation();
4615 return SourceLocation();
4616}
4617
John McCallad2587a2010-01-12 00:48:53 +00004618struct CompareOverloadCandidatesForDisplay {
4619 Sema &S;
4620 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00004621
4622 bool operator()(const OverloadCandidate *L,
4623 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00004624 // Fast-path this check.
4625 if (L == R) return false;
4626
John McCall12f97bc2010-01-08 04:41:39 +00004627 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00004628 if (L->Viable) {
4629 if (!R->Viable) return true;
4630
4631 // TODO: introduce a tri-valued comparison for overload
4632 // candidates. Would be more worthwhile if we had a sort
4633 // that could exploit it.
4634 if (S.isBetterOverloadCandidate(*L, *R)) return true;
4635 if (S.isBetterOverloadCandidate(*R, *L)) return false;
4636 } else if (R->Viable)
4637 return false;
John McCall12f97bc2010-01-08 04:41:39 +00004638
John McCall3712d9e2010-01-15 23:32:50 +00004639 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00004640
John McCall3712d9e2010-01-15 23:32:50 +00004641 // Criteria by which we can sort non-viable candidates:
4642 if (!L->Viable) {
4643 // 1. Arity mismatches come after other candidates.
4644 if (L->FailureKind == ovl_fail_too_many_arguments ||
4645 L->FailureKind == ovl_fail_too_few_arguments)
4646 return false;
4647 if (R->FailureKind == ovl_fail_too_many_arguments ||
4648 R->FailureKind == ovl_fail_too_few_arguments)
4649 return true;
John McCall12f97bc2010-01-08 04:41:39 +00004650
John McCall3712d9e2010-01-15 23:32:50 +00004651 // TODO: others?
4652 }
4653
4654 // Sort everything else by location.
4655 SourceLocation LLoc = GetLocationForCandidate(L);
4656 SourceLocation RLoc = GetLocationForCandidate(R);
4657
4658 // Put candidates without locations (e.g. builtins) at the end.
4659 if (LLoc.isInvalid()) return false;
4660 if (RLoc.isInvalid()) return true;
4661
4662 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00004663 }
4664};
4665
John McCalld3224162010-01-08 00:58:21 +00004666} // end anonymous namespace
4667
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004668/// PrintOverloadCandidates - When overload resolution fails, prints
4669/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00004670/// set.
Mike Stump11289f42009-09-09 15:08:12 +00004671void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004672Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00004673 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00004674 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004675 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004676 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00004677 // Sort the candidates by viability and position. Sorting directly would
4678 // be prohibitive, so we make a set of pointers and sort those.
4679 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4680 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4681 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4682 LastCand = CandidateSet.end();
4683 Cand != LastCand; ++Cand)
4684 if (Cand->Viable || OCD == OCD_AllCandidates)
4685 Cands.push_back(Cand);
John McCallad2587a2010-01-12 00:48:53 +00004686 std::sort(Cands.begin(), Cands.end(),
4687 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00004688
John McCall0d1da222010-01-12 00:44:57 +00004689 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00004690
John McCall12f97bc2010-01-08 04:41:39 +00004691 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4692 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4693 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004694
John McCalld3224162010-01-08 00:58:21 +00004695 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00004696 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00004697 else if (Cand->IsSurrogate)
4698 NoteSurrogateCandidate(*this, Cand);
4699
4700 // This a builtin candidate. We do not, in general, want to list
4701 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00004702 else if (Cand->Viable) {
4703 // Generally we only see ambiguities including viable builtin
4704 // operators if overload resolution got screwed up by an
4705 // ambiguous user-defined conversion.
4706 //
4707 // FIXME: It's quite possible for different conversions to see
4708 // different ambiguities, though.
4709 if (!ReportedAmbiguousConversions) {
4710 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4711 ReportedAmbiguousConversions = true;
4712 }
John McCalld3224162010-01-08 00:58:21 +00004713
John McCall0d1da222010-01-12 00:44:57 +00004714 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00004715 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00004716 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004717 }
4718}
4719
Douglas Gregorcd695e52008-11-10 20:40:00 +00004720/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4721/// an overloaded function (C++ [over.over]), where @p From is an
4722/// expression with overloaded function type and @p ToType is the type
4723/// we're trying to resolve to. For example:
4724///
4725/// @code
4726/// int f(double);
4727/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004728///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004729/// int (*pfd)(double) = f; // selects f(double)
4730/// @endcode
4731///
4732/// This routine returns the resulting FunctionDecl if it could be
4733/// resolved, and NULL otherwise. When @p Complain is true, this
4734/// routine will emit diagnostics if there is an error.
4735FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004736Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004737 bool Complain) {
4738 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004739 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004740 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004741 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004742 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004743 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004744 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004745 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004746 FunctionType = MemTypePtr->getPointeeType();
4747 IsMember = true;
4748 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004749
4750 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004751 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004752 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004753 return 0;
4754
4755 // Find the actual overloaded function declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004756
Douglas Gregorcd695e52008-11-10 20:40:00 +00004757 // C++ [over.over]p1:
4758 // [...] [Note: any redundant set of parentheses surrounding the
4759 // overloaded function name is ignored (5.1). ]
4760 Expr *OvlExpr = From->IgnoreParens();
4761
4762 // C++ [over.over]p1:
4763 // [...] The overloaded function name can be preceded by the &
4764 // operator.
4765 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4766 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4767 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4768 }
4769
Anders Carlssonb68b0282009-10-20 22:53:47 +00004770 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004771 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCalld14a8642009-11-21 08:51:07 +00004772
4773 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004774
John McCall10eae182009-11-30 22:42:35 +00004775 // Look into the overloaded expression.
John McCalle66edc12009-11-24 19:00:30 +00004776 if (UnresolvedLookupExpr *UL
John McCalld14a8642009-11-21 08:51:07 +00004777 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4778 Fns.append(UL->decls_begin(), UL->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00004779 if (UL->hasExplicitTemplateArgs()) {
4780 HasExplicitTemplateArgs = true;
4781 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4782 }
John McCall10eae182009-11-30 22:42:35 +00004783 } else if (UnresolvedMemberExpr *ME
4784 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4785 Fns.append(ME->decls_begin(), ME->decls_end());
4786 if (ME->hasExplicitTemplateArgs()) {
4787 HasExplicitTemplateArgs = true;
John McCall6b51f282009-11-23 01:53:49 +00004788 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004789 }
Douglas Gregor9b146582009-07-08 20:55:45 +00004790 }
Mike Stump11289f42009-09-09 15:08:12 +00004791
John McCalld14a8642009-11-21 08:51:07 +00004792 // If we didn't actually find anything, we're done.
4793 if (Fns.empty())
4794 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004795
Douglas Gregorcd695e52008-11-10 20:40:00 +00004796 // Look through all of the overloaded functions, searching for one
4797 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004798 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004799 bool FoundNonTemplateFunction = false;
John McCalld14a8642009-11-21 08:51:07 +00004800 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4801 E = Fns.end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004802 // Look through any using declarations to find the underlying function.
4803 NamedDecl *Fn = (*I)->getUnderlyingDecl();
4804
Douglas Gregorcd695e52008-11-10 20:40:00 +00004805 // C++ [over.over]p3:
4806 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004807 // targets of type "pointer-to-function" or "reference-to-function."
4808 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004809 // type "pointer-to-member-function."
4810 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004811
Mike Stump11289f42009-09-09 15:08:12 +00004812 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004813 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00004814 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004815 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004816 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004817 // static when converting to member pointer.
4818 if (Method->isStatic() == IsMember)
4819 continue;
4820 } else if (IsMember)
4821 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004822
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004823 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004824 // If the name is a function template, template argument deduction is
4825 // done (14.8.2.2), and if the argument deduction succeeds, the
4826 // resulting template argument list is used to generate a single
4827 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004828 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004829 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004830 FunctionDecl *Specialization = 0;
4831 TemplateDeductionInfo Info(Context);
4832 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004833 = DeduceTemplateArguments(FunctionTemplate,
4834 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor9b146582009-07-08 20:55:45 +00004835 FunctionType, Specialization, Info)) {
4836 // FIXME: make a note of the failed deduction for diagnostics.
4837 (void)Result;
4838 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004839 // FIXME: If the match isn't exact, shouldn't we just drop this as
4840 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004841 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004842 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004843 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004844 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004845 }
John McCalld14a8642009-11-21 08:51:07 +00004846
4847 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00004848 }
Mike Stump11289f42009-09-09 15:08:12 +00004849
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004850 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004851 // Skip non-static functions when converting to pointer, and static
4852 // when converting to member pointer.
4853 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004854 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004855
4856 // If we have explicit template arguments, skip non-templates.
4857 if (HasExplicitTemplateArgs)
4858 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004859 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004860 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004861
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004862 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00004863 QualType ResultTy;
4864 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4865 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4866 ResultTy)) {
John McCalld14a8642009-11-21 08:51:07 +00004867 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004868 FoundNonTemplateFunction = true;
4869 }
Mike Stump11289f42009-09-09 15:08:12 +00004870 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004871 }
4872
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004873 // If there were 0 or 1 matches, we're done.
4874 if (Matches.empty())
4875 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004876 else if (Matches.size() == 1) {
4877 FunctionDecl *Result = *Matches.begin();
4878 MarkDeclarationReferenced(From->getLocStart(), Result);
4879 return Result;
4880 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004881
4882 // C++ [over.over]p4:
4883 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004884 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004885 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004886 // [...] and any given function template specialization F1 is
4887 // eliminated if the set contains a second function template
4888 // specialization whose function template is more specialized
4889 // than the function template of F1 according to the partial
4890 // ordering rules of 14.5.5.2.
4891
4892 // The algorithm specified above is quadratic. We instead use a
4893 // two-pass algorithm (similar to the one used to identify the
4894 // best viable function in an overload set) that identifies the
4895 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004896 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004897 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004898 FunctionDecl *Result =
4899 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4900 TPOC_Other, From->getLocStart(),
4901 PDiag(),
4902 PDiag(diag::err_addr_ovl_ambiguous)
4903 << TemplateMatches[0]->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00004904 PDiag(diag::note_ovl_candidate)
4905 << (unsigned) oc_function_template);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004906 MarkDeclarationReferenced(From->getLocStart(), Result);
4907 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004908 }
Mike Stump11289f42009-09-09 15:08:12 +00004909
Douglas Gregorfae1d712009-09-26 03:56:17 +00004910 // [...] any function template specializations in the set are
4911 // eliminated if the set also contains a non-template function, [...]
4912 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4913 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4914 if ((*M)->getPrimaryTemplate() == 0)
4915 RemainingMatches.push_back(*M);
4916
Mike Stump11289f42009-09-09 15:08:12 +00004917 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004918 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004919 if (RemainingMatches.size() == 1) {
4920 FunctionDecl *Result = RemainingMatches.front();
4921 MarkDeclarationReferenced(From->getLocStart(), Result);
4922 return Result;
4923 }
Mike Stump11289f42009-09-09 15:08:12 +00004924
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004925 // FIXME: We should probably return the same thing that BestViableFunction
4926 // returns (even if we issue the diagnostics here).
4927 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4928 << RemainingMatches[0]->getDeclName();
4929 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
John McCallfd0b2f82010-01-06 09:43:14 +00004930 NoteOverloadCandidate(RemainingMatches[I]);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004931 return 0;
4932}
4933
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004934/// \brief Given an expression that refers to an overloaded function, try to
4935/// resolve that overloaded function expression down to a single function.
4936///
4937/// This routine can only resolve template-ids that refer to a single function
4938/// template, where that template-id refers to a single template whose template
4939/// arguments are either provided by the template-id or have defaults,
4940/// as described in C++0x [temp.arg.explicit]p3.
4941FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
4942 // C++ [over.over]p1:
4943 // [...] [Note: any redundant set of parentheses surrounding the
4944 // overloaded function name is ignored (5.1). ]
4945 Expr *OvlExpr = From->IgnoreParens();
4946
4947 // C++ [over.over]p1:
4948 // [...] The overloaded function name can be preceded by the &
4949 // operator.
4950 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4951 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4952 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4953 }
4954
4955 bool HasExplicitTemplateArgs = false;
4956 TemplateArgumentListInfo ExplicitTemplateArgs;
4957
4958 llvm::SmallVector<NamedDecl*,8> Fns;
4959
4960 // Look into the overloaded expression.
4961 if (UnresolvedLookupExpr *UL
4962 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4963 Fns.append(UL->decls_begin(), UL->decls_end());
4964 if (UL->hasExplicitTemplateArgs()) {
4965 HasExplicitTemplateArgs = true;
4966 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4967 }
4968 } else if (UnresolvedMemberExpr *ME
4969 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4970 Fns.append(ME->decls_begin(), ME->decls_end());
4971 if (ME->hasExplicitTemplateArgs()) {
4972 HasExplicitTemplateArgs = true;
4973 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4974 }
4975 }
4976
4977 // If we didn't actually find any template-ids, we're done.
4978 if (Fns.empty() || !HasExplicitTemplateArgs)
4979 return 0;
4980
4981 // Look through all of the overloaded functions, searching for one
4982 // whose type matches exactly.
4983 FunctionDecl *Matched = 0;
4984 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4985 E = Fns.end(); I != E; ++I) {
4986 // C++0x [temp.arg.explicit]p3:
4987 // [...] In contexts where deduction is done and fails, or in contexts
4988 // where deduction is not done, if a template argument list is
4989 // specified and it, along with any default template arguments,
4990 // identifies a single function template specialization, then the
4991 // template-id is an lvalue for the function template specialization.
4992 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
4993
4994 // C++ [over.over]p2:
4995 // If the name is a function template, template argument deduction is
4996 // done (14.8.2.2), and if the argument deduction succeeds, the
4997 // resulting template argument list is used to generate a single
4998 // function template specialization, which is added to the set of
4999 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005000 FunctionDecl *Specialization = 0;
5001 TemplateDeductionInfo Info(Context);
5002 if (TemplateDeductionResult Result
5003 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5004 Specialization, Info)) {
5005 // FIXME: make a note of the failed deduction for diagnostics.
5006 (void)Result;
5007 continue;
5008 }
5009
5010 // Multiple matches; we can't resolve to a single declaration.
5011 if (Matched)
5012 return 0;
5013
5014 Matched = Specialization;
5015 }
5016
5017 return Matched;
5018}
5019
Douglas Gregorcabea402009-09-22 15:41:20 +00005020/// \brief Add a single candidate to the overload set.
5021static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00005022 NamedDecl *Callee,
John McCall6b51f282009-11-23 01:53:49 +00005023 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005024 Expr **Args, unsigned NumArgs,
5025 OverloadCandidateSet &CandidateSet,
5026 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005027 if (isa<UsingShadowDecl>(Callee))
5028 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5029
Douglas Gregorcabea402009-09-22 15:41:20 +00005030 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005031 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorcabea402009-09-22 15:41:20 +00005032 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
5033 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005034 return;
John McCalld14a8642009-11-21 08:51:07 +00005035 }
5036
5037 if (FunctionTemplateDecl *FuncTemplate
5038 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005039 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005040 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005041 return;
5042 }
5043
5044 assert(false && "unhandled case in overloaded call candidate");
5045
5046 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005047}
5048
5049/// \brief Add the overload candidates named by callee and/or found by argument
5050/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005051void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005052 Expr **Args, unsigned NumArgs,
5053 OverloadCandidateSet &CandidateSet,
5054 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005055
5056#ifndef NDEBUG
5057 // Verify that ArgumentDependentLookup is consistent with the rules
5058 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005059 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005060 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5061 // and let Y be the lookup set produced by argument dependent
5062 // lookup (defined as follows). If X contains
5063 //
5064 // -- a declaration of a class member, or
5065 //
5066 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005067 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005068 //
5069 // -- a declaration that is neither a function or a function
5070 // template
5071 //
5072 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005073
John McCall57500772009-12-16 12:17:52 +00005074 if (ULE->requiresADL()) {
5075 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5076 E = ULE->decls_end(); I != E; ++I) {
5077 assert(!(*I)->getDeclContext()->isRecord());
5078 assert(isa<UsingShadowDecl>(*I) ||
5079 !(*I)->getDeclContext()->isFunctionOrMethod());
5080 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005081 }
5082 }
5083#endif
5084
John McCall57500772009-12-16 12:17:52 +00005085 // It would be nice to avoid this copy.
5086 TemplateArgumentListInfo TABuffer;
5087 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5088 if (ULE->hasExplicitTemplateArgs()) {
5089 ULE->copyTemplateArgumentsInto(TABuffer);
5090 ExplicitTemplateArgs = &TABuffer;
5091 }
5092
5093 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5094 E = ULE->decls_end(); I != E; ++I)
John McCall6b51f282009-11-23 01:53:49 +00005095 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005096 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005097 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005098
John McCall57500772009-12-16 12:17:52 +00005099 if (ULE->requiresADL())
5100 AddArgumentDependentLookupCandidates(ULE->getName(), Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005101 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005102 CandidateSet,
5103 PartialOverloading);
5104}
John McCalld681c392009-12-16 08:11:27 +00005105
John McCall57500772009-12-16 12:17:52 +00005106static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5107 Expr **Args, unsigned NumArgs) {
5108 Fn->Destroy(SemaRef.Context);
5109 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5110 Args[Arg]->Destroy(SemaRef.Context);
5111 return SemaRef.ExprError();
5112}
5113
John McCalld681c392009-12-16 08:11:27 +00005114/// Attempts to recover from a call where no functions were found.
5115///
5116/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005117static Sema::OwningExprResult
5118BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5119 UnresolvedLookupExpr *ULE,
5120 SourceLocation LParenLoc,
5121 Expr **Args, unsigned NumArgs,
5122 SourceLocation *CommaLocs,
5123 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005124
5125 CXXScopeSpec SS;
5126 if (ULE->getQualifier()) {
5127 SS.setScopeRep(ULE->getQualifier());
5128 SS.setRange(ULE->getQualifierRange());
5129 }
5130
John McCall57500772009-12-16 12:17:52 +00005131 TemplateArgumentListInfo TABuffer;
5132 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5133 if (ULE->hasExplicitTemplateArgs()) {
5134 ULE->copyTemplateArgumentsInto(TABuffer);
5135 ExplicitTemplateArgs = &TABuffer;
5136 }
5137
John McCalld681c392009-12-16 08:11:27 +00005138 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5139 Sema::LookupOrdinaryName);
Douglas Gregor598b08f2009-12-31 05:20:13 +00005140 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall57500772009-12-16 12:17:52 +00005141 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005142
John McCall57500772009-12-16 12:17:52 +00005143 assert(!R.empty() && "lookup results empty despite recovery");
5144
5145 // Build an implicit member call if appropriate. Just drop the
5146 // casts and such from the call, we don't really care.
5147 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5148 if ((*R.begin())->isCXXClassMember())
5149 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5150 else if (ExplicitTemplateArgs)
5151 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5152 else
5153 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5154
5155 if (NewFn.isInvalid())
5156 return Destroy(SemaRef, Fn, Args, NumArgs);
5157
5158 Fn->Destroy(SemaRef.Context);
5159
5160 // This shouldn't cause an infinite loop because we're giving it
5161 // an expression with non-empty lookup results, which should never
5162 // end up here.
5163 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5164 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5165 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005166}
Douglas Gregorcabea402009-09-22 15:41:20 +00005167
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005168/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005169/// (which eventually refers to the declaration Func) and the call
5170/// arguments Args/NumArgs, attempt to resolve the function call down
5171/// to a specific function. If overload resolution succeeds, returns
5172/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005173/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005174/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005175Sema::OwningExprResult
5176Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5177 SourceLocation LParenLoc,
5178 Expr **Args, unsigned NumArgs,
5179 SourceLocation *CommaLocs,
5180 SourceLocation RParenLoc) {
5181#ifndef NDEBUG
5182 if (ULE->requiresADL()) {
5183 // To do ADL, we must have found an unqualified name.
5184 assert(!ULE->getQualifier() && "qualified name with ADL");
5185
5186 // We don't perform ADL for implicit declarations of builtins.
5187 // Verify that this was correctly set up.
5188 FunctionDecl *F;
5189 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5190 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5191 F->getBuiltinID() && F->isImplicit())
5192 assert(0 && "performing ADL for builtin");
5193
5194 // We don't perform ADL in C.
5195 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5196 }
5197#endif
5198
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005199 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005200
John McCall57500772009-12-16 12:17:52 +00005201 // Add the functions denoted by the callee to the set of candidate
5202 // functions, including those from argument-dependent lookup.
5203 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005204
5205 // If we found nothing, try to recover.
5206 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5207 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005208 if (CandidateSet.empty())
5209 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5210 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005211
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005212 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005213 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005214 case OR_Success: {
5215 FunctionDecl *FDecl = Best->Function;
5216 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5217 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5218 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005219
5220 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005221 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005222 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005223 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005224 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005225 break;
5226
5227 case OR_Ambiguous:
5228 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005229 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005230 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005231 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005232
5233 case OR_Deleted:
5234 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5235 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005236 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005237 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005238 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005239 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005240 }
5241
5242 // Overload resolution failed. Destroy all of the subexpressions and
5243 // return NULL.
5244 Fn->Destroy(Context);
5245 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5246 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005247 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005248}
5249
John McCall283b9012009-11-22 00:44:51 +00005250static bool IsOverloaded(const Sema::FunctionSet &Functions) {
5251 return Functions.size() > 1 ||
5252 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5253}
5254
Douglas Gregor084d8552009-03-13 23:49:33 +00005255/// \brief Create a unary operation that may resolve to an overloaded
5256/// operator.
5257///
5258/// \param OpLoc The location of the operator itself (e.g., '*').
5259///
5260/// \param OpcIn The UnaryOperator::Opcode that describes this
5261/// operator.
5262///
5263/// \param Functions The set of non-member functions that will be
5264/// considered by overload resolution. The caller needs to build this
5265/// set based on the context using, e.g.,
5266/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5267/// set should not contain any member functions; those will be added
5268/// by CreateOverloadedUnaryOp().
5269///
5270/// \param input The input argument.
5271Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
5272 unsigned OpcIn,
5273 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00005274 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005275 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5276 Expr *Input = (Expr *)input.get();
5277
5278 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5279 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5280 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5281
5282 Expr *Args[2] = { Input, 0 };
5283 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005284
Douglas Gregor084d8552009-03-13 23:49:33 +00005285 // For post-increment and post-decrement, add the implicit '0' as
5286 // the second argument, so that we know this is a post-increment or
5287 // post-decrement.
5288 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5289 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005290 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005291 SourceLocation());
5292 NumArgs = 2;
5293 }
5294
5295 if (Input->isTypeDependent()) {
John McCalld14a8642009-11-21 08:51:07 +00005296 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005297 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5298 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00005299 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump11289f42009-09-09 15:08:12 +00005300 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00005301 FuncEnd = Functions.end();
5302 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00005303 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00005304
Douglas Gregor084d8552009-03-13 23:49:33 +00005305 input.release();
5306 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5307 &Args[0], NumArgs,
5308 Context.DependentTy,
5309 OpLoc));
5310 }
5311
5312 // Build an empty overload set.
5313 OverloadCandidateSet CandidateSet;
5314
5315 // Add the candidates from the given function set.
5316 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
5317
5318 // Add operator candidates that are member functions.
5319 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5320
5321 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005322 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005323
5324 // Perform overload resolution.
5325 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005326 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005327 case OR_Success: {
5328 // We found a built-in operator or an overloaded operator.
5329 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005330
Douglas Gregor084d8552009-03-13 23:49:33 +00005331 if (FnDecl) {
5332 // We matched an overloaded operator. Build a call to that
5333 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005334
Douglas Gregor084d8552009-03-13 23:49:33 +00005335 // Convert the arguments.
5336 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
5337 if (PerformObjectArgumentInitialization(Input, Method))
5338 return ExprError();
5339 } else {
5340 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005341 OwningExprResult InputInit
5342 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005343 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005344 SourceLocation(),
5345 move(input));
5346 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005347 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005348
Douglas Gregore6600372009-12-23 17:40:29 +00005349 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005350 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005351 }
5352
5353 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005354 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005355
Douglas Gregor084d8552009-03-13 23:49:33 +00005356 // Build the actual expression node.
5357 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5358 SourceLocation());
5359 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005360
Douglas Gregor084d8552009-03-13 23:49:33 +00005361 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005362 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005363 ExprOwningPtr<CallExpr> TheCall(this,
5364 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005365 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005366
5367 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5368 FnDecl))
5369 return ExprError();
5370
5371 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005372 } else {
5373 // We matched a built-in operator. Convert the arguments, then
5374 // break out so that we will build the appropriate built-in
5375 // operator node.
5376 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005377 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005378 return ExprError();
5379
5380 break;
5381 }
5382 }
5383
5384 case OR_No_Viable_Function:
5385 // No viable function; fall through to handling this as a
5386 // built-in operator, which will produce an error message for us.
5387 break;
5388
5389 case OR_Ambiguous:
5390 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5391 << UnaryOperator::getOpcodeStr(Opc)
5392 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005393 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005394 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005395 return ExprError();
5396
5397 case OR_Deleted:
5398 Diag(OpLoc, diag::err_ovl_deleted_oper)
5399 << Best->Function->isDeleted()
5400 << UnaryOperator::getOpcodeStr(Opc)
5401 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005402 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005403 return ExprError();
5404 }
5405
5406 // Either we found no viable overloaded operator or we matched a
5407 // built-in operator. In either case, fall through to trying to
5408 // build a built-in operation.
5409 input.release();
5410 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5411}
5412
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005413/// \brief Create a binary operation that may resolve to an overloaded
5414/// operator.
5415///
5416/// \param OpLoc The location of the operator itself (e.g., '+').
5417///
5418/// \param OpcIn The BinaryOperator::Opcode that describes this
5419/// operator.
5420///
5421/// \param Functions The set of non-member functions that will be
5422/// considered by overload resolution. The caller needs to build this
5423/// set based on the context using, e.g.,
5424/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5425/// set should not contain any member functions; those will be added
5426/// by CreateOverloadedBinOp().
5427///
5428/// \param LHS Left-hand argument.
5429/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005430Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005431Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005432 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005433 FunctionSet &Functions,
5434 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005435 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005436 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005437
5438 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5439 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5440 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5441
5442 // If either side is type-dependent, create an appropriate dependent
5443 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005444 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005445 if (Functions.empty()) {
5446 // If there are no functions to store, just build a dependent
5447 // BinaryOperator or CompoundAssignment.
5448 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5449 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5450 Context.DependentTy, OpLoc));
5451
5452 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5453 Context.DependentTy,
5454 Context.DependentTy,
5455 Context.DependentTy,
5456 OpLoc));
5457 }
5458
John McCalld14a8642009-11-21 08:51:07 +00005459 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005460 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5461 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00005462 /* ADL */ true, IsOverloaded(Functions));
John McCalld14a8642009-11-21 08:51:07 +00005463
Mike Stump11289f42009-09-09 15:08:12 +00005464 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005465 FuncEnd = Functions.end();
5466 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00005467 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00005468
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005469 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00005470 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005471 Context.DependentTy,
5472 OpLoc));
5473 }
5474
5475 // If this is the .* operator, which is not overloadable, just
5476 // create a built-in binary operator.
5477 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00005478 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005479
Sebastian Redl6a96bf72009-11-18 23:10:33 +00005480 // If this is the assignment operator, we only perform overload resolution
5481 // if the left-hand side is a class or enumeration type. This is actually
5482 // a hack. The standard requires that we do overload resolution between the
5483 // various built-in candidates, but as DR507 points out, this can lead to
5484 // problems. So we do it this way, which pretty much follows what GCC does.
5485 // Note that we go the traditional code path for compound assignment forms.
5486 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00005487 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005488
Douglas Gregor084d8552009-03-13 23:49:33 +00005489 // Build an empty overload set.
5490 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005491
5492 // Add the candidates from the given function set.
5493 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
5494
5495 // Add operator candidates that are member functions.
5496 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5497
5498 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005499 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005500
5501 // Perform overload resolution.
5502 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005503 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005504 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005505 // We found a built-in operator or an overloaded operator.
5506 FunctionDecl *FnDecl = Best->Function;
5507
5508 if (FnDecl) {
5509 // We matched an overloaded operator. Build a call to that
5510 // operator.
5511
5512 // Convert the arguments.
5513 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005514 OwningExprResult Arg1
5515 = PerformCopyInitialization(
5516 InitializedEntity::InitializeParameter(
5517 FnDecl->getParamDecl(0)),
5518 SourceLocation(),
5519 Owned(Args[1]));
5520 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005521 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005522
5523 if (PerformObjectArgumentInitialization(Args[0], Method))
5524 return ExprError();
5525
5526 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005527 } else {
5528 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005529 OwningExprResult Arg0
5530 = PerformCopyInitialization(
5531 InitializedEntity::InitializeParameter(
5532 FnDecl->getParamDecl(0)),
5533 SourceLocation(),
5534 Owned(Args[0]));
5535 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005536 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005537
5538 OwningExprResult Arg1
5539 = PerformCopyInitialization(
5540 InitializedEntity::InitializeParameter(
5541 FnDecl->getParamDecl(1)),
5542 SourceLocation(),
5543 Owned(Args[1]));
5544 if (Arg1.isInvalid())
5545 return ExprError();
5546 Args[0] = LHS = Arg0.takeAs<Expr>();
5547 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005548 }
5549
5550 // Determine the result type
5551 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00005552 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005553 ResultTy = ResultTy.getNonReferenceType();
5554
5555 // Build the actual expression node.
5556 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00005557 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005558 UsualUnaryConversions(FnExpr);
5559
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005560 ExprOwningPtr<CXXOperatorCallExpr>
5561 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5562 Args, 2, ResultTy,
5563 OpLoc));
5564
5565 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5566 FnDecl))
5567 return ExprError();
5568
5569 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005570 } else {
5571 // We matched a built-in operator. Convert the arguments, then
5572 // break out so that we will build the appropriate built-in
5573 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00005574 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005575 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00005576 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005577 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005578 return ExprError();
5579
5580 break;
5581 }
5582 }
5583
Douglas Gregor66950a32009-09-30 21:46:01 +00005584 case OR_No_Viable_Function: {
5585 // C++ [over.match.oper]p9:
5586 // If the operator is the operator , [...] and there are no
5587 // viable functions, then the operator is assumed to be the
5588 // built-in operator and interpreted according to clause 5.
5589 if (Opc == BinaryOperator::Comma)
5590 break;
5591
Sebastian Redl027de2a2009-05-21 11:50:50 +00005592 // For class as left operand for assignment or compound assigment operator
5593 // do not fall through to handling in built-in, but report that no overloaded
5594 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005595 OwningExprResult Result = ExprError();
5596 if (Args[0]->getType()->isRecordType() &&
5597 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005598 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5599 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005600 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005601 } else {
5602 // No viable function; try to create a built-in operation, which will
5603 // produce an error. Then, show the non-viable candidates.
5604 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005605 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005606 assert(Result.isInvalid() &&
5607 "C++ binary operator overloading is missing candidates!");
5608 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00005609 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005610 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005611 return move(Result);
5612 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005613
5614 case OR_Ambiguous:
5615 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5616 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005617 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005618 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005619 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005620 return ExprError();
5621
5622 case OR_Deleted:
5623 Diag(OpLoc, diag::err_ovl_deleted_oper)
5624 << Best->Function->isDeleted()
5625 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005626 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005627 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005628 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00005629 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005630
Douglas Gregor66950a32009-09-30 21:46:01 +00005631 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005632 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005633}
5634
Sebastian Redladba46e2009-10-29 20:17:01 +00005635Action::OwningExprResult
5636Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5637 SourceLocation RLoc,
5638 ExprArg Base, ExprArg Idx) {
5639 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5640 static_cast<Expr*>(Idx.get()) };
5641 DeclarationName OpName =
5642 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5643
5644 // If either side is type-dependent, create an appropriate dependent
5645 // expression.
5646 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5647
John McCalld14a8642009-11-21 08:51:07 +00005648 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005649 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5650 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005651 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005652 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005653
5654 Base.release();
5655 Idx.release();
5656 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5657 Args, 2,
5658 Context.DependentTy,
5659 RLoc));
5660 }
5661
5662 // Build an empty overload set.
5663 OverloadCandidateSet CandidateSet;
5664
5665 // Subscript can only be overloaded as a member function.
5666
5667 // Add operator candidates that are member functions.
5668 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5669
5670 // Add builtin operator candidates.
5671 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5672
5673 // Perform overload resolution.
5674 OverloadCandidateSet::iterator Best;
5675 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5676 case OR_Success: {
5677 // We found a built-in operator or an overloaded operator.
5678 FunctionDecl *FnDecl = Best->Function;
5679
5680 if (FnDecl) {
5681 // We matched an overloaded operator. Build a call to that
5682 // operator.
5683
5684 // Convert the arguments.
5685 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5686 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5687 PerformCopyInitialization(Args[1],
5688 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005689 AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005690 return ExprError();
5691
5692 // Determine the result type
5693 QualType ResultTy
5694 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5695 ResultTy = ResultTy.getNonReferenceType();
5696
5697 // Build the actual expression node.
5698 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5699 LLoc);
5700 UsualUnaryConversions(FnExpr);
5701
5702 Base.release();
5703 Idx.release();
5704 ExprOwningPtr<CXXOperatorCallExpr>
5705 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5706 FnExpr, Args, 2,
5707 ResultTy, RLoc));
5708
5709 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5710 FnDecl))
5711 return ExprError();
5712
5713 return MaybeBindToTemporary(TheCall.release());
5714 } else {
5715 // We matched a built-in operator. Convert the arguments, then
5716 // break out so that we will build the appropriate built-in
5717 // operator node.
5718 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005719 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00005720 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005721 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005722 return ExprError();
5723
5724 break;
5725 }
5726 }
5727
5728 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00005729 if (CandidateSet.empty())
5730 Diag(LLoc, diag::err_ovl_no_oper)
5731 << Args[0]->getType() << /*subscript*/ 0
5732 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5733 else
5734 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5735 << Args[0]->getType()
5736 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005737 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00005738 "[]", LLoc);
5739 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00005740 }
5741
5742 case OR_Ambiguous:
5743 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5744 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005745 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00005746 "[]", LLoc);
5747 return ExprError();
5748
5749 case OR_Deleted:
5750 Diag(LLoc, diag::err_ovl_deleted_oper)
5751 << Best->Function->isDeleted() << "[]"
5752 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005753 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00005754 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005755 return ExprError();
5756 }
5757
5758 // We matched a built-in operator; build it.
5759 Base.release();
5760 Idx.release();
5761 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5762 Owned(Args[1]), RLoc);
5763}
5764
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005765/// BuildCallToMemberFunction - Build a call to a member
5766/// function. MemExpr is the expression that refers to the member
5767/// function (and includes the object parameter), Args/NumArgs are the
5768/// arguments to the function call (not including the object
5769/// parameter). The caller needs to validate that the member
5770/// expression refers to a member function or an overloaded member
5771/// function.
John McCall2d74de92009-12-01 22:10:20 +00005772Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005773Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5774 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005775 unsigned NumArgs, SourceLocation *CommaLocs,
5776 SourceLocation RParenLoc) {
5777 // Dig out the member expression. This holds both the object
5778 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00005779 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5780
John McCall10eae182009-11-30 22:42:35 +00005781 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005782 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00005783 if (isa<MemberExpr>(NakedMemExpr)) {
5784 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00005785 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5786 } else {
5787 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCall2d74de92009-12-01 22:10:20 +00005788
John McCall6e9f8f62009-12-03 04:06:58 +00005789 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00005790
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005791 // Add overload candidates
5792 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00005793
John McCall2d74de92009-12-01 22:10:20 +00005794 // FIXME: avoid copy.
5795 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5796 if (UnresExpr->hasExplicitTemplateArgs()) {
5797 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5798 TemplateArgs = &TemplateArgsBuffer;
5799 }
5800
John McCall10eae182009-11-30 22:42:35 +00005801 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5802 E = UnresExpr->decls_end(); I != E; ++I) {
5803
John McCall6e9f8f62009-12-03 04:06:58 +00005804 NamedDecl *Func = *I;
5805 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5806 if (isa<UsingShadowDecl>(Func))
5807 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5808
John McCall10eae182009-11-30 22:42:35 +00005809 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00005810 // If explicit template arguments were provided, we can't call a
5811 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00005812 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00005813 continue;
5814
John McCall6e9f8f62009-12-03 04:06:58 +00005815 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5816 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005817 } else {
John McCall10eae182009-11-30 22:42:35 +00005818 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall6e9f8f62009-12-03 04:06:58 +00005819 ActingDC, TemplateArgs,
5820 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005821 CandidateSet,
5822 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005823 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005824 }
Mike Stump11289f42009-09-09 15:08:12 +00005825
John McCall10eae182009-11-30 22:42:35 +00005826 DeclarationName DeclName = UnresExpr->getMemberName();
5827
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005828 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00005829 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005830 case OR_Success:
5831 Method = cast<CXXMethodDecl>(Best->Function);
5832 break;
5833
5834 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00005835 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005836 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005837 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005838 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005839 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005840 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005841
5842 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00005843 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005844 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005845 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005846 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005847 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005848
5849 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00005850 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00005851 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005852 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005853 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005854 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005855 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005856 }
5857
Douglas Gregor51c538b2009-11-20 19:42:02 +00005858 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00005859
John McCall2d74de92009-12-01 22:10:20 +00005860 // If overload resolution picked a static member, build a
5861 // non-member call based on that function.
5862 if (Method->isStatic()) {
5863 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5864 Args, NumArgs, RParenLoc);
5865 }
5866
John McCall10eae182009-11-30 22:42:35 +00005867 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005868 }
5869
5870 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005871 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00005872 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005873 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005874 Method->getResultType().getNonReferenceType(),
5875 RParenLoc));
5876
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005877 // Check for a valid return type.
5878 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5879 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00005880 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005881
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005882 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00005883 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00005884 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005885 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCall2d74de92009-12-01 22:10:20 +00005886 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005887 MemExpr->setBase(ObjectArg);
5888
5889 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005890 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005891 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005892 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00005893 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005894
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005895 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00005896 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00005897
John McCall2d74de92009-12-01 22:10:20 +00005898 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005899}
5900
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005901/// BuildCallToObjectOfClassType - Build a call to an object of class
5902/// type (C++ [over.call.object]), which can end up invoking an
5903/// overloaded function call operator (@c operator()) or performing a
5904/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005905Sema::ExprResult
5906Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005907 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005908 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005909 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005910 SourceLocation RParenLoc) {
5911 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005912 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005913
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005914 // C++ [over.call.object]p1:
5915 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005916 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005917 // candidate functions includes at least the function call
5918 // operators of T. The function call operators of T are obtained by
5919 // ordinary lookup of the name operator() in the context of
5920 // (E).operator().
5921 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005922 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005923
5924 if (RequireCompleteType(LParenLoc, Object->getType(),
5925 PartialDiagnostic(diag::err_incomplete_object_call)
5926 << Object->getSourceRange()))
5927 return true;
5928
John McCall27b18f82009-11-17 02:14:36 +00005929 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5930 LookupQualifiedName(R, Record->getDecl());
5931 R.suppressDiagnostics();
5932
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005933 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00005934 Oper != OperEnd; ++Oper) {
John McCall6e9f8f62009-12-03 04:06:58 +00005935 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005936 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005937 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005938
Douglas Gregorab7897a2008-11-19 22:57:39 +00005939 // C++ [over.call.object]p2:
5940 // In addition, for each conversion function declared in T of the
5941 // form
5942 //
5943 // operator conversion-type-id () cv-qualifier;
5944 //
5945 // where cv-qualifier is the same cv-qualification as, or a
5946 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005947 // denotes the type "pointer to function of (P1,...,Pn) returning
5948 // R", or the type "reference to pointer to function of
5949 // (P1,...,Pn) returning R", or the type "reference to function
5950 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005951 // is also considered as a candidate function. Similarly,
5952 // surrogate call functions are added to the set of candidate
5953 // functions for each conversion function declared in an
5954 // accessible base class provided the function is not hidden
5955 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00005956 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00005957 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00005958 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005959 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00005960 NamedDecl *D = *I;
5961 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5962 if (isa<UsingShadowDecl>(D))
5963 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5964
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005965 // Skip over templated conversion functions; they aren't
5966 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00005967 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005968 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005969
John McCall6e9f8f62009-12-03 04:06:58 +00005970 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00005971
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005972 // Strip the reference type (if any) and then the pointer type (if
5973 // any) to get down to what might be a function type.
5974 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5975 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5976 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005977
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005978 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall6e9f8f62009-12-03 04:06:58 +00005979 AddSurrogateCandidate(Conv, ActingContext, Proto,
5980 Object->getType(), Args, NumArgs,
5981 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005982 }
Mike Stump11289f42009-09-09 15:08:12 +00005983
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005984 // Perform overload resolution.
5985 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005986 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005987 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005988 // Overload resolution succeeded; we'll build the appropriate call
5989 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005990 break;
5991
5992 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00005993 if (CandidateSet.empty())
5994 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
5995 << Object->getType() << /*call*/ 1
5996 << Object->getSourceRange();
5997 else
5998 Diag(Object->getSourceRange().getBegin(),
5999 diag::err_ovl_no_viable_object_call)
6000 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006001 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006002 break;
6003
6004 case OR_Ambiguous:
6005 Diag(Object->getSourceRange().getBegin(),
6006 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006007 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006008 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006009 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006010
6011 case OR_Deleted:
6012 Diag(Object->getSourceRange().getBegin(),
6013 diag::err_ovl_deleted_object_call)
6014 << Best->Function->isDeleted()
6015 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006016 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006017 break;
Mike Stump11289f42009-09-09 15:08:12 +00006018 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006019
Douglas Gregorab7897a2008-11-19 22:57:39 +00006020 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006021 // We had an error; delete all of the subexpressions and return
6022 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006023 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006024 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006025 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006026 return true;
6027 }
6028
Douglas Gregorab7897a2008-11-19 22:57:39 +00006029 if (Best->Function == 0) {
6030 // Since there is no function declaration, this is one of the
6031 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006032 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006033 = cast<CXXConversionDecl>(
6034 Best->Conversions[0].UserDefined.ConversionFunction);
6035
6036 // We selected one of the surrogate functions that converts the
6037 // object parameter to a function pointer. Perform the conversion
6038 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006039
6040 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006041 // and then call it.
Eli Friedmana958a012009-12-09 04:52:43 +00006042 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006043
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006044 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006045 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6046 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006047 }
6048
6049 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6050 // that calls this method, using Object for the implicit object
6051 // parameter and passing along the remaining arguments.
6052 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006053 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006054
6055 unsigned NumArgsInProto = Proto->getNumArgs();
6056 unsigned NumArgsToCheck = NumArgs;
6057
6058 // Build the full argument list for the method call (the
6059 // implicit object parameter is placed at the beginning of the
6060 // list).
6061 Expr **MethodArgs;
6062 if (NumArgs < NumArgsInProto) {
6063 NumArgsToCheck = NumArgsInProto;
6064 MethodArgs = new Expr*[NumArgsInProto + 1];
6065 } else {
6066 MethodArgs = new Expr*[NumArgs + 1];
6067 }
6068 MethodArgs[0] = Object;
6069 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6070 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006071
6072 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006073 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006074 UsualUnaryConversions(NewFn);
6075
6076 // Once we've built TheCall, all of the expressions are properly
6077 // owned.
6078 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006079 ExprOwningPtr<CXXOperatorCallExpr>
6080 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006081 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006082 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006083 delete [] MethodArgs;
6084
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006085 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6086 Method))
6087 return true;
6088
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006089 // We may have default arguments. If so, we need to allocate more
6090 // slots in the call for them.
6091 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006092 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006093 else if (NumArgs > NumArgsInProto)
6094 NumArgsToCheck = NumArgsInProto;
6095
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006096 bool IsError = false;
6097
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006098 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006099 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006100 TheCall->setArg(0, Object);
6101
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006102
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006103 // Check the argument types.
6104 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006105 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006106 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006107 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006108
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006109 // Pass the argument.
6110 QualType ProtoArgType = Proto->getArgType(i);
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006111 IsError |= PerformCopyInitialization(Arg, ProtoArgType, AA_Passing);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006112 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006113 OwningExprResult DefArg
6114 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6115 if (DefArg.isInvalid()) {
6116 IsError = true;
6117 break;
6118 }
6119
6120 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006121 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006122
6123 TheCall->setArg(i + 1, Arg);
6124 }
6125
6126 // If this is a variadic call, handle args passed through "...".
6127 if (Proto->isVariadic()) {
6128 // Promote the arguments (C99 6.5.2.2p7).
6129 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6130 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006131 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006132 TheCall->setArg(i + 1, Arg);
6133 }
6134 }
6135
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006136 if (IsError) return true;
6137
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006138 if (CheckFunctionCall(Method, TheCall.get()))
6139 return true;
6140
Anders Carlsson1c83deb2009-08-16 03:53:54 +00006141 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006142}
6143
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006144/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006145/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006146/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006147Sema::OwningExprResult
6148Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6149 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006150 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006151
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006152 // C++ [over.ref]p1:
6153 //
6154 // [...] An expression x->m is interpreted as (x.operator->())->m
6155 // for a class object x of type T if T::operator->() exists and if
6156 // the operator is selected as the best match function by the
6157 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006158 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
6159 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006160 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006161
Eli Friedman132e70b2009-11-18 01:28:03 +00006162 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
6163 PDiag(diag::err_typecheck_incomplete_tag)
6164 << Base->getSourceRange()))
6165 return ExprError();
6166
John McCall27b18f82009-11-17 02:14:36 +00006167 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6168 LookupQualifiedName(R, BaseRecord->getDecl());
6169 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006170
6171 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006172 Oper != OperEnd; ++Oper) {
6173 NamedDecl *D = *Oper;
6174 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6175 if (isa<UsingShadowDecl>(D))
6176 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6177
6178 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
6179 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006180 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006181 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006182
6183 // Perform overload resolution.
6184 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006185 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006186 case OR_Success:
6187 // Overload resolution succeeded; we'll build the call below.
6188 break;
6189
6190 case OR_No_Viable_Function:
6191 if (CandidateSet.empty())
6192 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006193 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006194 else
6195 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006196 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006197 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006198 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006199
6200 case OR_Ambiguous:
6201 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006202 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006203 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006204 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006205
6206 case OR_Deleted:
6207 Diag(OpLoc, diag::err_ovl_deleted_oper)
6208 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006209 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006210 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006211 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006212 }
6213
6214 // Convert the object parameter.
6215 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00006216 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006217 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006218
6219 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006220 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006221
6222 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006223 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6224 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006225 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006226
6227 QualType ResultTy = Method->getResultType().getNonReferenceType();
6228 ExprOwningPtr<CXXOperatorCallExpr>
6229 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6230 &Base, 1, ResultTy, OpLoc));
6231
6232 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6233 Method))
6234 return ExprError();
6235 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006236}
6237
Douglas Gregorcd695e52008-11-10 20:40:00 +00006238/// FixOverloadedFunctionReference - E is an expression that refers to
6239/// a C++ overloaded function (possibly with some parentheses and
6240/// perhaps a '&' around it). We have resolved the overloaded function
6241/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006242/// refer (possibly indirectly) to Fn. Returns the new expr.
6243Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006244 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00006245 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6246 if (SubExpr == PE->getSubExpr())
6247 return PE->Retain();
6248
6249 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6250 }
6251
6252 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6253 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006254 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006255 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006256 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006257 if (SubExpr == ICE->getSubExpr())
6258 return ICE->Retain();
6259
6260 return new (Context) ImplicitCastExpr(ICE->getType(),
6261 ICE->getCastKind(),
6262 SubExpr,
6263 ICE->isLvalueCast());
6264 }
6265
6266 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006267 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006268 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006269 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6270 if (Method->isStatic()) {
6271 // Do nothing: static member functions aren't any different
6272 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006273 } else {
John McCalle66edc12009-11-24 19:00:30 +00006274 // Fix the sub expression, which really has to be an
6275 // UnresolvedLookupExpr holding an overloaded member function
6276 // or template.
John McCalld14a8642009-11-21 08:51:07 +00006277 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6278 if (SubExpr == UnOp->getSubExpr())
6279 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006280
John McCalld14a8642009-11-21 08:51:07 +00006281 assert(isa<DeclRefExpr>(SubExpr)
6282 && "fixed to something other than a decl ref");
6283 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6284 && "fixed to a member ref with no nested name qualifier");
6285
6286 // We have taken the address of a pointer to member
6287 // function. Perform the computation here so that we get the
6288 // appropriate pointer to member type.
6289 QualType ClassType
6290 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6291 QualType MemPtrType
6292 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6293
6294 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6295 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006296 }
6297 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00006298 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6299 if (SubExpr == UnOp->getSubExpr())
6300 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006301
Douglas Gregor51c538b2009-11-20 19:42:02 +00006302 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6303 Context.getPointerType(SubExpr->getType()),
6304 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006305 }
John McCalld14a8642009-11-21 08:51:07 +00006306
6307 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006308 // FIXME: avoid copy.
6309 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006310 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006311 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6312 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006313 }
6314
John McCalld14a8642009-11-21 08:51:07 +00006315 return DeclRefExpr::Create(Context,
6316 ULE->getQualifier(),
6317 ULE->getQualifierRange(),
6318 Fn,
6319 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006320 Fn->getType(),
6321 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006322 }
6323
John McCall10eae182009-11-30 22:42:35 +00006324 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006325 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006326 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6327 if (MemExpr->hasExplicitTemplateArgs()) {
6328 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6329 TemplateArgs = &TemplateArgsBuffer;
6330 }
John McCall6b51f282009-11-23 01:53:49 +00006331
John McCall2d74de92009-12-01 22:10:20 +00006332 Expr *Base;
6333
6334 // If we're filling in
6335 if (MemExpr->isImplicitAccess()) {
6336 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6337 return DeclRefExpr::Create(Context,
6338 MemExpr->getQualifier(),
6339 MemExpr->getQualifierRange(),
6340 Fn,
6341 MemExpr->getMemberLoc(),
6342 Fn->getType(),
6343 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006344 } else {
6345 SourceLocation Loc = MemExpr->getMemberLoc();
6346 if (MemExpr->getQualifier())
6347 Loc = MemExpr->getQualifierRange().getBegin();
6348 Base = new (Context) CXXThisExpr(Loc,
6349 MemExpr->getBaseType(),
6350 /*isImplicit=*/true);
6351 }
John McCall2d74de92009-12-01 22:10:20 +00006352 } else
6353 Base = MemExpr->getBase()->Retain();
6354
6355 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006356 MemExpr->isArrow(),
6357 MemExpr->getQualifier(),
6358 MemExpr->getQualifierRange(),
6359 Fn,
John McCall6b51f282009-11-23 01:53:49 +00006360 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006361 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006362 Fn->getType());
6363 }
6364
Douglas Gregor51c538b2009-11-20 19:42:02 +00006365 assert(false && "Invalid reference to overloaded function");
6366 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006367}
6368
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006369Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6370 FunctionDecl *Fn) {
6371 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6372}
6373
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006374} // end namespace clang