blob: e9b6072adcaae4364c1e94772419350fce9faf88 [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>()) {
1146 // Objective C++: We're able to convert from a pointer to an any object
1147 // 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 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001154 else
Douglas Gregora119f102008-12-19 19:13:09 +00001155 return false;
1156
Douglas Gregor033f56d2008-12-23 00:53:59 +00001157 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001158 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001159 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001160 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001161 FromPointeeType = FromBlockPtr->getPointeeType();
1162 else
Douglas Gregora119f102008-12-19 19:13:09 +00001163 return false;
1164
Douglas Gregora119f102008-12-19 19:13:09 +00001165 // If we have pointers to pointers, recursively check whether this
1166 // is an Objective-C conversion.
1167 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1168 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1169 IncompatibleObjC)) {
1170 // We always complain about this conversion.
1171 IncompatibleObjC = true;
1172 ConvertedType = ToType;
1173 return true;
1174 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001175 // Allow conversion of pointee being objective-c pointer to another one;
1176 // as in I* to id.
1177 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1178 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1179 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1180 IncompatibleObjC)) {
1181 ConvertedType = ToType;
1182 return true;
1183 }
1184
Douglas Gregor033f56d2008-12-23 00:53:59 +00001185 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001186 // differences in the argument and result types are in Objective-C
1187 // pointer conversions. If so, we permit the conversion (but
1188 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001189 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001190 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001191 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001192 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001193 if (FromFunctionType && ToFunctionType) {
1194 // If the function types are exactly the same, this isn't an
1195 // Objective-C pointer conversion.
1196 if (Context.getCanonicalType(FromPointeeType)
1197 == Context.getCanonicalType(ToPointeeType))
1198 return false;
1199
1200 // Perform the quick checks that will tell us whether these
1201 // function types are obviously different.
1202 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1203 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1204 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1205 return false;
1206
1207 bool HasObjCConversion = false;
1208 if (Context.getCanonicalType(FromFunctionType->getResultType())
1209 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1210 // Okay, the types match exactly. Nothing to do.
1211 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1212 ToFunctionType->getResultType(),
1213 ConvertedType, IncompatibleObjC)) {
1214 // Okay, we have an Objective-C pointer conversion.
1215 HasObjCConversion = true;
1216 } else {
1217 // Function types are too different. Abort.
1218 return false;
1219 }
Mike Stump11289f42009-09-09 15:08:12 +00001220
Douglas Gregora119f102008-12-19 19:13:09 +00001221 // Check argument types.
1222 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1223 ArgIdx != NumArgs; ++ArgIdx) {
1224 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1225 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1226 if (Context.getCanonicalType(FromArgType)
1227 == Context.getCanonicalType(ToArgType)) {
1228 // Okay, the types match exactly. Nothing to do.
1229 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1230 ConvertedType, IncompatibleObjC)) {
1231 // Okay, we have an Objective-C pointer conversion.
1232 HasObjCConversion = true;
1233 } else {
1234 // Argument types are too different. Abort.
1235 return false;
1236 }
1237 }
1238
1239 if (HasObjCConversion) {
1240 // We had an Objective-C conversion. Allow this pointer
1241 // conversion, but complain about it.
1242 ConvertedType = ToType;
1243 IncompatibleObjC = true;
1244 return true;
1245 }
1246 }
1247
Sebastian Redl72b597d2009-01-25 19:43:20 +00001248 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001249}
1250
Douglas Gregor39c16d42008-10-24 04:54:22 +00001251/// CheckPointerConversion - Check the pointer conversion from the
1252/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001253/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001254/// conversions for which IsPointerConversion has already returned
1255/// true. It returns true and produces a diagnostic if there was an
1256/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001257bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001258 CastExpr::CastKind &Kind,
1259 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001260 QualType FromType = From->getType();
1261
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001262 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1263 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001264 QualType FromPointeeType = FromPtrType->getPointeeType(),
1265 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001266
Douglas Gregor39c16d42008-10-24 04:54:22 +00001267 if (FromPointeeType->isRecordType() &&
1268 ToPointeeType->isRecordType()) {
1269 // We must have a derived-to-base conversion. Check an
1270 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001271 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1272 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001273 From->getSourceRange(),
1274 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001275 return true;
1276
1277 // The conversion was successful.
1278 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001279 }
1280 }
Mike Stump11289f42009-09-09 15:08:12 +00001281 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001282 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001283 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001284 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001285 // Objective-C++ conversions are always okay.
1286 // FIXME: We should have a different class of conversions for the
1287 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001288 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001289 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001290
Steve Naroff7cae42b2009-07-10 23:34:53 +00001291 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001292 return false;
1293}
1294
Sebastian Redl72b597d2009-01-25 19:43:20 +00001295/// IsMemberPointerConversion - Determines whether the conversion of the
1296/// expression From, which has the (possibly adjusted) type FromType, can be
1297/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1298/// If so, returns true and places the converted type (that might differ from
1299/// ToType in its cv-qualifiers at some level) into ConvertedType.
1300bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001301 QualType ToType,
1302 bool InOverloadResolution,
1303 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001304 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001305 if (!ToTypePtr)
1306 return false;
1307
1308 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001309 if (From->isNullPointerConstant(Context,
1310 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1311 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001312 ConvertedType = ToType;
1313 return true;
1314 }
1315
1316 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001317 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001318 if (!FromTypePtr)
1319 return false;
1320
1321 // A pointer to member of B can be converted to a pointer to member of D,
1322 // where D is derived from B (C++ 4.11p2).
1323 QualType FromClass(FromTypePtr->getClass(), 0);
1324 QualType ToClass(ToTypePtr->getClass(), 0);
1325 // FIXME: What happens when these are dependent? Is this function even called?
1326
1327 if (IsDerivedFrom(ToClass, FromClass)) {
1328 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1329 ToClass.getTypePtr());
1330 return true;
1331 }
1332
1333 return false;
1334}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001335
Sebastian Redl72b597d2009-01-25 19:43:20 +00001336/// CheckMemberPointerConversion - Check the member pointer conversion from the
1337/// expression From to the type ToType. This routine checks for ambiguous or
1338/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1339/// for which IsMemberPointerConversion has already returned true. It returns
1340/// true and produces a diagnostic if there was an error, or returns false
1341/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001342bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001343 CastExpr::CastKind &Kind,
1344 bool IgnoreBaseAccess) {
1345 (void)IgnoreBaseAccess;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001346 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001347 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001348 if (!FromPtrType) {
1349 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001350 assert(From->isNullPointerConstant(Context,
1351 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001352 "Expr must be null pointer constant!");
1353 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001354 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001355 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001356
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001357 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001358 assert(ToPtrType && "No member pointer cast has a target type "
1359 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001360
Sebastian Redled8f2002009-01-28 18:33:18 +00001361 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1362 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001363
Sebastian Redled8f2002009-01-28 18:33:18 +00001364 // FIXME: What about dependent types?
1365 assert(FromClass->isRecordType() && "Pointer into non-class.");
1366 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001367
Douglas Gregor36d1b142009-10-06 17:59:45 +00001368 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1369 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001370 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1371 assert(DerivationOkay &&
1372 "Should not have been called if derivation isn't OK.");
1373 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001374
Sebastian Redled8f2002009-01-28 18:33:18 +00001375 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1376 getUnqualifiedType())) {
1377 // Derivation is ambiguous. Redo the check to find the exact paths.
1378 Paths.clear();
1379 Paths.setRecordingPaths(true);
1380 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1381 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1382 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001383
Sebastian Redled8f2002009-01-28 18:33:18 +00001384 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1385 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1386 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1387 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001388 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001389
Douglas Gregor89ee6822009-02-28 01:32:25 +00001390 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001391 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1392 << FromClass << ToClass << QualType(VBase, 0)
1393 << From->getSourceRange();
1394 return true;
1395 }
1396
Anders Carlssond7923c62009-08-22 23:33:40 +00001397 // Must be a base to derived member conversion.
1398 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001399 return false;
1400}
1401
Douglas Gregor9a657932008-10-21 23:43:52 +00001402/// IsQualificationConversion - Determines whether the conversion from
1403/// an rvalue of type FromType to ToType is a qualification conversion
1404/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001405bool
1406Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001407 FromType = Context.getCanonicalType(FromType);
1408 ToType = Context.getCanonicalType(ToType);
1409
1410 // If FromType and ToType are the same type, this is not a
1411 // qualification conversion.
1412 if (FromType == ToType)
1413 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001414
Douglas Gregor9a657932008-10-21 23:43:52 +00001415 // (C++ 4.4p4):
1416 // A conversion can add cv-qualifiers at levels other than the first
1417 // in multi-level pointers, subject to the following rules: [...]
1418 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001419 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001420 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001421 // Within each iteration of the loop, we check the qualifiers to
1422 // determine if this still looks like a qualification
1423 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001424 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001425 // until there are no more pointers or pointers-to-members left to
1426 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001427 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001428
1429 // -- for every j > 0, if const is in cv 1,j then const is in cv
1430 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001431 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001432 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001433
Douglas Gregor9a657932008-10-21 23:43:52 +00001434 // -- if the cv 1,j and cv 2,j are different, then const is in
1435 // every cv for 0 < k < j.
1436 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001437 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001438 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001439
Douglas Gregor9a657932008-10-21 23:43:52 +00001440 // Keep track of whether all prior cv-qualifiers in the "to" type
1441 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001442 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001443 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001444 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001445
1446 // We are left with FromType and ToType being the pointee types
1447 // after unwrapping the original FromType and ToType the same number
1448 // of types. If we unwrapped any pointers, and if FromType and
1449 // ToType have the same unqualified type (since we checked
1450 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001451 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001452}
1453
Douglas Gregor576e98c2009-01-30 23:27:23 +00001454/// Determines whether there is a user-defined conversion sequence
1455/// (C++ [over.ics.user]) that converts expression From to the type
1456/// ToType. If such a conversion exists, User will contain the
1457/// user-defined conversion sequence that performs such a conversion
1458/// and this routine will return true. Otherwise, this routine returns
1459/// false and User is unspecified.
1460///
1461/// \param AllowConversionFunctions true if the conversion should
1462/// consider conversion functions at all. If false, only constructors
1463/// will be considered.
1464///
1465/// \param AllowExplicit true if the conversion should consider C++0x
1466/// "explicit" conversion functions as well as non-explicit conversion
1467/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001468///
1469/// \param ForceRValue true if the expression should be treated as an rvalue
1470/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001471/// \param UserCast true if looking for user defined conversion for a static
1472/// cast.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001473OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1474 UserDefinedConversionSequence& User,
1475 OverloadCandidateSet& CandidateSet,
1476 bool AllowConversionFunctions,
1477 bool AllowExplicit,
1478 bool ForceRValue,
1479 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001480 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001481 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1482 // We're not going to find any constructors.
1483 } else if (CXXRecordDecl *ToRecordDecl
1484 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001485 // C++ [over.match.ctor]p1:
1486 // When objects of class type are direct-initialized (8.5), or
1487 // copy-initialized from an expression of the same or a
1488 // derived class type (8.5), overload resolution selects the
1489 // constructor. [...] For copy-initialization, the candidate
1490 // functions are all the converting constructors (12.3.1) of
1491 // that class. The argument list is the expression-list within
1492 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001493 bool SuppressUserConversions = !UserCast;
1494 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1495 IsDerivedFrom(From->getType(), ToType)) {
1496 SuppressUserConversions = false;
1497 AllowConversionFunctions = false;
1498 }
1499
Mike Stump11289f42009-09-09 15:08:12 +00001500 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001501 = Context.DeclarationNames.getCXXConstructorName(
1502 Context.getCanonicalType(ToType).getUnqualifiedType());
1503 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001504 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001505 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001506 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001507 // Find the constructor (which may be a template).
1508 CXXConstructorDecl *Constructor = 0;
1509 FunctionTemplateDecl *ConstructorTmpl
1510 = dyn_cast<FunctionTemplateDecl>(*Con);
1511 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001512 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001513 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1514 else
1515 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001516
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001517 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001518 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001519 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00001520 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1521 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001522 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001523 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001524 // Allow one user-defined conversion when user specifies a
1525 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001526 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001527 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001528 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001529 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001530 }
1531 }
1532
Douglas Gregor576e98c2009-01-30 23:27:23 +00001533 if (!AllowConversionFunctions) {
1534 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001535 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1536 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001537 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001538 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001539 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001540 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001541 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001542 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1543 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001544 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001545 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001546 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001547 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00001548 NamedDecl *D = *I;
1549 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1550 if (isa<UsingShadowDecl>(D))
1551 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1552
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001553 CXXConversionDecl *Conv;
1554 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001555 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001556 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1557 else
John McCalld14a8642009-11-21 08:51:07 +00001558 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001559
1560 if (AllowExplicit || !Conv->isExplicit()) {
1561 if (ConvTemplate)
John McCall6e9f8f62009-12-03 04:06:58 +00001562 AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1563 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001564 else
John McCall6e9f8f62009-12-03 04:06:58 +00001565 AddConversionCandidate(Conv, ActingContext, From, ToType,
1566 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001567 }
1568 }
1569 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001570 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001571
1572 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001573 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001574 case OR_Success:
1575 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001576 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001577 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1578 // C++ [over.ics.user]p1:
1579 // If the user-defined conversion is specified by a
1580 // constructor (12.3.1), the initial standard conversion
1581 // sequence converts the source type to the type required by
1582 // the argument of the constructor.
1583 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001584 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001585 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001586 User.EllipsisConversion = true;
1587 else {
1588 User.Before = Best->Conversions[0].Standard;
1589 User.EllipsisConversion = false;
1590 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001591 User.ConversionFunction = Constructor;
1592 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001593 User.After.setFromType(
1594 ThisType->getAs<PointerType>()->getPointeeType());
1595 User.After.setToType(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001596 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001597 } else if (CXXConversionDecl *Conversion
1598 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1599 // C++ [over.ics.user]p1:
1600 //
1601 // [...] If the user-defined conversion is specified by a
1602 // conversion function (12.3.2), the initial standard
1603 // conversion sequence converts the source type to the
1604 // implicit object parameter of the conversion function.
1605 User.Before = Best->Conversions[0].Standard;
1606 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001607 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001608
1609 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001610 // The second standard conversion sequence converts the
1611 // result of the user-defined conversion to the target type
1612 // for the sequence. Since an implicit conversion sequence
1613 // is an initialization, the special rules for
1614 // initialization by user-defined conversion apply when
1615 // selecting the best user-defined conversion for a
1616 // user-defined conversion sequence (see 13.3.3 and
1617 // 13.3.3.1).
1618 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001619 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001620 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001621 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001622 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001623 }
Mike Stump11289f42009-09-09 15:08:12 +00001624
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001625 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001626 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001627 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001628 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001629 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001630
1631 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001632 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001633 }
1634
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001635 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001636}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001637
1638bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001639Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001640 ImplicitConversionSequence ICS;
1641 OverloadCandidateSet CandidateSet;
1642 OverloadingResult OvResult =
1643 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1644 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001645 if (OvResult == OR_Ambiguous)
1646 Diag(From->getSourceRange().getBegin(),
1647 diag::err_typecheck_ambiguous_condition)
1648 << From->getType() << ToType << From->getSourceRange();
1649 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1650 Diag(From->getSourceRange().getBegin(),
1651 diag::err_typecheck_nonviable_condition)
1652 << From->getType() << ToType << From->getSourceRange();
1653 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001654 return false;
John McCallad907772010-01-12 07:18:19 +00001655 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001656 return true;
1657}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001658
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001659/// CompareImplicitConversionSequences - Compare two implicit
1660/// conversion sequences to determine whether one is better than the
1661/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001662ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1664 const ImplicitConversionSequence& ICS2)
1665{
1666 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1667 // conversion sequences (as defined in 13.3.3.1)
1668 // -- a standard conversion sequence (13.3.3.1.1) is a better
1669 // conversion sequence than a user-defined conversion sequence or
1670 // an ellipsis conversion sequence, and
1671 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1672 // conversion sequence than an ellipsis conversion sequence
1673 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001674 //
John McCall0d1da222010-01-12 00:44:57 +00001675 // C++0x [over.best.ics]p10:
1676 // For the purpose of ranking implicit conversion sequences as
1677 // described in 13.3.3.2, the ambiguous conversion sequence is
1678 // treated as a user-defined sequence that is indistinguishable
1679 // from any other user-defined conversion sequence.
1680 if (ICS1.getKind() < ICS2.getKind()) {
1681 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1682 return ImplicitConversionSequence::Better;
1683 } else if (ICS2.getKind() < ICS1.getKind()) {
1684 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1685 return ImplicitConversionSequence::Worse;
1686 }
1687
1688 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1689 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001690
1691 // Two implicit conversion sequences of the same form are
1692 // indistinguishable conversion sequences unless one of the
1693 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001694 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001695 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001696 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001697 // User-defined conversion sequence U1 is a better conversion
1698 // sequence than another user-defined conversion sequence U2 if
1699 // they contain the same user-defined conversion function or
1700 // constructor and if the second standard conversion sequence of
1701 // U1 is better than the second standard conversion sequence of
1702 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001703 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001704 ICS2.UserDefined.ConversionFunction)
1705 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1706 ICS2.UserDefined.After);
1707 }
1708
1709 return ImplicitConversionSequence::Indistinguishable;
1710}
1711
1712/// CompareStandardConversionSequences - Compare two standard
1713/// conversion sequences to determine whether one is better than the
1714/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001715ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001716Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1717 const StandardConversionSequence& SCS2)
1718{
1719 // Standard conversion sequence S1 is a better conversion sequence
1720 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1721
1722 // -- S1 is a proper subsequence of S2 (comparing the conversion
1723 // sequences in the canonical form defined by 13.3.3.1.1,
1724 // excluding any Lvalue Transformation; the identity conversion
1725 // sequence is considered to be a subsequence of any
1726 // non-identity conversion sequence) or, if not that,
1727 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1728 // Neither is a proper subsequence of the other. Do nothing.
1729 ;
1730 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1731 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001732 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001733 SCS1.Third == ICK_Identity))
1734 // SCS1 is a proper subsequence of SCS2.
1735 return ImplicitConversionSequence::Better;
1736 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1737 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001738 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001739 SCS2.Third == ICK_Identity))
1740 // SCS2 is a proper subsequence of SCS1.
1741 return ImplicitConversionSequence::Worse;
1742
1743 // -- the rank of S1 is better than the rank of S2 (by the rules
1744 // defined below), or, if not that,
1745 ImplicitConversionRank Rank1 = SCS1.getRank();
1746 ImplicitConversionRank Rank2 = SCS2.getRank();
1747 if (Rank1 < Rank2)
1748 return ImplicitConversionSequence::Better;
1749 else if (Rank2 < Rank1)
1750 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001751
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001752 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1753 // are indistinguishable unless one of the following rules
1754 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001755
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001756 // A conversion that is not a conversion of a pointer, or
1757 // pointer to member, to bool is better than another conversion
1758 // that is such a conversion.
1759 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1760 return SCS2.isPointerConversionToBool()
1761 ? ImplicitConversionSequence::Better
1762 : ImplicitConversionSequence::Worse;
1763
Douglas Gregor5c407d92008-10-23 00:40:37 +00001764 // C++ [over.ics.rank]p4b2:
1765 //
1766 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001767 // conversion of B* to A* is better than conversion of B* to
1768 // void*, and conversion of A* to void* is better than conversion
1769 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001770 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001771 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001772 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001773 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001774 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1775 // Exactly one of the conversion sequences is a conversion to
1776 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001777 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1778 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001779 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1780 // Neither conversion sequence converts to a void pointer; compare
1781 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001782 if (ImplicitConversionSequence::CompareKind DerivedCK
1783 = CompareDerivedToBaseConversions(SCS1, SCS2))
1784 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001785 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1786 // Both conversion sequences are conversions to void
1787 // pointers. Compare the source types to determine if there's an
1788 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001789 QualType FromType1 = SCS1.getFromType();
1790 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001791
1792 // Adjust the types we're converting from via the array-to-pointer
1793 // conversion, if we need to.
1794 if (SCS1.First == ICK_Array_To_Pointer)
1795 FromType1 = Context.getArrayDecayedType(FromType1);
1796 if (SCS2.First == ICK_Array_To_Pointer)
1797 FromType2 = Context.getArrayDecayedType(FromType2);
1798
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001799 QualType FromPointee1
1800 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1801 QualType FromPointee2
1802 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001803
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001804 if (IsDerivedFrom(FromPointee2, FromPointee1))
1805 return ImplicitConversionSequence::Better;
1806 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1807 return ImplicitConversionSequence::Worse;
1808
1809 // Objective-C++: If one interface is more specific than the
1810 // other, it is the better one.
1811 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1812 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1813 if (FromIface1 && FromIface1) {
1814 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1815 return ImplicitConversionSequence::Better;
1816 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1817 return ImplicitConversionSequence::Worse;
1818 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001819 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001820
1821 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1822 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001823 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001824 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001825 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001826
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001827 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001828 // C++0x [over.ics.rank]p3b4:
1829 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1830 // implicit object parameter of a non-static member function declared
1831 // without a ref-qualifier, and S1 binds an rvalue reference to an
1832 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001833 // FIXME: We don't know if we're dealing with the implicit object parameter,
1834 // or if the member function in this case has a ref qualifier.
1835 // (Of course, we don't have ref qualifiers yet.)
1836 if (SCS1.RRefBinding != SCS2.RRefBinding)
1837 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1838 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001839
1840 // C++ [over.ics.rank]p3b4:
1841 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1842 // which the references refer are the same type except for
1843 // top-level cv-qualifiers, and the type to which the reference
1844 // initialized by S2 refers is more cv-qualified than the type
1845 // to which the reference initialized by S1 refers.
John McCall0d1da222010-01-12 00:44:57 +00001846 QualType T1 = SCS1.getToType();
1847 QualType T2 = SCS2.getToType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001848 T1 = Context.getCanonicalType(T1);
1849 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001850 Qualifiers T1Quals, T2Quals;
1851 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1852 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1853 if (UnqualT1 == UnqualT2) {
1854 // If the type is an array type, promote the element qualifiers to the type
1855 // for comparison.
1856 if (isa<ArrayType>(T1) && T1Quals)
1857 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1858 if (isa<ArrayType>(T2) && T2Quals)
1859 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001860 if (T2.isMoreQualifiedThan(T1))
1861 return ImplicitConversionSequence::Better;
1862 else if (T1.isMoreQualifiedThan(T2))
1863 return ImplicitConversionSequence::Worse;
1864 }
1865 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001866
1867 return ImplicitConversionSequence::Indistinguishable;
1868}
1869
1870/// CompareQualificationConversions - Compares two standard conversion
1871/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001872/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1873ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001874Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001875 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001876 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001877 // -- S1 and S2 differ only in their qualification conversion and
1878 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1879 // cv-qualification signature of type T1 is a proper subset of
1880 // the cv-qualification signature of type T2, and S1 is not the
1881 // deprecated string literal array-to-pointer conversion (4.2).
1882 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1883 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1884 return ImplicitConversionSequence::Indistinguishable;
1885
1886 // FIXME: the example in the standard doesn't use a qualification
1887 // conversion (!)
1888 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1889 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1890 T1 = Context.getCanonicalType(T1);
1891 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001892 Qualifiers T1Quals, T2Quals;
1893 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1894 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001895
1896 // If the types are the same, we won't learn anything by unwrapped
1897 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00001898 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001899 return ImplicitConversionSequence::Indistinguishable;
1900
Chandler Carruth607f38e2009-12-29 07:16:59 +00001901 // If the type is an array type, promote the element qualifiers to the type
1902 // for comparison.
1903 if (isa<ArrayType>(T1) && T1Quals)
1904 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1905 if (isa<ArrayType>(T2) && T2Quals)
1906 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1907
Mike Stump11289f42009-09-09 15:08:12 +00001908 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001909 = ImplicitConversionSequence::Indistinguishable;
1910 while (UnwrapSimilarPointerTypes(T1, T2)) {
1911 // Within each iteration of the loop, we check the qualifiers to
1912 // determine if this still looks like a qualification
1913 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001914 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001915 // until there are no more pointers or pointers-to-members left
1916 // to unwrap. This essentially mimics what
1917 // IsQualificationConversion does, but here we're checking for a
1918 // strict subset of qualifiers.
1919 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1920 // The qualifiers are the same, so this doesn't tell us anything
1921 // about how the sequences rank.
1922 ;
1923 else if (T2.isMoreQualifiedThan(T1)) {
1924 // T1 has fewer qualifiers, so it could be the better sequence.
1925 if (Result == ImplicitConversionSequence::Worse)
1926 // Neither has qualifiers that are a subset of the other's
1927 // qualifiers.
1928 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001929
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001930 Result = ImplicitConversionSequence::Better;
1931 } else if (T1.isMoreQualifiedThan(T2)) {
1932 // T2 has fewer qualifiers, so it could be the better sequence.
1933 if (Result == ImplicitConversionSequence::Better)
1934 // Neither has qualifiers that are a subset of the other's
1935 // qualifiers.
1936 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001937
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001938 Result = ImplicitConversionSequence::Worse;
1939 } else {
1940 // Qualifiers are disjoint.
1941 return ImplicitConversionSequence::Indistinguishable;
1942 }
1943
1944 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001945 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001946 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001947 }
1948
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001949 // Check that the winning standard conversion sequence isn't using
1950 // the deprecated string literal array to pointer conversion.
1951 switch (Result) {
1952 case ImplicitConversionSequence::Better:
1953 if (SCS1.Deprecated)
1954 Result = ImplicitConversionSequence::Indistinguishable;
1955 break;
1956
1957 case ImplicitConversionSequence::Indistinguishable:
1958 break;
1959
1960 case ImplicitConversionSequence::Worse:
1961 if (SCS2.Deprecated)
1962 Result = ImplicitConversionSequence::Indistinguishable;
1963 break;
1964 }
1965
1966 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001967}
1968
Douglas Gregor5c407d92008-10-23 00:40:37 +00001969/// CompareDerivedToBaseConversions - Compares two standard conversion
1970/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001971/// various kinds of derived-to-base conversions (C++
1972/// [over.ics.rank]p4b3). As part of these checks, we also look at
1973/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001974ImplicitConversionSequence::CompareKind
1975Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1976 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00001977 QualType FromType1 = SCS1.getFromType();
1978 QualType ToType1 = SCS1.getToType();
1979 QualType FromType2 = SCS2.getFromType();
1980 QualType ToType2 = SCS2.getToType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001981
1982 // Adjust the types we're converting from via the array-to-pointer
1983 // conversion, if we need to.
1984 if (SCS1.First == ICK_Array_To_Pointer)
1985 FromType1 = Context.getArrayDecayedType(FromType1);
1986 if (SCS2.First == ICK_Array_To_Pointer)
1987 FromType2 = Context.getArrayDecayedType(FromType2);
1988
1989 // Canonicalize all of the types.
1990 FromType1 = Context.getCanonicalType(FromType1);
1991 ToType1 = Context.getCanonicalType(ToType1);
1992 FromType2 = Context.getCanonicalType(FromType2);
1993 ToType2 = Context.getCanonicalType(ToType2);
1994
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001995 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001996 //
1997 // If class B is derived directly or indirectly from class A and
1998 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001999 //
2000 // For Objective-C, we let A, B, and C also be Objective-C
2001 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002002
2003 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002004 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002005 SCS2.Second == ICK_Pointer_Conversion &&
2006 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2007 FromType1->isPointerType() && FromType2->isPointerType() &&
2008 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002009 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002010 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002011 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002012 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002013 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002014 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002015 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002016 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002017
John McCall9dd450b2009-09-21 23:43:11 +00002018 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2019 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2020 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2021 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002022
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002023 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002024 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2025 if (IsDerivedFrom(ToPointee1, ToPointee2))
2026 return ImplicitConversionSequence::Better;
2027 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2028 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002029
2030 if (ToIface1 && ToIface2) {
2031 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2032 return ImplicitConversionSequence::Better;
2033 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2034 return ImplicitConversionSequence::Worse;
2035 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002036 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002037
2038 // -- conversion of B* to A* is better than conversion of C* to A*,
2039 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2040 if (IsDerivedFrom(FromPointee2, FromPointee1))
2041 return ImplicitConversionSequence::Better;
2042 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2043 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002044
Douglas Gregor237f96c2008-11-26 23:31:11 +00002045 if (FromIface1 && FromIface2) {
2046 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2047 return ImplicitConversionSequence::Better;
2048 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2049 return ImplicitConversionSequence::Worse;
2050 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002051 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002052 }
2053
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002054 // Compare based on reference bindings.
2055 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
2056 SCS1.Second == ICK_Derived_To_Base) {
2057 // -- binding of an expression of type C to a reference of type
2058 // B& is better than binding an expression of type C to a
2059 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002060 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2061 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002062 if (IsDerivedFrom(ToType1, ToType2))
2063 return ImplicitConversionSequence::Better;
2064 else if (IsDerivedFrom(ToType2, ToType1))
2065 return ImplicitConversionSequence::Worse;
2066 }
2067
Douglas Gregor2fe98832008-11-03 19:09:14 +00002068 // -- binding of an expression of type B to a reference of type
2069 // A& is better than binding an expression of type C to a
2070 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002071 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2072 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002073 if (IsDerivedFrom(FromType2, FromType1))
2074 return ImplicitConversionSequence::Better;
2075 else if (IsDerivedFrom(FromType1, FromType2))
2076 return ImplicitConversionSequence::Worse;
2077 }
2078 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002079
2080 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002081 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2082 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2083 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2084 const MemberPointerType * FromMemPointer1 =
2085 FromType1->getAs<MemberPointerType>();
2086 const MemberPointerType * ToMemPointer1 =
2087 ToType1->getAs<MemberPointerType>();
2088 const MemberPointerType * FromMemPointer2 =
2089 FromType2->getAs<MemberPointerType>();
2090 const MemberPointerType * ToMemPointer2 =
2091 ToType2->getAs<MemberPointerType>();
2092 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2093 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2094 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2095 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2096 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2097 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2098 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2099 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002100 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002101 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2102 if (IsDerivedFrom(ToPointee1, ToPointee2))
2103 return ImplicitConversionSequence::Worse;
2104 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2105 return ImplicitConversionSequence::Better;
2106 }
2107 // conversion of B::* to C::* is better than conversion of A::* to C::*
2108 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2109 if (IsDerivedFrom(FromPointee1, FromPointee2))
2110 return ImplicitConversionSequence::Better;
2111 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2112 return ImplicitConversionSequence::Worse;
2113 }
2114 }
2115
Douglas Gregor2fe98832008-11-03 19:09:14 +00002116 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2117 SCS1.Second == ICK_Derived_To_Base) {
2118 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002119 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2120 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002121 if (IsDerivedFrom(ToType1, ToType2))
2122 return ImplicitConversionSequence::Better;
2123 else if (IsDerivedFrom(ToType2, ToType1))
2124 return ImplicitConversionSequence::Worse;
2125 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002126
Douglas Gregor2fe98832008-11-03 19:09:14 +00002127 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002128 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2129 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002130 if (IsDerivedFrom(FromType2, FromType1))
2131 return ImplicitConversionSequence::Better;
2132 else if (IsDerivedFrom(FromType1, FromType2))
2133 return ImplicitConversionSequence::Worse;
2134 }
2135 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002136
Douglas Gregor5c407d92008-10-23 00:40:37 +00002137 return ImplicitConversionSequence::Indistinguishable;
2138}
2139
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002140/// TryCopyInitialization - Try to copy-initialize a value of type
2141/// ToType from the expression From. Return the implicit conversion
2142/// sequence required to pass this argument, which may be a bad
2143/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002144/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002145/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2146/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002147ImplicitConversionSequence
2148Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002149 bool SuppressUserConversions, bool ForceRValue,
2150 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002151 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002152 ImplicitConversionSequence ICS;
John McCall6a61b522010-01-13 09:16:55 +00002153 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002154 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002155 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002156 SuppressUserConversions,
2157 /*AllowExplicit=*/false,
2158 ForceRValue,
2159 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002160 return ICS;
2161 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002162 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002163 SuppressUserConversions,
2164 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002165 ForceRValue,
2166 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002167 }
2168}
2169
Sebastian Redl42e92c42009-04-12 17:16:29 +00002170/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2171/// the expression @p From. Returns true (and emits a diagnostic) if there was
2172/// an error, returns false if the initialization succeeded. Elidable should
2173/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2174/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002175bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002176 AssignmentAction Action, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002177 if (!getLangOptions().CPlusPlus) {
2178 // In C, argument passing is the same as performing an assignment.
2179 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002180
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002181 AssignConvertType ConvTy =
2182 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002183 if (ConvTy != Compatible &&
2184 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2185 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002186
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002187 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002188 FromType, From, Action);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002189 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002190
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002191 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002192 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002193 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002194 /*SuppressUserConversions=*/false,
2195 /*AllowExplicit=*/false,
2196 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002197
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002198 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002199 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002200 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002201 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002202 return Diag(From->getSourceRange().getBegin(),
2203 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002204 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002205 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002206}
2207
Douglas Gregor436424c2008-11-18 23:14:02 +00002208/// TryObjectArgumentInitialization - Try to initialize the object
2209/// parameter of the given member function (@c Method) from the
2210/// expression @p From.
2211ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002212Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002213 CXXMethodDecl *Method,
2214 CXXRecordDecl *ActingContext) {
2215 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002216 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2217 // const volatile object.
2218 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2219 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2220 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002221
2222 // Set up the conversion sequence as a "bad" conversion, to allow us
2223 // to exit early.
2224 ImplicitConversionSequence ICS;
2225 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002226 ICS.setBad();
Douglas Gregor436424c2008-11-18 23:14:02 +00002227
2228 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002229 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002230 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002231 FromType = PT->getPointeeType();
2232
2233 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002234
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002235 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002236 // where X is the class of which the function is a member
2237 // (C++ [over.match.funcs]p4). However, when finding an implicit
2238 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002239 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002240 // (C++ [over.match.funcs]p5). We perform a simplified version of
2241 // reference binding here, that allows class rvalues to bind to
2242 // non-constant references.
2243
2244 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2245 // with the implicit object parameter (C++ [over.match.funcs]p5).
2246 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002247 if (ImplicitParamType.getCVRQualifiers()
2248 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002249 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall47000992010-01-14 03:28:57 +00002250 ICS.Bad.init(BadConversionSequence::bad_qualifiers,
2251 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002252 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002253 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002254
2255 // Check that we have either the same type or a derived type. It
2256 // affects the conversion rank.
2257 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002258 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002259 ICS.Standard.Second = ICK_Identity;
2260 else if (IsDerivedFrom(FromType, ClassType))
2261 ICS.Standard.Second = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002262 else {
2263 ICS.Bad.init(BadConversionSequence::unrelated_class, FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002264 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002265 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002266
2267 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002268 ICS.setStandard();
2269 ICS.Standard.setFromType(FromType);
2270 ICS.Standard.setToType(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002271 ICS.Standard.ReferenceBinding = true;
2272 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002273 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002274 return ICS;
2275}
2276
2277/// PerformObjectArgumentInitialization - Perform initialization of
2278/// the implicit object parameter for the given Method with the given
2279/// expression.
2280bool
2281Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002282 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002283 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002284 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002285
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002286 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002287 FromRecordType = PT->getPointeeType();
2288 DestType = Method->getThisType(Context);
2289 } else {
2290 FromRecordType = From->getType();
2291 DestType = ImplicitParamRecordType;
2292 }
2293
John McCall6e9f8f62009-12-03 04:06:58 +00002294 // Note that we always use the true parent context when performing
2295 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002296 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002297 = TryObjectArgumentInitialization(From->getType(), Method,
2298 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002299 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002300 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002301 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002302 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002303
Douglas Gregor436424c2008-11-18 23:14:02 +00002304 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002305 CheckDerivedToBaseConversion(FromRecordType,
2306 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002307 From->getSourceRange().getBegin(),
2308 From->getSourceRange()))
2309 return true;
2310
Mike Stump11289f42009-09-09 15:08:12 +00002311 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002312 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002313 return false;
2314}
2315
Douglas Gregor5fb53972009-01-14 15:45:31 +00002316/// TryContextuallyConvertToBool - Attempt to contextually convert the
2317/// expression From to bool (C++0x [conv]p3).
2318ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002319 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002320 // FIXME: Are these flags correct?
2321 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002322 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002323 /*ForceRValue=*/false,
2324 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002325}
2326
2327/// PerformContextuallyConvertToBool - Perform a contextual conversion
2328/// of the expression From to bool (C++0x [conv]p3).
2329bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2330 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002331 if (!ICS.isBad())
2332 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002333
Fariborz Jahanian76197412009-11-18 18:26:29 +00002334 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002335 return Diag(From->getSourceRange().getBegin(),
2336 diag::err_typecheck_bool_condition)
2337 << From->getType() << From->getSourceRange();
2338 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002339}
2340
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002341/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002342/// candidate functions, using the given function call arguments. If
2343/// @p SuppressUserConversions, then don't allow user-defined
2344/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002345/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2346/// hacky way to implement the overloading rules for elidable copy
2347/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002348///
2349/// \para PartialOverloading true if we are performing "partial" overloading
2350/// based on an incomplete set of function arguments. This feature is used by
2351/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002352void
2353Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002354 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002355 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002356 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002357 bool ForceRValue,
2358 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002359 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002360 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002361 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002362 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002363 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002364
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002365 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002366 if (!isa<CXXConstructorDecl>(Method)) {
2367 // If we get here, it's because we're calling a member function
2368 // that is named without a member access expression (e.g.,
2369 // "this->f") that was either written explicitly or created
2370 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002371 // function, e.g., X::f(). We use an empty type for the implied
2372 // object argument (C++ [over.call.func]p3), and the acting context
2373 // is irrelevant.
2374 AddMethodCandidate(Method, Method->getParent(),
2375 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002376 SuppressUserConversions, ForceRValue);
2377 return;
2378 }
2379 // We treat a constructor like a non-member function, since its object
2380 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002381 }
2382
Douglas Gregorff7028a2009-11-13 23:59:09 +00002383 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002384 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002385
Douglas Gregor27381f32009-11-23 12:27:39 +00002386 // Overload resolution is always an unevaluated context.
2387 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2388
Douglas Gregorffe14e32009-11-14 01:20:54 +00002389 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2390 // C++ [class.copy]p3:
2391 // A member function template is never instantiated to perform the copy
2392 // of a class object to an object of its class type.
2393 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2394 if (NumArgs == 1 &&
2395 Constructor->isCopyConstructorLikeSpecialization() &&
2396 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2397 return;
2398 }
2399
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002400 // Add this candidate
2401 CandidateSet.push_back(OverloadCandidate());
2402 OverloadCandidate& Candidate = CandidateSet.back();
2403 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002404 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002405 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002406 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002407
2408 unsigned NumArgsInProto = Proto->getNumArgs();
2409
2410 // (C++ 13.3.2p2): A candidate function having fewer than m
2411 // parameters is viable only if it has an ellipsis in its parameter
2412 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002413 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2414 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002415 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002416 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002417 return;
2418 }
2419
2420 // (C++ 13.3.2p2): A candidate function having more than m parameters
2421 // is viable only if the (m+1)st parameter has a default argument
2422 // (8.3.6). For the purposes of overload resolution, the
2423 // parameter list is truncated on the right, so that there are
2424 // exactly m parameters.
2425 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002426 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002427 // Not enough arguments.
2428 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002429 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002430 return;
2431 }
2432
2433 // Determine the implicit conversion sequences for each of the
2434 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002435 Candidate.Conversions.resize(NumArgs);
2436 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2437 if (ArgIdx < NumArgsInProto) {
2438 // (C++ 13.3.2p3): for F to be a viable function, there shall
2439 // exist for each argument an implicit conversion sequence
2440 // (13.3.3.1) that converts that argument to the corresponding
2441 // parameter of F.
2442 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002443 Candidate.Conversions[ArgIdx]
2444 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002445 SuppressUserConversions, ForceRValue,
2446 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002447 if (Candidate.Conversions[ArgIdx].isBad()) {
2448 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002449 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002450 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002451 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002452 } else {
2453 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2454 // argument for which there is no corresponding parameter is
2455 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002456 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002457 }
2458 }
2459}
2460
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002461/// \brief Add all of the function declarations in the given function set to
2462/// the overload canddiate set.
2463void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2464 Expr **Args, unsigned NumArgs,
2465 OverloadCandidateSet& CandidateSet,
2466 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002467 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002468 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002469 F != FEnd; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002470 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002471 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2472 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2473 AddMethodCandidate(cast<CXXMethodDecl>(FD),
John McCall6e9f8f62009-12-03 04:06:58 +00002474 cast<CXXMethodDecl>(FD)->getParent(),
2475 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002476 CandidateSet, SuppressUserConversions);
2477 else
2478 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2479 SuppressUserConversions);
2480 } else {
2481 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2482 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2483 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2484 AddMethodTemplateCandidate(FunTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002485 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002486 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002487 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002488 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002489 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002490 else
2491 AddTemplateOverloadCandidate(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002492 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002493 Args, NumArgs, CandidateSet,
2494 SuppressUserConversions);
2495 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002496 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002497}
2498
John McCallf0f1cf02009-11-17 07:50:12 +00002499/// AddMethodCandidate - Adds a named decl (which is some kind of
2500/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002501void Sema::AddMethodCandidate(NamedDecl *Decl,
2502 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002503 Expr **Args, unsigned NumArgs,
2504 OverloadCandidateSet& CandidateSet,
2505 bool SuppressUserConversions, bool ForceRValue) {
John McCall6e9f8f62009-12-03 04:06:58 +00002506 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002507
2508 if (isa<UsingShadowDecl>(Decl))
2509 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2510
2511 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2512 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2513 "Expected a member function template");
John McCall6e9f8f62009-12-03 04:06:58 +00002514 AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2515 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002516 CandidateSet,
2517 SuppressUserConversions,
2518 ForceRValue);
2519 } else {
John McCall6e9f8f62009-12-03 04:06:58 +00002520 AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2521 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002522 CandidateSet, SuppressUserConversions, ForceRValue);
2523 }
2524}
2525
Douglas Gregor436424c2008-11-18 23:14:02 +00002526/// AddMethodCandidate - Adds the given C++ member function to the set
2527/// of candidate functions, using the given function call arguments
2528/// and the object argument (@c Object). For example, in a call
2529/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2530/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2531/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002532/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2533/// a slightly hacky way to implement the overloading rules for elidable copy
2534/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002535void
John McCall6e9f8f62009-12-03 04:06:58 +00002536Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2537 QualType ObjectType, Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002538 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002539 bool SuppressUserConversions, bool ForceRValue) {
2540 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002541 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002542 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002543 assert(!isa<CXXConstructorDecl>(Method) &&
2544 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002545
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002546 if (!CandidateSet.isNewCandidate(Method))
2547 return;
2548
Douglas Gregor27381f32009-11-23 12:27:39 +00002549 // Overload resolution is always an unevaluated context.
2550 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2551
Douglas Gregor436424c2008-11-18 23:14:02 +00002552 // Add this candidate
2553 CandidateSet.push_back(OverloadCandidate());
2554 OverloadCandidate& Candidate = CandidateSet.back();
2555 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002556 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002557 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002558
2559 unsigned NumArgsInProto = Proto->getNumArgs();
2560
2561 // (C++ 13.3.2p2): A candidate function having fewer than m
2562 // parameters is viable only if it has an ellipsis in its parameter
2563 // list (8.3.5).
2564 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2565 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002566 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002567 return;
2568 }
2569
2570 // (C++ 13.3.2p2): A candidate function having more than m parameters
2571 // is viable only if the (m+1)st parameter has a default argument
2572 // (8.3.6). For the purposes of overload resolution, the
2573 // parameter list is truncated on the right, so that there are
2574 // exactly m parameters.
2575 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2576 if (NumArgs < MinRequiredArgs) {
2577 // Not enough arguments.
2578 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002579 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002580 return;
2581 }
2582
2583 Candidate.Viable = true;
2584 Candidate.Conversions.resize(NumArgs + 1);
2585
John McCall6e9f8f62009-12-03 04:06:58 +00002586 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002587 // The implicit object argument is ignored.
2588 Candidate.IgnoreObjectArgument = true;
2589 else {
2590 // Determine the implicit conversion sequence for the object
2591 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002592 Candidate.Conversions[0]
2593 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002594 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002595 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002596 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002597 return;
2598 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002599 }
2600
2601 // Determine the implicit conversion sequences for each of the
2602 // arguments.
2603 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2604 if (ArgIdx < NumArgsInProto) {
2605 // (C++ 13.3.2p3): for F to be a viable function, there shall
2606 // exist for each argument an implicit conversion sequence
2607 // (13.3.3.1) that converts that argument to the corresponding
2608 // parameter of F.
2609 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002610 Candidate.Conversions[ArgIdx + 1]
2611 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002612 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002613 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002614 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002615 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002616 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002617 break;
2618 }
2619 } else {
2620 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2621 // argument for which there is no corresponding parameter is
2622 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002623 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002624 }
2625 }
2626}
2627
Douglas Gregor97628d62009-08-21 00:16:32 +00002628/// \brief Add a C++ member function template as a candidate to the candidate
2629/// set, using template argument deduction to produce an appropriate member
2630/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002631void
Douglas Gregor97628d62009-08-21 00:16:32 +00002632Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002633 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002634 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002635 QualType ObjectType,
2636 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002637 OverloadCandidateSet& CandidateSet,
2638 bool SuppressUserConversions,
2639 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002640 if (!CandidateSet.isNewCandidate(MethodTmpl))
2641 return;
2642
Douglas Gregor97628d62009-08-21 00:16:32 +00002643 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002644 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002645 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002646 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002647 // candidate functions in the usual way.113) A given name can refer to one
2648 // or more function templates and also to a set of overloaded non-template
2649 // functions. In such a case, the candidate functions generated from each
2650 // function template are combined with the set of non-template candidate
2651 // functions.
2652 TemplateDeductionInfo Info(Context);
2653 FunctionDecl *Specialization = 0;
2654 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002655 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002656 Args, NumArgs, Specialization, Info)) {
2657 // FIXME: Record what happened with template argument deduction, so
2658 // that we can give the user a beautiful diagnostic.
2659 (void)Result;
2660 return;
2661 }
Mike Stump11289f42009-09-09 15:08:12 +00002662
Douglas Gregor97628d62009-08-21 00:16:32 +00002663 // Add the function template specialization produced by template argument
2664 // deduction as a candidate.
2665 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002666 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002667 "Specialization is not a member function?");
John McCall6e9f8f62009-12-03 04:06:58 +00002668 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2669 ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002670 CandidateSet, SuppressUserConversions, ForceRValue);
2671}
2672
Douglas Gregor05155d82009-08-21 23:19:43 +00002673/// \brief Add a C++ function template specialization as a candidate
2674/// in the candidate set, using template argument deduction to produce
2675/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002676void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002677Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002678 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002679 Expr **Args, unsigned NumArgs,
2680 OverloadCandidateSet& CandidateSet,
2681 bool SuppressUserConversions,
2682 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002683 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2684 return;
2685
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002686 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002687 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002688 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002689 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002690 // candidate functions in the usual way.113) A given name can refer to one
2691 // or more function templates and also to a set of overloaded non-template
2692 // functions. In such a case, the candidate functions generated from each
2693 // function template are combined with the set of non-template candidate
2694 // functions.
2695 TemplateDeductionInfo Info(Context);
2696 FunctionDecl *Specialization = 0;
2697 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002698 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002699 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002700 // FIXME: Record what happened with template argument deduction, so
2701 // that we can give the user a beautiful diagnostic.
John McCalld681c392009-12-16 08:11:27 +00002702 (void) Result;
2703
2704 CandidateSet.push_back(OverloadCandidate());
2705 OverloadCandidate &Candidate = CandidateSet.back();
2706 Candidate.Function = FunctionTemplate->getTemplatedDecl();
2707 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002708 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00002709 Candidate.IsSurrogate = false;
2710 Candidate.IgnoreObjectArgument = false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002711 return;
2712 }
Mike Stump11289f42009-09-09 15:08:12 +00002713
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002714 // Add the function template specialization produced by template argument
2715 // deduction as a candidate.
2716 assert(Specialization && "Missing function template specialization?");
2717 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2718 SuppressUserConversions, ForceRValue);
2719}
Mike Stump11289f42009-09-09 15:08:12 +00002720
Douglas Gregora1f013e2008-11-07 22:36:19 +00002721/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002722/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002723/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002724/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002725/// (which may or may not be the same type as the type that the
2726/// conversion function produces).
2727void
2728Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002729 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002730 Expr *From, QualType ToType,
2731 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002732 assert(!Conversion->getDescribedFunctionTemplate() &&
2733 "Conversion function templates use AddTemplateConversionCandidate");
2734
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002735 if (!CandidateSet.isNewCandidate(Conversion))
2736 return;
2737
Douglas Gregor27381f32009-11-23 12:27:39 +00002738 // Overload resolution is always an unevaluated context.
2739 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2740
Douglas Gregora1f013e2008-11-07 22:36:19 +00002741 // Add this candidate
2742 CandidateSet.push_back(OverloadCandidate());
2743 OverloadCandidate& Candidate = CandidateSet.back();
2744 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002745 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002746 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002747 Candidate.FinalConversion.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002748 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
2749 Candidate.FinalConversion.setToType(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00002750
Douglas Gregor436424c2008-11-18 23:14:02 +00002751 // Determine the implicit conversion sequence for the implicit
2752 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002753 Candidate.Viable = true;
2754 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002755 Candidate.Conversions[0]
2756 = TryObjectArgumentInitialization(From->getType(), Conversion,
2757 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002758 // Conversion functions to a different type in the base class is visible in
2759 // the derived class. So, a derived to base conversion should not participate
2760 // in overload resolution.
2761 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2762 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00002763 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002764 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002765 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002766 return;
2767 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002768
2769 // We won't go through a user-define type conversion function to convert a
2770 // derived to base as such conversions are given Conversion Rank. They only
2771 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2772 QualType FromCanon
2773 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2774 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2775 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2776 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002777 Candidate.FailureKind = ovl_fail_bad_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002778 return;
2779 }
2780
Douglas Gregora1f013e2008-11-07 22:36:19 +00002781
2782 // To determine what the conversion from the result of calling the
2783 // conversion function to the type we're eventually trying to
2784 // convert to (ToType), we need to synthesize a call to the
2785 // conversion function and attempt copy initialization from it. This
2786 // makes sure that we get the right semantics with respect to
2787 // lvalues/rvalues and the type. Fortunately, we can allocate this
2788 // call on the stack and we don't need its arguments to be
2789 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002790 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002791 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002792 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002793 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002794 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002795
2796 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002797 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2798 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002799 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002800 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002801 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002802 ImplicitConversionSequence ICS =
2803 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002804 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002805 /*ForceRValue=*/false,
2806 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002807
John McCall0d1da222010-01-12 00:44:57 +00002808 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002809 case ImplicitConversionSequence::StandardConversion:
2810 Candidate.FinalConversion = ICS.Standard;
2811 break;
2812
2813 case ImplicitConversionSequence::BadConversion:
2814 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002815 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002816 break;
2817
2818 default:
Mike Stump11289f42009-09-09 15:08:12 +00002819 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002820 "Can only end up with a standard conversion sequence or failure");
2821 }
2822}
2823
Douglas Gregor05155d82009-08-21 23:19:43 +00002824/// \brief Adds a conversion function template specialization
2825/// candidate to the overload set, using template argument deduction
2826/// to deduce the template arguments of the conversion function
2827/// template from the type that we are converting to (C++
2828/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002829void
Douglas Gregor05155d82009-08-21 23:19:43 +00002830Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6e9f8f62009-12-03 04:06:58 +00002831 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002832 Expr *From, QualType ToType,
2833 OverloadCandidateSet &CandidateSet) {
2834 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2835 "Only conversion function templates permitted here");
2836
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002837 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2838 return;
2839
Douglas Gregor05155d82009-08-21 23:19:43 +00002840 TemplateDeductionInfo Info(Context);
2841 CXXConversionDecl *Specialization = 0;
2842 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002843 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002844 Specialization, Info)) {
2845 // FIXME: Record what happened with template argument deduction, so
2846 // that we can give the user a beautiful diagnostic.
2847 (void)Result;
2848 return;
2849 }
Mike Stump11289f42009-09-09 15:08:12 +00002850
Douglas Gregor05155d82009-08-21 23:19:43 +00002851 // Add the conversion function template specialization produced by
2852 // template argument deduction as a candidate.
2853 assert(Specialization && "Missing function template specialization?");
John McCall6e9f8f62009-12-03 04:06:58 +00002854 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002855}
2856
Douglas Gregorab7897a2008-11-19 22:57:39 +00002857/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2858/// converts the given @c Object to a function pointer via the
2859/// conversion function @c Conversion, and then attempts to call it
2860/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2861/// the type of function that we'll eventually be calling.
2862void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002863 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002864 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002865 QualType ObjectType,
2866 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002867 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002868 if (!CandidateSet.isNewCandidate(Conversion))
2869 return;
2870
Douglas Gregor27381f32009-11-23 12:27:39 +00002871 // Overload resolution is always an unevaluated context.
2872 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2873
Douglas Gregorab7897a2008-11-19 22:57:39 +00002874 CandidateSet.push_back(OverloadCandidate());
2875 OverloadCandidate& Candidate = CandidateSet.back();
2876 Candidate.Function = 0;
2877 Candidate.Surrogate = Conversion;
2878 Candidate.Viable = true;
2879 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002880 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002881 Candidate.Conversions.resize(NumArgs + 1);
2882
2883 // Determine the implicit conversion sequence for the implicit
2884 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002885 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002886 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002887 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002888 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002889 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002890 return;
2891 }
2892
2893 // The first conversion is actually a user-defined conversion whose
2894 // first conversion is ObjectInit's standard conversion (which is
2895 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00002896 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002897 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002898 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002899 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002900 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002901 = Candidate.Conversions[0].UserDefined.Before;
2902 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2903
Mike Stump11289f42009-09-09 15:08:12 +00002904 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002905 unsigned NumArgsInProto = Proto->getNumArgs();
2906
2907 // (C++ 13.3.2p2): A candidate function having fewer than m
2908 // parameters is viable only if it has an ellipsis in its parameter
2909 // list (8.3.5).
2910 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2911 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002912 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002913 return;
2914 }
2915
2916 // Function types don't have any default arguments, so just check if
2917 // we have enough arguments.
2918 if (NumArgs < NumArgsInProto) {
2919 // Not enough arguments.
2920 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002921 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002922 return;
2923 }
2924
2925 // Determine the implicit conversion sequences for each of the
2926 // arguments.
2927 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2928 if (ArgIdx < NumArgsInProto) {
2929 // (C++ 13.3.2p3): for F to be a viable function, there shall
2930 // exist for each argument an implicit conversion sequence
2931 // (13.3.3.1) that converts that argument to the corresponding
2932 // parameter of F.
2933 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002934 Candidate.Conversions[ArgIdx + 1]
2935 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002936 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002937 /*ForceRValue=*/false,
2938 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00002939 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002940 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002941 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002942 break;
2943 }
2944 } else {
2945 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2946 // argument for which there is no corresponding parameter is
2947 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002948 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002949 }
2950 }
2951}
2952
Mike Stump87c57ac2009-05-16 07:39:55 +00002953// FIXME: This will eventually be removed, once we've migrated all of the
2954// operator overloading logic over to the scheme used by binary operators, which
2955// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002956void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002957 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002958 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002959 OverloadCandidateSet& CandidateSet,
2960 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002961 FunctionSet Functions;
2962
2963 QualType T1 = Args[0]->getType();
2964 QualType T2;
2965 if (NumArgs > 1)
2966 T2 = Args[1]->getType();
2967
2968 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002969 if (S)
2970 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002971 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002972 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2973 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002974 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002975}
2976
2977/// \brief Add overload candidates for overloaded operators that are
2978/// member functions.
2979///
2980/// Add the overloaded operator candidates that are member functions
2981/// for the operator Op that was used in an operator expression such
2982/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2983/// CandidateSet will store the added overload candidates. (C++
2984/// [over.match.oper]).
2985void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2986 SourceLocation OpLoc,
2987 Expr **Args, unsigned NumArgs,
2988 OverloadCandidateSet& CandidateSet,
2989 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002990 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2991
2992 // C++ [over.match.oper]p3:
2993 // For a unary operator @ with an operand of a type whose
2994 // cv-unqualified version is T1, and for a binary operator @ with
2995 // a left operand of a type whose cv-unqualified version is T1 and
2996 // a right operand of a type whose cv-unqualified version is T2,
2997 // three sets of candidate functions, designated member
2998 // candidates, non-member candidates and built-in candidates, are
2999 // constructed as follows:
3000 QualType T1 = Args[0]->getType();
3001 QualType T2;
3002 if (NumArgs > 1)
3003 T2 = Args[1]->getType();
3004
3005 // -- If T1 is a class type, the set of member candidates is the
3006 // result of the qualified lookup of T1::operator@
3007 // (13.3.1.1.1); otherwise, the set of member candidates is
3008 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003009 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003010 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003011 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003012 return;
Mike Stump11289f42009-09-09 15:08:12 +00003013
John McCall27b18f82009-11-17 02:14:36 +00003014 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3015 LookupQualifiedName(Operators, T1Rec->getDecl());
3016 Operators.suppressDiagnostics();
3017
Mike Stump11289f42009-09-09 15:08:12 +00003018 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003019 OperEnd = Operators.end();
3020 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003021 ++Oper)
John McCall6e9f8f62009-12-03 04:06:58 +00003022 AddMethodCandidate(*Oper, Args[0]->getType(),
3023 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003024 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003025 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003026}
3027
Douglas Gregora11693b2008-11-12 17:17:38 +00003028/// AddBuiltinCandidate - Add a candidate for a built-in
3029/// operator. ResultTy and ParamTys are the result and parameter types
3030/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003031/// arguments being passed to the candidate. IsAssignmentOperator
3032/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003033/// operator. NumContextualBoolArguments is the number of arguments
3034/// (at the beginning of the argument list) that will be contextually
3035/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003036void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003037 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003038 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003039 bool IsAssignmentOperator,
3040 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003041 // Overload resolution is always an unevaluated context.
3042 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3043
Douglas Gregora11693b2008-11-12 17:17:38 +00003044 // Add this candidate
3045 CandidateSet.push_back(OverloadCandidate());
3046 OverloadCandidate& Candidate = CandidateSet.back();
3047 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003048 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003049 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003050 Candidate.BuiltinTypes.ResultTy = ResultTy;
3051 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3052 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3053
3054 // Determine the implicit conversion sequences for each of the
3055 // arguments.
3056 Candidate.Viable = true;
3057 Candidate.Conversions.resize(NumArgs);
3058 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003059 // C++ [over.match.oper]p4:
3060 // For the built-in assignment operators, conversions of the
3061 // left operand are restricted as follows:
3062 // -- no temporaries are introduced to hold the left operand, and
3063 // -- no user-defined conversions are applied to the left
3064 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003065 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003066 //
3067 // We block these conversions by turning off user-defined
3068 // conversions, since that is the only way that initialization of
3069 // a reference to a non-class type can occur from something that
3070 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003071 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003072 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003073 "Contextual conversion to bool requires bool type");
3074 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3075 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003076 Candidate.Conversions[ArgIdx]
3077 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003078 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003079 /*ForceRValue=*/false,
3080 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003081 }
John McCall0d1da222010-01-12 00:44:57 +00003082 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003083 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003084 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003085 break;
3086 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003087 }
3088}
3089
3090/// BuiltinCandidateTypeSet - A set of types that will be used for the
3091/// candidate operator functions for built-in operators (C++
3092/// [over.built]). The types are separated into pointer types and
3093/// enumeration types.
3094class BuiltinCandidateTypeSet {
3095 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003096 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003097
3098 /// PointerTypes - The set of pointer types that will be used in the
3099 /// built-in candidates.
3100 TypeSet PointerTypes;
3101
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003102 /// MemberPointerTypes - The set of member pointer types that will be
3103 /// used in the built-in candidates.
3104 TypeSet MemberPointerTypes;
3105
Douglas Gregora11693b2008-11-12 17:17:38 +00003106 /// EnumerationTypes - The set of enumeration types that will be
3107 /// used in the built-in candidates.
3108 TypeSet EnumerationTypes;
3109
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003110 /// Sema - The semantic analysis instance where we are building the
3111 /// candidate type set.
3112 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003113
Douglas Gregora11693b2008-11-12 17:17:38 +00003114 /// Context - The AST context in which we will build the type sets.
3115 ASTContext &Context;
3116
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003117 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3118 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003119 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003120
3121public:
3122 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003123 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003124
Mike Stump11289f42009-09-09 15:08:12 +00003125 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003126 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003127
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003128 void AddTypesConvertedFrom(QualType Ty,
3129 SourceLocation Loc,
3130 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003131 bool AllowExplicitConversions,
3132 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003133
3134 /// pointer_begin - First pointer type found;
3135 iterator pointer_begin() { return PointerTypes.begin(); }
3136
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003137 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003138 iterator pointer_end() { return PointerTypes.end(); }
3139
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003140 /// member_pointer_begin - First member pointer type found;
3141 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3142
3143 /// member_pointer_end - Past the last member pointer type found;
3144 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3145
Douglas Gregora11693b2008-11-12 17:17:38 +00003146 /// enumeration_begin - First enumeration type found;
3147 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3148
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003149 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003150 iterator enumeration_end() { return EnumerationTypes.end(); }
3151};
3152
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003153/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003154/// the set of pointer types along with any more-qualified variants of
3155/// that type. For example, if @p Ty is "int const *", this routine
3156/// will add "int const *", "int const volatile *", "int const
3157/// restrict *", and "int const volatile restrict *" to the set of
3158/// pointer types. Returns true if the add of @p Ty itself succeeded,
3159/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003160///
3161/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003162bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003163BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3164 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003165
Douglas Gregora11693b2008-11-12 17:17:38 +00003166 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003167 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003168 return false;
3169
John McCall8ccfcb52009-09-24 19:53:00 +00003170 const PointerType *PointerTy = Ty->getAs<PointerType>();
3171 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003172
John McCall8ccfcb52009-09-24 19:53:00 +00003173 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003174 // Don't add qualified variants of arrays. For one, they're not allowed
3175 // (the qualifier would sink to the element type), and for another, the
3176 // only overload situation where it matters is subscript or pointer +- int,
3177 // and those shouldn't have qualifier variants anyway.
3178 if (PointeeTy->isArrayType())
3179 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003180 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003181 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003182 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003183 bool hasVolatile = VisibleQuals.hasVolatile();
3184 bool hasRestrict = VisibleQuals.hasRestrict();
3185
John McCall8ccfcb52009-09-24 19:53:00 +00003186 // Iterate through all strict supersets of BaseCVR.
3187 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3188 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003189 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3190 // in the types.
3191 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3192 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003193 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3194 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003195 }
3196
3197 return true;
3198}
3199
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003200/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3201/// to the set of pointer types along with any more-qualified variants of
3202/// that type. For example, if @p Ty is "int const *", this routine
3203/// will add "int const *", "int const volatile *", "int const
3204/// restrict *", and "int const volatile restrict *" to the set of
3205/// pointer types. Returns true if the add of @p Ty itself succeeded,
3206/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003207///
3208/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003209bool
3210BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3211 QualType Ty) {
3212 // Insert this type.
3213 if (!MemberPointerTypes.insert(Ty))
3214 return false;
3215
John McCall8ccfcb52009-09-24 19:53:00 +00003216 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3217 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003218
John McCall8ccfcb52009-09-24 19:53:00 +00003219 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003220 // Don't add qualified variants of arrays. For one, they're not allowed
3221 // (the qualifier would sink to the element type), and for another, the
3222 // only overload situation where it matters is subscript or pointer +- int,
3223 // and those shouldn't have qualifier variants anyway.
3224 if (PointeeTy->isArrayType())
3225 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003226 const Type *ClassTy = PointerTy->getClass();
3227
3228 // Iterate through all strict supersets of the pointee type's CVR
3229 // qualifiers.
3230 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3231 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3232 if ((CVR | BaseCVR) != CVR) continue;
3233
3234 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3235 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003236 }
3237
3238 return true;
3239}
3240
Douglas Gregora11693b2008-11-12 17:17:38 +00003241/// AddTypesConvertedFrom - Add each of the types to which the type @p
3242/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003243/// primarily interested in pointer types and enumeration types. We also
3244/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003245/// AllowUserConversions is true if we should look at the conversion
3246/// functions of a class type, and AllowExplicitConversions if we
3247/// should also include the explicit conversion functions of a class
3248/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003249void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003250BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003251 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003252 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003253 bool AllowExplicitConversions,
3254 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003255 // Only deal with canonical types.
3256 Ty = Context.getCanonicalType(Ty);
3257
3258 // Look through reference types; they aren't part of the type of an
3259 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003260 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003261 Ty = RefTy->getPointeeType();
3262
3263 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003264 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003265
Sebastian Redl65ae2002009-11-05 16:36:20 +00003266 // If we're dealing with an array type, decay to the pointer.
3267 if (Ty->isArrayType())
3268 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3269
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003270 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003271 QualType PointeeTy = PointerTy->getPointeeType();
3272
3273 // Insert our type, and its more-qualified variants, into the set
3274 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003275 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003276 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003277 } else if (Ty->isMemberPointerType()) {
3278 // Member pointers are far easier, since the pointee can't be converted.
3279 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3280 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003281 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003282 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003283 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003284 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003285 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003286 // No conversion functions in incomplete types.
3287 return;
3288 }
Mike Stump11289f42009-09-09 15:08:12 +00003289
Douglas Gregora11693b2008-11-12 17:17:38 +00003290 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003291 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003292 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003293 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003294 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003295
Mike Stump11289f42009-09-09 15:08:12 +00003296 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003297 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003298 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003299 continue;
3300
John McCalld14a8642009-11-21 08:51:07 +00003301 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003302 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003303 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003304 VisibleQuals);
3305 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003306 }
3307 }
3308 }
3309}
3310
Douglas Gregor84605ae2009-08-24 13:43:27 +00003311/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3312/// the volatile- and non-volatile-qualified assignment operators for the
3313/// given type to the candidate set.
3314static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3315 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003316 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003317 unsigned NumArgs,
3318 OverloadCandidateSet &CandidateSet) {
3319 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003320
Douglas Gregor84605ae2009-08-24 13:43:27 +00003321 // T& operator=(T&, T)
3322 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3323 ParamTypes[1] = T;
3324 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3325 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003326
Douglas Gregor84605ae2009-08-24 13:43:27 +00003327 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3328 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003329 ParamTypes[0]
3330 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003331 ParamTypes[1] = T;
3332 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003333 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003334 }
3335}
Mike Stump11289f42009-09-09 15:08:12 +00003336
Sebastian Redl1054fae2009-10-25 17:03:50 +00003337/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3338/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003339static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3340 Qualifiers VRQuals;
3341 const RecordType *TyRec;
3342 if (const MemberPointerType *RHSMPType =
3343 ArgExpr->getType()->getAs<MemberPointerType>())
3344 TyRec = cast<RecordType>(RHSMPType->getClass());
3345 else
3346 TyRec = ArgExpr->getType()->getAs<RecordType>();
3347 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003348 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003349 VRQuals.addVolatile();
3350 VRQuals.addRestrict();
3351 return VRQuals;
3352 }
3353
3354 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003355 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003356 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003357
John McCallad371252010-01-20 00:46:10 +00003358 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003359 E = Conversions->end(); I != E; ++I) {
3360 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003361 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3362 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3363 CanTy = ResTypeRef->getPointeeType();
3364 // Need to go down the pointer/mempointer chain and add qualifiers
3365 // as see them.
3366 bool done = false;
3367 while (!done) {
3368 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3369 CanTy = ResTypePtr->getPointeeType();
3370 else if (const MemberPointerType *ResTypeMPtr =
3371 CanTy->getAs<MemberPointerType>())
3372 CanTy = ResTypeMPtr->getPointeeType();
3373 else
3374 done = true;
3375 if (CanTy.isVolatileQualified())
3376 VRQuals.addVolatile();
3377 if (CanTy.isRestrictQualified())
3378 VRQuals.addRestrict();
3379 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3380 return VRQuals;
3381 }
3382 }
3383 }
3384 return VRQuals;
3385}
3386
Douglas Gregord08452f2008-11-19 15:42:04 +00003387/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3388/// operator overloads to the candidate set (C++ [over.built]), based
3389/// on the operator @p Op and the arguments given. For example, if the
3390/// operator is a binary '+', this routine might add "int
3391/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003392void
Mike Stump11289f42009-09-09 15:08:12 +00003393Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003394 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003395 Expr **Args, unsigned NumArgs,
3396 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003397 // The set of "promoted arithmetic types", which are the arithmetic
3398 // types are that preserved by promotion (C++ [over.built]p2). Note
3399 // that the first few of these types are the promoted integral
3400 // types; these types need to be first.
3401 // FIXME: What about complex?
3402 const unsigned FirstIntegralType = 0;
3403 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003404 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003405 LastPromotedIntegralType = 13;
3406 const unsigned FirstPromotedArithmeticType = 7,
3407 LastPromotedArithmeticType = 16;
3408 const unsigned NumArithmeticTypes = 16;
3409 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003410 Context.BoolTy, Context.CharTy, Context.WCharTy,
3411// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003412 Context.SignedCharTy, Context.ShortTy,
3413 Context.UnsignedCharTy, Context.UnsignedShortTy,
3414 Context.IntTy, Context.LongTy, Context.LongLongTy,
3415 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3416 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3417 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003418 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3419 "Invalid first promoted integral type");
3420 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3421 == Context.UnsignedLongLongTy &&
3422 "Invalid last promoted integral type");
3423 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3424 "Invalid first promoted arithmetic type");
3425 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3426 == Context.LongDoubleTy &&
3427 "Invalid last promoted arithmetic type");
3428
Douglas Gregora11693b2008-11-12 17:17:38 +00003429 // Find all of the types that the arguments can convert to, but only
3430 // if the operator we're looking at has built-in operator candidates
3431 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003432 Qualifiers VisibleTypeConversionsQuals;
3433 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003434 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3435 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3436
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003437 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003438 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3439 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003440 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003441 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003442 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003443 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003444 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003445 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003446 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003447 true,
3448 (Op == OO_Exclaim ||
3449 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003450 Op == OO_PipePipe),
3451 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003452 }
3453
3454 bool isComparison = false;
3455 switch (Op) {
3456 case OO_None:
3457 case NUM_OVERLOADED_OPERATORS:
3458 assert(false && "Expected an overloaded operator");
3459 break;
3460
Douglas Gregord08452f2008-11-19 15:42:04 +00003461 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003462 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003463 goto UnaryStar;
3464 else
3465 goto BinaryStar;
3466 break;
3467
3468 case OO_Plus: // '+' is either unary or binary
3469 if (NumArgs == 1)
3470 goto UnaryPlus;
3471 else
3472 goto BinaryPlus;
3473 break;
3474
3475 case OO_Minus: // '-' is either unary or binary
3476 if (NumArgs == 1)
3477 goto UnaryMinus;
3478 else
3479 goto BinaryMinus;
3480 break;
3481
3482 case OO_Amp: // '&' is either unary or binary
3483 if (NumArgs == 1)
3484 goto UnaryAmp;
3485 else
3486 goto BinaryAmp;
3487
3488 case OO_PlusPlus:
3489 case OO_MinusMinus:
3490 // C++ [over.built]p3:
3491 //
3492 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3493 // is either volatile or empty, there exist candidate operator
3494 // functions of the form
3495 //
3496 // VQ T& operator++(VQ T&);
3497 // T operator++(VQ T&, int);
3498 //
3499 // C++ [over.built]p4:
3500 //
3501 // For every pair (T, VQ), where T is an arithmetic type other
3502 // than bool, and VQ is either volatile or empty, there exist
3503 // candidate operator functions of the form
3504 //
3505 // VQ T& operator--(VQ T&);
3506 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003507 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003508 Arith < NumArithmeticTypes; ++Arith) {
3509 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003510 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003511 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003512
3513 // Non-volatile version.
3514 if (NumArgs == 1)
3515 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3516 else
3517 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003518 // heuristic to reduce number of builtin candidates in the set.
3519 // Add volatile version only if there are conversions to a volatile type.
3520 if (VisibleTypeConversionsQuals.hasVolatile()) {
3521 // Volatile version
3522 ParamTypes[0]
3523 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3524 if (NumArgs == 1)
3525 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3526 else
3527 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3528 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003529 }
3530
3531 // C++ [over.built]p5:
3532 //
3533 // For every pair (T, VQ), where T is a cv-qualified or
3534 // cv-unqualified object type, and VQ is either volatile or
3535 // empty, there exist candidate operator functions of the form
3536 //
3537 // T*VQ& operator++(T*VQ&);
3538 // T*VQ& operator--(T*VQ&);
3539 // T* operator++(T*VQ&, int);
3540 // T* operator--(T*VQ&, int);
3541 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3542 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3543 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003544 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003545 continue;
3546
Mike Stump11289f42009-09-09 15:08:12 +00003547 QualType ParamTypes[2] = {
3548 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003549 };
Mike Stump11289f42009-09-09 15:08:12 +00003550
Douglas Gregord08452f2008-11-19 15:42:04 +00003551 // Without volatile
3552 if (NumArgs == 1)
3553 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3554 else
3555 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3556
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003557 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3558 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003559 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003560 ParamTypes[0]
3561 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003562 if (NumArgs == 1)
3563 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3564 else
3565 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3566 }
3567 }
3568 break;
3569
3570 UnaryStar:
3571 // C++ [over.built]p6:
3572 // For every cv-qualified or cv-unqualified object type T, there
3573 // exist candidate operator functions of the form
3574 //
3575 // T& operator*(T*);
3576 //
3577 // C++ [over.built]p7:
3578 // For every function type T, there exist candidate operator
3579 // functions of the form
3580 // T& operator*(T*);
3581 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3582 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3583 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003584 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003585 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003586 &ParamTy, Args, 1, CandidateSet);
3587 }
3588 break;
3589
3590 UnaryPlus:
3591 // C++ [over.built]p8:
3592 // For every type T, there exist candidate operator functions of
3593 // the form
3594 //
3595 // T* operator+(T*);
3596 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3597 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3598 QualType ParamTy = *Ptr;
3599 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3600 }
Mike Stump11289f42009-09-09 15:08:12 +00003601
Douglas Gregord08452f2008-11-19 15:42:04 +00003602 // Fall through
3603
3604 UnaryMinus:
3605 // C++ [over.built]p9:
3606 // For every promoted arithmetic type T, there exist candidate
3607 // operator functions of the form
3608 //
3609 // T operator+(T);
3610 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003611 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003612 Arith < LastPromotedArithmeticType; ++Arith) {
3613 QualType ArithTy = ArithmeticTypes[Arith];
3614 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3615 }
3616 break;
3617
3618 case OO_Tilde:
3619 // C++ [over.built]p10:
3620 // For every promoted integral type T, there exist candidate
3621 // operator functions of the form
3622 //
3623 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003624 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003625 Int < LastPromotedIntegralType; ++Int) {
3626 QualType IntTy = ArithmeticTypes[Int];
3627 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3628 }
3629 break;
3630
Douglas Gregora11693b2008-11-12 17:17:38 +00003631 case OO_New:
3632 case OO_Delete:
3633 case OO_Array_New:
3634 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003635 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003636 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003637 break;
3638
3639 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003640 UnaryAmp:
3641 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003642 // C++ [over.match.oper]p3:
3643 // -- For the operator ',', the unary operator '&', or the
3644 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003645 break;
3646
Douglas Gregor84605ae2009-08-24 13:43:27 +00003647 case OO_EqualEqual:
3648 case OO_ExclaimEqual:
3649 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003650 // For every pointer to member type T, there exist candidate operator
3651 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003652 //
3653 // bool operator==(T,T);
3654 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003655 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003656 MemPtr = CandidateTypes.member_pointer_begin(),
3657 MemPtrEnd = CandidateTypes.member_pointer_end();
3658 MemPtr != MemPtrEnd;
3659 ++MemPtr) {
3660 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3661 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3662 }
Mike Stump11289f42009-09-09 15:08:12 +00003663
Douglas Gregor84605ae2009-08-24 13:43:27 +00003664 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003665
Douglas Gregora11693b2008-11-12 17:17:38 +00003666 case OO_Less:
3667 case OO_Greater:
3668 case OO_LessEqual:
3669 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003670 // C++ [over.built]p15:
3671 //
3672 // For every pointer or enumeration type T, there exist
3673 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003674 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003675 // bool operator<(T, T);
3676 // bool operator>(T, T);
3677 // bool operator<=(T, T);
3678 // bool operator>=(T, T);
3679 // bool operator==(T, T);
3680 // bool operator!=(T, T);
3681 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3682 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3683 QualType ParamTypes[2] = { *Ptr, *Ptr };
3684 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3685 }
Mike Stump11289f42009-09-09 15:08:12 +00003686 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003687 = CandidateTypes.enumeration_begin();
3688 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3689 QualType ParamTypes[2] = { *Enum, *Enum };
3690 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3691 }
3692
3693 // Fall through.
3694 isComparison = true;
3695
Douglas Gregord08452f2008-11-19 15:42:04 +00003696 BinaryPlus:
3697 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003698 if (!isComparison) {
3699 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3700
3701 // C++ [over.built]p13:
3702 //
3703 // For every cv-qualified or cv-unqualified object type T
3704 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003705 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003706 // T* operator+(T*, ptrdiff_t);
3707 // T& operator[](T*, ptrdiff_t); [BELOW]
3708 // T* operator-(T*, ptrdiff_t);
3709 // T* operator+(ptrdiff_t, T*);
3710 // T& operator[](ptrdiff_t, T*); [BELOW]
3711 //
3712 // C++ [over.built]p14:
3713 //
3714 // For every T, where T is a pointer to object type, there
3715 // exist candidate operator functions of the form
3716 //
3717 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003718 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003719 = CandidateTypes.pointer_begin();
3720 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3721 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3722
3723 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3724 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3725
3726 if (Op == OO_Plus) {
3727 // T* operator+(ptrdiff_t, T*);
3728 ParamTypes[0] = ParamTypes[1];
3729 ParamTypes[1] = *Ptr;
3730 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3731 } else {
3732 // ptrdiff_t operator-(T, T);
3733 ParamTypes[1] = *Ptr;
3734 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3735 Args, 2, CandidateSet);
3736 }
3737 }
3738 }
3739 // Fall through
3740
Douglas Gregora11693b2008-11-12 17:17:38 +00003741 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003742 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003743 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003744 // C++ [over.built]p12:
3745 //
3746 // For every pair of promoted arithmetic types L and R, there
3747 // exist candidate operator functions of the form
3748 //
3749 // LR operator*(L, R);
3750 // LR operator/(L, R);
3751 // LR operator+(L, R);
3752 // LR operator-(L, R);
3753 // bool operator<(L, R);
3754 // bool operator>(L, R);
3755 // bool operator<=(L, R);
3756 // bool operator>=(L, R);
3757 // bool operator==(L, R);
3758 // bool operator!=(L, R);
3759 //
3760 // where LR is the result of the usual arithmetic conversions
3761 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003762 //
3763 // C++ [over.built]p24:
3764 //
3765 // For every pair of promoted arithmetic types L and R, there exist
3766 // candidate operator functions of the form
3767 //
3768 // LR operator?(bool, L, R);
3769 //
3770 // where LR is the result of the usual arithmetic conversions
3771 // between types L and R.
3772 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003773 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003774 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003775 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003776 Right < LastPromotedArithmeticType; ++Right) {
3777 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003778 QualType Result
3779 = isComparison
3780 ? Context.BoolTy
3781 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003782 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3783 }
3784 }
3785 break;
3786
3787 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003788 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003789 case OO_Caret:
3790 case OO_Pipe:
3791 case OO_LessLess:
3792 case OO_GreaterGreater:
3793 // C++ [over.built]p17:
3794 //
3795 // For every pair of promoted integral types L and R, there
3796 // exist candidate operator functions of the form
3797 //
3798 // LR operator%(L, R);
3799 // LR operator&(L, R);
3800 // LR operator^(L, R);
3801 // LR operator|(L, R);
3802 // L operator<<(L, R);
3803 // L operator>>(L, R);
3804 //
3805 // where LR is the result of the usual arithmetic conversions
3806 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003807 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003808 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003809 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003810 Right < LastPromotedIntegralType; ++Right) {
3811 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3812 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3813 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003814 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003815 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3816 }
3817 }
3818 break;
3819
3820 case OO_Equal:
3821 // C++ [over.built]p20:
3822 //
3823 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003824 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003825 // empty, there exist candidate operator functions of the form
3826 //
3827 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003828 for (BuiltinCandidateTypeSet::iterator
3829 Enum = CandidateTypes.enumeration_begin(),
3830 EnumEnd = CandidateTypes.enumeration_end();
3831 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003832 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003833 CandidateSet);
3834 for (BuiltinCandidateTypeSet::iterator
3835 MemPtr = CandidateTypes.member_pointer_begin(),
3836 MemPtrEnd = CandidateTypes.member_pointer_end();
3837 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003838 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003839 CandidateSet);
3840 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003841
3842 case OO_PlusEqual:
3843 case OO_MinusEqual:
3844 // C++ [over.built]p19:
3845 //
3846 // For every pair (T, VQ), where T is any type and VQ is either
3847 // volatile or empty, there exist candidate operator functions
3848 // of the form
3849 //
3850 // T*VQ& operator=(T*VQ&, T*);
3851 //
3852 // C++ [over.built]p21:
3853 //
3854 // For every pair (T, VQ), where T is a cv-qualified or
3855 // cv-unqualified object type and VQ is either volatile or
3856 // empty, there exist candidate operator functions of the form
3857 //
3858 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3859 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3860 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3861 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3862 QualType ParamTypes[2];
3863 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3864
3865 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003866 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003867 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3868 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003869
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003870 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3871 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003872 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003873 ParamTypes[0]
3874 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003875 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3876 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003877 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003878 }
3879 // Fall through.
3880
3881 case OO_StarEqual:
3882 case OO_SlashEqual:
3883 // C++ [over.built]p18:
3884 //
3885 // For every triple (L, VQ, R), where L is an arithmetic type,
3886 // VQ is either volatile or empty, and R is a promoted
3887 // arithmetic type, there exist candidate operator functions of
3888 // the form
3889 //
3890 // VQ L& operator=(VQ L&, R);
3891 // VQ L& operator*=(VQ L&, R);
3892 // VQ L& operator/=(VQ L&, R);
3893 // VQ L& operator+=(VQ L&, R);
3894 // VQ L& operator-=(VQ L&, R);
3895 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003896 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003897 Right < LastPromotedArithmeticType; ++Right) {
3898 QualType ParamTypes[2];
3899 ParamTypes[1] = ArithmeticTypes[Right];
3900
3901 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003902 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003903 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3904 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003905
3906 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003907 if (VisibleTypeConversionsQuals.hasVolatile()) {
3908 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3909 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3910 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3911 /*IsAssigmentOperator=*/Op == OO_Equal);
3912 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003913 }
3914 }
3915 break;
3916
3917 case OO_PercentEqual:
3918 case OO_LessLessEqual:
3919 case OO_GreaterGreaterEqual:
3920 case OO_AmpEqual:
3921 case OO_CaretEqual:
3922 case OO_PipeEqual:
3923 // C++ [over.built]p22:
3924 //
3925 // For every triple (L, VQ, R), where L is an integral type, VQ
3926 // is either volatile or empty, and R is a promoted integral
3927 // type, there exist candidate operator functions of the form
3928 //
3929 // VQ L& operator%=(VQ L&, R);
3930 // VQ L& operator<<=(VQ L&, R);
3931 // VQ L& operator>>=(VQ L&, R);
3932 // VQ L& operator&=(VQ L&, R);
3933 // VQ L& operator^=(VQ L&, R);
3934 // VQ L& operator|=(VQ L&, R);
3935 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003936 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003937 Right < LastPromotedIntegralType; ++Right) {
3938 QualType ParamTypes[2];
3939 ParamTypes[1] = ArithmeticTypes[Right];
3940
3941 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003942 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003943 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003944 if (VisibleTypeConversionsQuals.hasVolatile()) {
3945 // Add this built-in operator as a candidate (VQ is 'volatile').
3946 ParamTypes[0] = ArithmeticTypes[Left];
3947 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3948 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3949 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3950 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003951 }
3952 }
3953 break;
3954
Douglas Gregord08452f2008-11-19 15:42:04 +00003955 case OO_Exclaim: {
3956 // C++ [over.operator]p23:
3957 //
3958 // There also exist candidate operator functions of the form
3959 //
Mike Stump11289f42009-09-09 15:08:12 +00003960 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003961 // bool operator&&(bool, bool); [BELOW]
3962 // bool operator||(bool, bool); [BELOW]
3963 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003964 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3965 /*IsAssignmentOperator=*/false,
3966 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003967 break;
3968 }
3969
Douglas Gregora11693b2008-11-12 17:17:38 +00003970 case OO_AmpAmp:
3971 case OO_PipePipe: {
3972 // C++ [over.operator]p23:
3973 //
3974 // There also exist candidate operator functions of the form
3975 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003976 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003977 // bool operator&&(bool, bool);
3978 // bool operator||(bool, bool);
3979 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003980 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3981 /*IsAssignmentOperator=*/false,
3982 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003983 break;
3984 }
3985
3986 case OO_Subscript:
3987 // C++ [over.built]p13:
3988 //
3989 // For every cv-qualified or cv-unqualified object type T there
3990 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003991 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003992 // T* operator+(T*, ptrdiff_t); [ABOVE]
3993 // T& operator[](T*, ptrdiff_t);
3994 // T* operator-(T*, ptrdiff_t); [ABOVE]
3995 // T* operator+(ptrdiff_t, T*); [ABOVE]
3996 // T& operator[](ptrdiff_t, T*);
3997 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3998 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3999 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004000 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004001 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004002
4003 // T& operator[](T*, ptrdiff_t)
4004 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4005
4006 // T& operator[](ptrdiff_t, T*);
4007 ParamTypes[0] = ParamTypes[1];
4008 ParamTypes[1] = *Ptr;
4009 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4010 }
4011 break;
4012
4013 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004014 // C++ [over.built]p11:
4015 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4016 // C1 is the same type as C2 or is a derived class of C2, T is an object
4017 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4018 // there exist candidate operator functions of the form
4019 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4020 // where CV12 is the union of CV1 and CV2.
4021 {
4022 for (BuiltinCandidateTypeSet::iterator Ptr =
4023 CandidateTypes.pointer_begin();
4024 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4025 QualType C1Ty = (*Ptr);
4026 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004027 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004028 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004029 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004030 if (!isa<RecordType>(C1))
4031 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004032 // heuristic to reduce number of builtin candidates in the set.
4033 // Add volatile/restrict version only if there are conversions to a
4034 // volatile/restrict type.
4035 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4036 continue;
4037 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4038 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004039 }
4040 for (BuiltinCandidateTypeSet::iterator
4041 MemPtr = CandidateTypes.member_pointer_begin(),
4042 MemPtrEnd = CandidateTypes.member_pointer_end();
4043 MemPtr != MemPtrEnd; ++MemPtr) {
4044 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4045 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004046 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004047 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4048 break;
4049 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4050 // build CV12 T&
4051 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004052 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4053 T.isVolatileQualified())
4054 continue;
4055 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4056 T.isRestrictQualified())
4057 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004058 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004059 QualType ResultTy = Context.getLValueReferenceType(T);
4060 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4061 }
4062 }
4063 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004064 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004065
4066 case OO_Conditional:
4067 // Note that we don't consider the first argument, since it has been
4068 // contextually converted to bool long ago. The candidates below are
4069 // therefore added as binary.
4070 //
4071 // C++ [over.built]p24:
4072 // For every type T, where T is a pointer or pointer-to-member type,
4073 // there exist candidate operator functions of the form
4074 //
4075 // T operator?(bool, T, T);
4076 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004077 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4078 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4079 QualType ParamTypes[2] = { *Ptr, *Ptr };
4080 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4081 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004082 for (BuiltinCandidateTypeSet::iterator Ptr =
4083 CandidateTypes.member_pointer_begin(),
4084 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4085 QualType ParamTypes[2] = { *Ptr, *Ptr };
4086 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4087 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004088 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004089 }
4090}
4091
Douglas Gregore254f902009-02-04 00:32:51 +00004092/// \brief Add function candidates found via argument-dependent lookup
4093/// to the set of overloading candidates.
4094///
4095/// This routine performs argument-dependent name lookup based on the
4096/// given function name (which may also be an operator name) and adds
4097/// all of the overload candidates found by ADL to the overload
4098/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004099void
Douglas Gregore254f902009-02-04 00:32:51 +00004100Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4101 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004102 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004103 OverloadCandidateSet& CandidateSet,
4104 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004105 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00004106
Douglas Gregorcabea402009-09-22 15:41:20 +00004107 // FIXME: Should we be trafficking in canonical function decls throughout?
4108
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004109 // Record all of the function candidates that we've already
4110 // added to the overload set, so that we don't add those same
4111 // candidates a second time.
4112 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4113 CandEnd = CandidateSet.end();
4114 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004115 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004116 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004117 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4118 Functions.insert(FunTmpl);
4119 }
Douglas Gregore254f902009-02-04 00:32:51 +00004120
Douglas Gregorcabea402009-09-22 15:41:20 +00004121 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00004122 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00004123
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004124 // Erase all of the candidates we already knew about.
4125 // FIXME: This is suboptimal. Is there a better way?
4126 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4127 CandEnd = CandidateSet.end();
4128 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004129 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004130 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004131 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4132 Functions.erase(FunTmpl);
4133 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004134
4135 // For each of the ADL candidates we found, add it to the overload
4136 // set.
4137 for (FunctionSet::iterator Func = Functions.begin(),
4138 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00004139 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004140 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCall6b51f282009-11-23 01:53:49 +00004141 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004142 continue;
4143
4144 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4145 false, false, PartialOverloading);
4146 } else
Mike Stump11289f42009-09-09 15:08:12 +00004147 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00004148 ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004149 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004150 }
Douglas Gregore254f902009-02-04 00:32:51 +00004151}
4152
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004153/// isBetterOverloadCandidate - Determines whether the first overload
4154/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004155bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004156Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00004157 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004158 // Define viable functions to be better candidates than non-viable
4159 // functions.
4160 if (!Cand2.Viable)
4161 return Cand1.Viable;
4162 else if (!Cand1.Viable)
4163 return false;
4164
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004165 // C++ [over.match.best]p1:
4166 //
4167 // -- if F is a static member function, ICS1(F) is defined such
4168 // that ICS1(F) is neither better nor worse than ICS1(G) for
4169 // any function G, and, symmetrically, ICS1(G) is neither
4170 // better nor worse than ICS1(F).
4171 unsigned StartArg = 0;
4172 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4173 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004174
Douglas Gregord3cb3562009-07-07 23:38:56 +00004175 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004176 // A viable function F1 is defined to be a better function than another
4177 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004178 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004179 unsigned NumArgs = Cand1.Conversions.size();
4180 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4181 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004182 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004183 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4184 Cand2.Conversions[ArgIdx])) {
4185 case ImplicitConversionSequence::Better:
4186 // Cand1 has a better conversion sequence.
4187 HasBetterConversion = true;
4188 break;
4189
4190 case ImplicitConversionSequence::Worse:
4191 // Cand1 can't be better than Cand2.
4192 return false;
4193
4194 case ImplicitConversionSequence::Indistinguishable:
4195 // Do nothing.
4196 break;
4197 }
4198 }
4199
Mike Stump11289f42009-09-09 15:08:12 +00004200 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004201 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004202 if (HasBetterConversion)
4203 return true;
4204
Mike Stump11289f42009-09-09 15:08:12 +00004205 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004206 // specialization, or, if not that,
4207 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4208 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4209 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004210
4211 // -- F1 and F2 are function template specializations, and the function
4212 // template for F1 is more specialized than the template for F2
4213 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004214 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004215 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4216 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004217 if (FunctionTemplateDecl *BetterTemplate
4218 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4219 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004220 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4221 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004222 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004223
Douglas Gregora1f013e2008-11-07 22:36:19 +00004224 // -- the context is an initialization by user-defined conversion
4225 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4226 // from the return type of F1 to the destination type (i.e.,
4227 // the type of the entity being initialized) is a better
4228 // conversion sequence than the standard conversion sequence
4229 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004230 if (Cand1.Function && Cand2.Function &&
4231 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004232 isa<CXXConversionDecl>(Cand2.Function)) {
4233 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4234 Cand2.FinalConversion)) {
4235 case ImplicitConversionSequence::Better:
4236 // Cand1 has a better conversion sequence.
4237 return true;
4238
4239 case ImplicitConversionSequence::Worse:
4240 // Cand1 can't be better than Cand2.
4241 return false;
4242
4243 case ImplicitConversionSequence::Indistinguishable:
4244 // Do nothing
4245 break;
4246 }
4247 }
4248
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004249 return false;
4250}
4251
Mike Stump11289f42009-09-09 15:08:12 +00004252/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004253/// within an overload candidate set.
4254///
4255/// \param CandidateSet the set of candidate functions.
4256///
4257/// \param Loc the location of the function name (or operator symbol) for
4258/// which overload resolution occurs.
4259///
Mike Stump11289f42009-09-09 15:08:12 +00004260/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004261/// function, Best points to the candidate function found.
4262///
4263/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004264OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4265 SourceLocation Loc,
4266 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004267 // Find the best viable function.
4268 Best = CandidateSet.end();
4269 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4270 Cand != CandidateSet.end(); ++Cand) {
4271 if (Cand->Viable) {
4272 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4273 Best = Cand;
4274 }
4275 }
4276
4277 // If we didn't find any viable functions, abort.
4278 if (Best == CandidateSet.end())
4279 return OR_No_Viable_Function;
4280
4281 // Make sure that this function is better than every other viable
4282 // function. If not, we have an ambiguity.
4283 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4284 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004285 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004286 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004287 !isBetterOverloadCandidate(*Best, *Cand)) {
4288 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004289 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004290 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004291 }
Mike Stump11289f42009-09-09 15:08:12 +00004292
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004293 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004294 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004295 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004296 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004297 return OR_Deleted;
4298
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004299 // C++ [basic.def.odr]p2:
4300 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004301 // when referred to from a potentially-evaluated expression. [Note: this
4302 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004303 // (clause 13), user-defined conversions (12.3.2), allocation function for
4304 // placement new (5.3.4), as well as non-default initialization (8.5).
4305 if (Best->Function)
4306 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004307 return OR_Success;
4308}
4309
John McCall53262c92010-01-12 02:15:36 +00004310namespace {
4311
4312enum OverloadCandidateKind {
4313 oc_function,
4314 oc_method,
4315 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004316 oc_function_template,
4317 oc_method_template,
4318 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004319 oc_implicit_default_constructor,
4320 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004321 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004322};
4323
John McCalle1ac8d12010-01-13 00:25:19 +00004324OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4325 FunctionDecl *Fn,
4326 std::string &Description) {
4327 bool isTemplate = false;
4328
4329 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4330 isTemplate = true;
4331 Description = S.getTemplateArgumentBindingsText(
4332 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4333 }
John McCallfd0b2f82010-01-06 09:43:14 +00004334
4335 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004336 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004337 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004338
John McCall53262c92010-01-12 02:15:36 +00004339 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4340 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004341 }
4342
4343 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4344 // This actually gets spelled 'candidate function' for now, but
4345 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004346 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004347 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004348
4349 assert(Meth->isCopyAssignment()
4350 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004351 return oc_implicit_copy_assignment;
4352 }
4353
John McCalle1ac8d12010-01-13 00:25:19 +00004354 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004355}
4356
4357} // end anonymous namespace
4358
4359// Notes the location of an overload candidate.
4360void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004361 std::string FnDesc;
4362 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4363 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4364 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004365}
4366
John McCall0d1da222010-01-12 00:44:57 +00004367/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4368/// "lead" diagnostic; it will be given two arguments, the source and
4369/// target types of the conversion.
4370void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4371 SourceLocation CaretLoc,
4372 const PartialDiagnostic &PDiag) {
4373 Diag(CaretLoc, PDiag)
4374 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4375 for (AmbiguousConversionSequence::const_iterator
4376 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4377 NoteOverloadCandidate(*I);
4378 }
John McCall12f97bc2010-01-08 04:41:39 +00004379}
4380
John McCall0d1da222010-01-12 00:44:57 +00004381namespace {
4382
John McCall6a61b522010-01-13 09:16:55 +00004383void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4384 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4385 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004386 assert(Cand->Function && "for now, candidate must be a function");
4387 FunctionDecl *Fn = Cand->Function;
4388
4389 // There's a conversion slot for the object argument if this is a
4390 // non-constructor method. Note that 'I' corresponds the
4391 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004392 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004393 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004394 if (I == 0)
4395 isObjectArgument = true;
4396 else
4397 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004398 }
4399
John McCalle1ac8d12010-01-13 00:25:19 +00004400 std::string FnDesc;
4401 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4402
John McCall6a61b522010-01-13 09:16:55 +00004403 Expr *FromExpr = Conv.Bad.FromExpr;
4404 QualType FromTy = Conv.Bad.getFromType();
4405 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004406
John McCall47000992010-01-14 03:28:57 +00004407 // Do some hand-waving analysis to see if the non-viability is due to a
4408 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4409 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4410 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4411 CToTy = RT->getPointeeType();
4412 else {
4413 // TODO: detect and diagnose the full richness of const mismatches.
4414 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4415 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4416 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4417 }
4418
4419 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4420 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4421 // It is dumb that we have to do this here.
4422 while (isa<ArrayType>(CFromTy))
4423 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4424 while (isa<ArrayType>(CToTy))
4425 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4426
4427 Qualifiers FromQs = CFromTy.getQualifiers();
4428 Qualifiers ToQs = CToTy.getQualifiers();
4429
4430 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4431 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4432 << (unsigned) FnKind << FnDesc
4433 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4434 << FromTy
4435 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4436 << (unsigned) isObjectArgument << I+1;
4437 return;
4438 }
4439
4440 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4441 assert(CVR && "unexpected qualifiers mismatch");
4442
4443 if (isObjectArgument) {
4444 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4445 << (unsigned) FnKind << FnDesc
4446 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4447 << FromTy << (CVR - 1);
4448 } else {
4449 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4450 << (unsigned) FnKind << FnDesc
4451 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4452 << FromTy << (CVR - 1) << I+1;
4453 }
4454 return;
4455 }
4456
4457 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004458 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4459 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004460 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004461 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004462}
4463
4464void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4465 unsigned NumFormalArgs) {
4466 // TODO: treat calls to a missing default constructor as a special case
4467
4468 FunctionDecl *Fn = Cand->Function;
4469 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4470
4471 unsigned MinParams = Fn->getMinRequiredArguments();
4472
4473 // at least / at most / exactly
4474 unsigned mode, modeCount;
4475 if (NumFormalArgs < MinParams) {
4476 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4477 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4478 mode = 0; // "at least"
4479 else
4480 mode = 2; // "exactly"
4481 modeCount = MinParams;
4482 } else {
4483 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4484 if (MinParams != FnTy->getNumArgs())
4485 mode = 1; // "at most"
4486 else
4487 mode = 2; // "exactly"
4488 modeCount = FnTy->getNumArgs();
4489 }
4490
4491 std::string Description;
4492 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4493
4494 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4495 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004496}
4497
4498void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4499 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004500 FunctionDecl *Fn = Cand->Function;
4501
John McCall12f97bc2010-01-08 04:41:39 +00004502 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004503 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004504 std::string FnDesc;
4505 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004506
4507 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004508 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004509 return;
John McCall12f97bc2010-01-08 04:41:39 +00004510 }
4511
John McCalle1ac8d12010-01-13 00:25:19 +00004512 // We don't really have anything else to say about viable candidates.
4513 if (Cand->Viable) {
4514 S.NoteOverloadCandidate(Fn);
4515 return;
4516 }
John McCall0d1da222010-01-12 00:44:57 +00004517
John McCall6a61b522010-01-13 09:16:55 +00004518 switch (Cand->FailureKind) {
4519 case ovl_fail_too_many_arguments:
4520 case ovl_fail_too_few_arguments:
4521 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004522
John McCall6a61b522010-01-13 09:16:55 +00004523 case ovl_fail_bad_deduction:
4524 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004525
John McCall6a61b522010-01-13 09:16:55 +00004526 case ovl_fail_bad_conversion:
4527 for (unsigned I = 0, N = Cand->Conversions.size(); I != N; ++I)
4528 if (Cand->Conversions[I].isBad())
4529 return DiagnoseBadConversion(S, Cand, I);
4530
4531 // FIXME: this currently happens when we're called from SemaInit
4532 // when user-conversion overload fails. Figure out how to handle
4533 // those conditions and diagnose them well.
4534 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004535 }
John McCalld3224162010-01-08 00:58:21 +00004536}
4537
4538void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4539 // Desugar the type of the surrogate down to a function type,
4540 // retaining as many typedefs as possible while still showing
4541 // the function type (and, therefore, its parameter types).
4542 QualType FnType = Cand->Surrogate->getConversionType();
4543 bool isLValueReference = false;
4544 bool isRValueReference = false;
4545 bool isPointer = false;
4546 if (const LValueReferenceType *FnTypeRef =
4547 FnType->getAs<LValueReferenceType>()) {
4548 FnType = FnTypeRef->getPointeeType();
4549 isLValueReference = true;
4550 } else if (const RValueReferenceType *FnTypeRef =
4551 FnType->getAs<RValueReferenceType>()) {
4552 FnType = FnTypeRef->getPointeeType();
4553 isRValueReference = true;
4554 }
4555 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4556 FnType = FnTypePtr->getPointeeType();
4557 isPointer = true;
4558 }
4559 // Desugar down to a function type.
4560 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4561 // Reconstruct the pointer/reference as appropriate.
4562 if (isPointer) FnType = S.Context.getPointerType(FnType);
4563 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4564 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4565
4566 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4567 << FnType;
4568}
4569
4570void NoteBuiltinOperatorCandidate(Sema &S,
4571 const char *Opc,
4572 SourceLocation OpLoc,
4573 OverloadCandidate *Cand) {
4574 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4575 std::string TypeStr("operator");
4576 TypeStr += Opc;
4577 TypeStr += "(";
4578 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4579 if (Cand->Conversions.size() == 1) {
4580 TypeStr += ")";
4581 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4582 } else {
4583 TypeStr += ", ";
4584 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4585 TypeStr += ")";
4586 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4587 }
4588}
4589
4590void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4591 OverloadCandidate *Cand) {
4592 unsigned NoOperands = Cand->Conversions.size();
4593 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4594 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00004595 if (ICS.isBad()) break; // all meaningless after first invalid
4596 if (!ICS.isAmbiguous()) continue;
4597
4598 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4599 PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00004600 }
4601}
4602
John McCall3712d9e2010-01-15 23:32:50 +00004603SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4604 if (Cand->Function)
4605 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00004606 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00004607 return Cand->Surrogate->getLocation();
4608 return SourceLocation();
4609}
4610
John McCallad2587a2010-01-12 00:48:53 +00004611struct CompareOverloadCandidatesForDisplay {
4612 Sema &S;
4613 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00004614
4615 bool operator()(const OverloadCandidate *L,
4616 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00004617 // Fast-path this check.
4618 if (L == R) return false;
4619
John McCall12f97bc2010-01-08 04:41:39 +00004620 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00004621 if (L->Viable) {
4622 if (!R->Viable) return true;
4623
4624 // TODO: introduce a tri-valued comparison for overload
4625 // candidates. Would be more worthwhile if we had a sort
4626 // that could exploit it.
4627 if (S.isBetterOverloadCandidate(*L, *R)) return true;
4628 if (S.isBetterOverloadCandidate(*R, *L)) return false;
4629 } else if (R->Viable)
4630 return false;
John McCall12f97bc2010-01-08 04:41:39 +00004631
John McCall3712d9e2010-01-15 23:32:50 +00004632 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00004633
John McCall3712d9e2010-01-15 23:32:50 +00004634 // Criteria by which we can sort non-viable candidates:
4635 if (!L->Viable) {
4636 // 1. Arity mismatches come after other candidates.
4637 if (L->FailureKind == ovl_fail_too_many_arguments ||
4638 L->FailureKind == ovl_fail_too_few_arguments)
4639 return false;
4640 if (R->FailureKind == ovl_fail_too_many_arguments ||
4641 R->FailureKind == ovl_fail_too_few_arguments)
4642 return true;
John McCall12f97bc2010-01-08 04:41:39 +00004643
John McCall3712d9e2010-01-15 23:32:50 +00004644 // TODO: others?
4645 }
4646
4647 // Sort everything else by location.
4648 SourceLocation LLoc = GetLocationForCandidate(L);
4649 SourceLocation RLoc = GetLocationForCandidate(R);
4650
4651 // Put candidates without locations (e.g. builtins) at the end.
4652 if (LLoc.isInvalid()) return false;
4653 if (RLoc.isInvalid()) return true;
4654
4655 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00004656 }
4657};
4658
John McCalld3224162010-01-08 00:58:21 +00004659} // end anonymous namespace
4660
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004661/// PrintOverloadCandidates - When overload resolution fails, prints
4662/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00004663/// set.
Mike Stump11289f42009-09-09 15:08:12 +00004664void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004665Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00004666 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00004667 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004668 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004669 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00004670 // Sort the candidates by viability and position. Sorting directly would
4671 // be prohibitive, so we make a set of pointers and sort those.
4672 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4673 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4674 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4675 LastCand = CandidateSet.end();
4676 Cand != LastCand; ++Cand)
4677 if (Cand->Viable || OCD == OCD_AllCandidates)
4678 Cands.push_back(Cand);
John McCallad2587a2010-01-12 00:48:53 +00004679 std::sort(Cands.begin(), Cands.end(),
4680 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00004681
John McCall0d1da222010-01-12 00:44:57 +00004682 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00004683
John McCall12f97bc2010-01-08 04:41:39 +00004684 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4685 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4686 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004687
John McCalld3224162010-01-08 00:58:21 +00004688 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00004689 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00004690 else if (Cand->IsSurrogate)
4691 NoteSurrogateCandidate(*this, Cand);
4692
4693 // This a builtin candidate. We do not, in general, want to list
4694 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00004695 else if (Cand->Viable) {
4696 // Generally we only see ambiguities including viable builtin
4697 // operators if overload resolution got screwed up by an
4698 // ambiguous user-defined conversion.
4699 //
4700 // FIXME: It's quite possible for different conversions to see
4701 // different ambiguities, though.
4702 if (!ReportedAmbiguousConversions) {
4703 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4704 ReportedAmbiguousConversions = true;
4705 }
John McCalld3224162010-01-08 00:58:21 +00004706
John McCall0d1da222010-01-12 00:44:57 +00004707 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00004708 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00004709 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004710 }
4711}
4712
Douglas Gregorcd695e52008-11-10 20:40:00 +00004713/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4714/// an overloaded function (C++ [over.over]), where @p From is an
4715/// expression with overloaded function type and @p ToType is the type
4716/// we're trying to resolve to. For example:
4717///
4718/// @code
4719/// int f(double);
4720/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004721///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004722/// int (*pfd)(double) = f; // selects f(double)
4723/// @endcode
4724///
4725/// This routine returns the resulting FunctionDecl if it could be
4726/// resolved, and NULL otherwise. When @p Complain is true, this
4727/// routine will emit diagnostics if there is an error.
4728FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004729Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004730 bool Complain) {
4731 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004732 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004733 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004734 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004735 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004736 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004737 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004738 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004739 FunctionType = MemTypePtr->getPointeeType();
4740 IsMember = true;
4741 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004742
4743 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004744 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004745 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004746 return 0;
4747
4748 // Find the actual overloaded function declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004749
Douglas Gregorcd695e52008-11-10 20:40:00 +00004750 // C++ [over.over]p1:
4751 // [...] [Note: any redundant set of parentheses surrounding the
4752 // overloaded function name is ignored (5.1). ]
4753 Expr *OvlExpr = From->IgnoreParens();
4754
4755 // C++ [over.over]p1:
4756 // [...] The overloaded function name can be preceded by the &
4757 // operator.
4758 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4759 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4760 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4761 }
4762
Anders Carlssonb68b0282009-10-20 22:53:47 +00004763 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004764 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCalld14a8642009-11-21 08:51:07 +00004765
4766 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004767
John McCall10eae182009-11-30 22:42:35 +00004768 // Look into the overloaded expression.
John McCalle66edc12009-11-24 19:00:30 +00004769 if (UnresolvedLookupExpr *UL
John McCalld14a8642009-11-21 08:51:07 +00004770 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4771 Fns.append(UL->decls_begin(), UL->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00004772 if (UL->hasExplicitTemplateArgs()) {
4773 HasExplicitTemplateArgs = true;
4774 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4775 }
John McCall10eae182009-11-30 22:42:35 +00004776 } else if (UnresolvedMemberExpr *ME
4777 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4778 Fns.append(ME->decls_begin(), ME->decls_end());
4779 if (ME->hasExplicitTemplateArgs()) {
4780 HasExplicitTemplateArgs = true;
John McCall6b51f282009-11-23 01:53:49 +00004781 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004782 }
Douglas Gregor9b146582009-07-08 20:55:45 +00004783 }
Mike Stump11289f42009-09-09 15:08:12 +00004784
John McCalld14a8642009-11-21 08:51:07 +00004785 // If we didn't actually find anything, we're done.
4786 if (Fns.empty())
4787 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004788
Douglas Gregorcd695e52008-11-10 20:40:00 +00004789 // Look through all of the overloaded functions, searching for one
4790 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004791 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004792 bool FoundNonTemplateFunction = false;
John McCalld14a8642009-11-21 08:51:07 +00004793 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4794 E = Fns.end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004795 // Look through any using declarations to find the underlying function.
4796 NamedDecl *Fn = (*I)->getUnderlyingDecl();
4797
Douglas Gregorcd695e52008-11-10 20:40:00 +00004798 // C++ [over.over]p3:
4799 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004800 // targets of type "pointer-to-function" or "reference-to-function."
4801 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004802 // type "pointer-to-member-function."
4803 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004804
Mike Stump11289f42009-09-09 15:08:12 +00004805 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004806 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00004807 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004808 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004809 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004810 // static when converting to member pointer.
4811 if (Method->isStatic() == IsMember)
4812 continue;
4813 } else if (IsMember)
4814 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004815
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004816 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004817 // If the name is a function template, template argument deduction is
4818 // done (14.8.2.2), and if the argument deduction succeeds, the
4819 // resulting template argument list is used to generate a single
4820 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004821 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004822 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004823 FunctionDecl *Specialization = 0;
4824 TemplateDeductionInfo Info(Context);
4825 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004826 = DeduceTemplateArguments(FunctionTemplate,
4827 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor9b146582009-07-08 20:55:45 +00004828 FunctionType, Specialization, Info)) {
4829 // FIXME: make a note of the failed deduction for diagnostics.
4830 (void)Result;
4831 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004832 // FIXME: If the match isn't exact, shouldn't we just drop this as
4833 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004834 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004835 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004836 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004837 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004838 }
John McCalld14a8642009-11-21 08:51:07 +00004839
4840 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00004841 }
Mike Stump11289f42009-09-09 15:08:12 +00004842
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004843 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004844 // Skip non-static functions when converting to pointer, and static
4845 // when converting to member pointer.
4846 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004847 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004848
4849 // If we have explicit template arguments, skip non-templates.
4850 if (HasExplicitTemplateArgs)
4851 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004852 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004853 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004854
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004855 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00004856 QualType ResultTy;
4857 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4858 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4859 ResultTy)) {
John McCalld14a8642009-11-21 08:51:07 +00004860 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004861 FoundNonTemplateFunction = true;
4862 }
Mike Stump11289f42009-09-09 15:08:12 +00004863 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004864 }
4865
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004866 // If there were 0 or 1 matches, we're done.
4867 if (Matches.empty())
4868 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004869 else if (Matches.size() == 1) {
4870 FunctionDecl *Result = *Matches.begin();
4871 MarkDeclarationReferenced(From->getLocStart(), Result);
4872 return Result;
4873 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004874
4875 // C++ [over.over]p4:
4876 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004877 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004878 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004879 // [...] and any given function template specialization F1 is
4880 // eliminated if the set contains a second function template
4881 // specialization whose function template is more specialized
4882 // than the function template of F1 according to the partial
4883 // ordering rules of 14.5.5.2.
4884
4885 // The algorithm specified above is quadratic. We instead use a
4886 // two-pass algorithm (similar to the one used to identify the
4887 // best viable function in an overload set) that identifies the
4888 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004889 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004890 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004891 FunctionDecl *Result =
4892 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4893 TPOC_Other, From->getLocStart(),
4894 PDiag(),
4895 PDiag(diag::err_addr_ovl_ambiguous)
4896 << TemplateMatches[0]->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00004897 PDiag(diag::note_ovl_candidate)
4898 << (unsigned) oc_function_template);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004899 MarkDeclarationReferenced(From->getLocStart(), Result);
4900 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004901 }
Mike Stump11289f42009-09-09 15:08:12 +00004902
Douglas Gregorfae1d712009-09-26 03:56:17 +00004903 // [...] any function template specializations in the set are
4904 // eliminated if the set also contains a non-template function, [...]
4905 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4906 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4907 if ((*M)->getPrimaryTemplate() == 0)
4908 RemainingMatches.push_back(*M);
4909
Mike Stump11289f42009-09-09 15:08:12 +00004910 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004911 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004912 if (RemainingMatches.size() == 1) {
4913 FunctionDecl *Result = RemainingMatches.front();
4914 MarkDeclarationReferenced(From->getLocStart(), Result);
4915 return Result;
4916 }
Mike Stump11289f42009-09-09 15:08:12 +00004917
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004918 // FIXME: We should probably return the same thing that BestViableFunction
4919 // returns (even if we issue the diagnostics here).
4920 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4921 << RemainingMatches[0]->getDeclName();
4922 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
John McCallfd0b2f82010-01-06 09:43:14 +00004923 NoteOverloadCandidate(RemainingMatches[I]);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004924 return 0;
4925}
4926
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004927/// \brief Given an expression that refers to an overloaded function, try to
4928/// resolve that overloaded function expression down to a single function.
4929///
4930/// This routine can only resolve template-ids that refer to a single function
4931/// template, where that template-id refers to a single template whose template
4932/// arguments are either provided by the template-id or have defaults,
4933/// as described in C++0x [temp.arg.explicit]p3.
4934FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
4935 // C++ [over.over]p1:
4936 // [...] [Note: any redundant set of parentheses surrounding the
4937 // overloaded function name is ignored (5.1). ]
4938 Expr *OvlExpr = From->IgnoreParens();
4939
4940 // C++ [over.over]p1:
4941 // [...] The overloaded function name can be preceded by the &
4942 // operator.
4943 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4944 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4945 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4946 }
4947
4948 bool HasExplicitTemplateArgs = false;
4949 TemplateArgumentListInfo ExplicitTemplateArgs;
4950
4951 llvm::SmallVector<NamedDecl*,8> Fns;
4952
4953 // Look into the overloaded expression.
4954 if (UnresolvedLookupExpr *UL
4955 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4956 Fns.append(UL->decls_begin(), UL->decls_end());
4957 if (UL->hasExplicitTemplateArgs()) {
4958 HasExplicitTemplateArgs = true;
4959 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4960 }
4961 } else if (UnresolvedMemberExpr *ME
4962 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4963 Fns.append(ME->decls_begin(), ME->decls_end());
4964 if (ME->hasExplicitTemplateArgs()) {
4965 HasExplicitTemplateArgs = true;
4966 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4967 }
4968 }
4969
4970 // If we didn't actually find any template-ids, we're done.
4971 if (Fns.empty() || !HasExplicitTemplateArgs)
4972 return 0;
4973
4974 // Look through all of the overloaded functions, searching for one
4975 // whose type matches exactly.
4976 FunctionDecl *Matched = 0;
4977 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4978 E = Fns.end(); I != E; ++I) {
4979 // C++0x [temp.arg.explicit]p3:
4980 // [...] In contexts where deduction is done and fails, or in contexts
4981 // where deduction is not done, if a template argument list is
4982 // specified and it, along with any default template arguments,
4983 // identifies a single function template specialization, then the
4984 // template-id is an lvalue for the function template specialization.
4985 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
4986
4987 // C++ [over.over]p2:
4988 // If the name is a function template, template argument deduction is
4989 // done (14.8.2.2), and if the argument deduction succeeds, the
4990 // resulting template argument list is used to generate a single
4991 // function template specialization, which is added to the set of
4992 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004993 FunctionDecl *Specialization = 0;
4994 TemplateDeductionInfo Info(Context);
4995 if (TemplateDeductionResult Result
4996 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
4997 Specialization, Info)) {
4998 // FIXME: make a note of the failed deduction for diagnostics.
4999 (void)Result;
5000 continue;
5001 }
5002
5003 // Multiple matches; we can't resolve to a single declaration.
5004 if (Matched)
5005 return 0;
5006
5007 Matched = Specialization;
5008 }
5009
5010 return Matched;
5011}
5012
Douglas Gregorcabea402009-09-22 15:41:20 +00005013/// \brief Add a single candidate to the overload set.
5014static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00005015 NamedDecl *Callee,
John McCall6b51f282009-11-23 01:53:49 +00005016 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005017 Expr **Args, unsigned NumArgs,
5018 OverloadCandidateSet &CandidateSet,
5019 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005020 if (isa<UsingShadowDecl>(Callee))
5021 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5022
Douglas Gregorcabea402009-09-22 15:41:20 +00005023 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005024 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorcabea402009-09-22 15:41:20 +00005025 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
5026 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005027 return;
John McCalld14a8642009-11-21 08:51:07 +00005028 }
5029
5030 if (FunctionTemplateDecl *FuncTemplate
5031 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005032 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005033 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005034 return;
5035 }
5036
5037 assert(false && "unhandled case in overloaded call candidate");
5038
5039 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005040}
5041
5042/// \brief Add the overload candidates named by callee and/or found by argument
5043/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005044void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005045 Expr **Args, unsigned NumArgs,
5046 OverloadCandidateSet &CandidateSet,
5047 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005048
5049#ifndef NDEBUG
5050 // Verify that ArgumentDependentLookup is consistent with the rules
5051 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005052 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005053 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5054 // and let Y be the lookup set produced by argument dependent
5055 // lookup (defined as follows). If X contains
5056 //
5057 // -- a declaration of a class member, or
5058 //
5059 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005060 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005061 //
5062 // -- a declaration that is neither a function or a function
5063 // template
5064 //
5065 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005066
John McCall57500772009-12-16 12:17:52 +00005067 if (ULE->requiresADL()) {
5068 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5069 E = ULE->decls_end(); I != E; ++I) {
5070 assert(!(*I)->getDeclContext()->isRecord());
5071 assert(isa<UsingShadowDecl>(*I) ||
5072 !(*I)->getDeclContext()->isFunctionOrMethod());
5073 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005074 }
5075 }
5076#endif
5077
John McCall57500772009-12-16 12:17:52 +00005078 // It would be nice to avoid this copy.
5079 TemplateArgumentListInfo TABuffer;
5080 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5081 if (ULE->hasExplicitTemplateArgs()) {
5082 ULE->copyTemplateArgumentsInto(TABuffer);
5083 ExplicitTemplateArgs = &TABuffer;
5084 }
5085
5086 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5087 E = ULE->decls_end(); I != E; ++I)
John McCall6b51f282009-11-23 01:53:49 +00005088 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005089 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005090 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005091
John McCall57500772009-12-16 12:17:52 +00005092 if (ULE->requiresADL())
5093 AddArgumentDependentLookupCandidates(ULE->getName(), Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005094 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005095 CandidateSet,
5096 PartialOverloading);
5097}
John McCalld681c392009-12-16 08:11:27 +00005098
John McCall57500772009-12-16 12:17:52 +00005099static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5100 Expr **Args, unsigned NumArgs) {
5101 Fn->Destroy(SemaRef.Context);
5102 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5103 Args[Arg]->Destroy(SemaRef.Context);
5104 return SemaRef.ExprError();
5105}
5106
John McCalld681c392009-12-16 08:11:27 +00005107/// Attempts to recover from a call where no functions were found.
5108///
5109/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005110static Sema::OwningExprResult
5111BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5112 UnresolvedLookupExpr *ULE,
5113 SourceLocation LParenLoc,
5114 Expr **Args, unsigned NumArgs,
5115 SourceLocation *CommaLocs,
5116 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005117
5118 CXXScopeSpec SS;
5119 if (ULE->getQualifier()) {
5120 SS.setScopeRep(ULE->getQualifier());
5121 SS.setRange(ULE->getQualifierRange());
5122 }
5123
John McCall57500772009-12-16 12:17:52 +00005124 TemplateArgumentListInfo TABuffer;
5125 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5126 if (ULE->hasExplicitTemplateArgs()) {
5127 ULE->copyTemplateArgumentsInto(TABuffer);
5128 ExplicitTemplateArgs = &TABuffer;
5129 }
5130
John McCalld681c392009-12-16 08:11:27 +00005131 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5132 Sema::LookupOrdinaryName);
Douglas Gregor598b08f2009-12-31 05:20:13 +00005133 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall57500772009-12-16 12:17:52 +00005134 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005135
John McCall57500772009-12-16 12:17:52 +00005136 assert(!R.empty() && "lookup results empty despite recovery");
5137
5138 // Build an implicit member call if appropriate. Just drop the
5139 // casts and such from the call, we don't really care.
5140 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5141 if ((*R.begin())->isCXXClassMember())
5142 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5143 else if (ExplicitTemplateArgs)
5144 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5145 else
5146 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5147
5148 if (NewFn.isInvalid())
5149 return Destroy(SemaRef, Fn, Args, NumArgs);
5150
5151 Fn->Destroy(SemaRef.Context);
5152
5153 // This shouldn't cause an infinite loop because we're giving it
5154 // an expression with non-empty lookup results, which should never
5155 // end up here.
5156 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5157 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5158 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005159}
Douglas Gregorcabea402009-09-22 15:41:20 +00005160
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005161/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005162/// (which eventually refers to the declaration Func) and the call
5163/// arguments Args/NumArgs, attempt to resolve the function call down
5164/// to a specific function. If overload resolution succeeds, returns
5165/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005166/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005167/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005168Sema::OwningExprResult
5169Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5170 SourceLocation LParenLoc,
5171 Expr **Args, unsigned NumArgs,
5172 SourceLocation *CommaLocs,
5173 SourceLocation RParenLoc) {
5174#ifndef NDEBUG
5175 if (ULE->requiresADL()) {
5176 // To do ADL, we must have found an unqualified name.
5177 assert(!ULE->getQualifier() && "qualified name with ADL");
5178
5179 // We don't perform ADL for implicit declarations of builtins.
5180 // Verify that this was correctly set up.
5181 FunctionDecl *F;
5182 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5183 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5184 F->getBuiltinID() && F->isImplicit())
5185 assert(0 && "performing ADL for builtin");
5186
5187 // We don't perform ADL in C.
5188 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5189 }
5190#endif
5191
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005192 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005193
John McCall57500772009-12-16 12:17:52 +00005194 // Add the functions denoted by the callee to the set of candidate
5195 // functions, including those from argument-dependent lookup.
5196 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005197
5198 // If we found nothing, try to recover.
5199 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5200 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005201 if (CandidateSet.empty())
5202 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5203 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005204
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005205 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005206 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005207 case OR_Success: {
5208 FunctionDecl *FDecl = Best->Function;
5209 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5210 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5211 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005212
5213 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005214 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005215 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005216 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005217 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005218 break;
5219
5220 case OR_Ambiguous:
5221 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005222 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005223 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005224 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005225
5226 case OR_Deleted:
5227 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5228 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005229 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005230 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005231 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005232 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005233 }
5234
5235 // Overload resolution failed. Destroy all of the subexpressions and
5236 // return NULL.
5237 Fn->Destroy(Context);
5238 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5239 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005240 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005241}
5242
John McCall283b9012009-11-22 00:44:51 +00005243static bool IsOverloaded(const Sema::FunctionSet &Functions) {
5244 return Functions.size() > 1 ||
5245 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5246}
5247
Douglas Gregor084d8552009-03-13 23:49:33 +00005248/// \brief Create a unary operation that may resolve to an overloaded
5249/// operator.
5250///
5251/// \param OpLoc The location of the operator itself (e.g., '*').
5252///
5253/// \param OpcIn The UnaryOperator::Opcode that describes this
5254/// operator.
5255///
5256/// \param Functions The set of non-member functions that will be
5257/// considered by overload resolution. The caller needs to build this
5258/// set based on the context using, e.g.,
5259/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5260/// set should not contain any member functions; those will be added
5261/// by CreateOverloadedUnaryOp().
5262///
5263/// \param input The input argument.
5264Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
5265 unsigned OpcIn,
5266 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00005267 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005268 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5269 Expr *Input = (Expr *)input.get();
5270
5271 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5272 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5273 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5274
5275 Expr *Args[2] = { Input, 0 };
5276 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005277
Douglas Gregor084d8552009-03-13 23:49:33 +00005278 // For post-increment and post-decrement, add the implicit '0' as
5279 // the second argument, so that we know this is a post-increment or
5280 // post-decrement.
5281 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5282 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005283 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005284 SourceLocation());
5285 NumArgs = 2;
5286 }
5287
5288 if (Input->isTypeDependent()) {
John McCalld14a8642009-11-21 08:51:07 +00005289 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005290 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5291 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00005292 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump11289f42009-09-09 15:08:12 +00005293 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00005294 FuncEnd = Functions.end();
5295 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00005296 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00005297
Douglas Gregor084d8552009-03-13 23:49:33 +00005298 input.release();
5299 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5300 &Args[0], NumArgs,
5301 Context.DependentTy,
5302 OpLoc));
5303 }
5304
5305 // Build an empty overload set.
5306 OverloadCandidateSet CandidateSet;
5307
5308 // Add the candidates from the given function set.
5309 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
5310
5311 // Add operator candidates that are member functions.
5312 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5313
5314 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005315 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005316
5317 // Perform overload resolution.
5318 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005319 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005320 case OR_Success: {
5321 // We found a built-in operator or an overloaded operator.
5322 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005323
Douglas Gregor084d8552009-03-13 23:49:33 +00005324 if (FnDecl) {
5325 // We matched an overloaded operator. Build a call to that
5326 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005327
Douglas Gregor084d8552009-03-13 23:49:33 +00005328 // Convert the arguments.
5329 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
5330 if (PerformObjectArgumentInitialization(Input, Method))
5331 return ExprError();
5332 } else {
5333 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005334 OwningExprResult InputInit
5335 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005336 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005337 SourceLocation(),
5338 move(input));
5339 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005340 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005341
Douglas Gregore6600372009-12-23 17:40:29 +00005342 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005343 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005344 }
5345
5346 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005347 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005348
Douglas Gregor084d8552009-03-13 23:49:33 +00005349 // Build the actual expression node.
5350 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5351 SourceLocation());
5352 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005353
Douglas Gregor084d8552009-03-13 23:49:33 +00005354 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005355 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005356 ExprOwningPtr<CallExpr> TheCall(this,
5357 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005358 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005359
5360 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5361 FnDecl))
5362 return ExprError();
5363
5364 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005365 } else {
5366 // We matched a built-in operator. Convert the arguments, then
5367 // break out so that we will build the appropriate built-in
5368 // operator node.
5369 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005370 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005371 return ExprError();
5372
5373 break;
5374 }
5375 }
5376
5377 case OR_No_Viable_Function:
5378 // No viable function; fall through to handling this as a
5379 // built-in operator, which will produce an error message for us.
5380 break;
5381
5382 case OR_Ambiguous:
5383 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5384 << UnaryOperator::getOpcodeStr(Opc)
5385 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005386 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005387 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005388 return ExprError();
5389
5390 case OR_Deleted:
5391 Diag(OpLoc, diag::err_ovl_deleted_oper)
5392 << Best->Function->isDeleted()
5393 << UnaryOperator::getOpcodeStr(Opc)
5394 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005395 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005396 return ExprError();
5397 }
5398
5399 // Either we found no viable overloaded operator or we matched a
5400 // built-in operator. In either case, fall through to trying to
5401 // build a built-in operation.
5402 input.release();
5403 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5404}
5405
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005406/// \brief Create a binary operation that may resolve to an overloaded
5407/// operator.
5408///
5409/// \param OpLoc The location of the operator itself (e.g., '+').
5410///
5411/// \param OpcIn The BinaryOperator::Opcode that describes this
5412/// operator.
5413///
5414/// \param Functions The set of non-member functions that will be
5415/// considered by overload resolution. The caller needs to build this
5416/// set based on the context using, e.g.,
5417/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5418/// set should not contain any member functions; those will be added
5419/// by CreateOverloadedBinOp().
5420///
5421/// \param LHS Left-hand argument.
5422/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005423Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005424Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005425 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005426 FunctionSet &Functions,
5427 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005428 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005429 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005430
5431 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5432 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5433 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5434
5435 // If either side is type-dependent, create an appropriate dependent
5436 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005437 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005438 if (Functions.empty()) {
5439 // If there are no functions to store, just build a dependent
5440 // BinaryOperator or CompoundAssignment.
5441 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5442 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5443 Context.DependentTy, OpLoc));
5444
5445 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5446 Context.DependentTy,
5447 Context.DependentTy,
5448 Context.DependentTy,
5449 OpLoc));
5450 }
5451
John McCalld14a8642009-11-21 08:51:07 +00005452 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005453 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5454 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00005455 /* ADL */ true, IsOverloaded(Functions));
John McCalld14a8642009-11-21 08:51:07 +00005456
Mike Stump11289f42009-09-09 15:08:12 +00005457 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005458 FuncEnd = Functions.end();
5459 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00005460 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00005461
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005462 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00005463 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005464 Context.DependentTy,
5465 OpLoc));
5466 }
5467
5468 // If this is the .* operator, which is not overloadable, just
5469 // create a built-in binary operator.
5470 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00005471 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005472
Sebastian Redl6a96bf72009-11-18 23:10:33 +00005473 // If this is the assignment operator, we only perform overload resolution
5474 // if the left-hand side is a class or enumeration type. This is actually
5475 // a hack. The standard requires that we do overload resolution between the
5476 // various built-in candidates, but as DR507 points out, this can lead to
5477 // problems. So we do it this way, which pretty much follows what GCC does.
5478 // Note that we go the traditional code path for compound assignment forms.
5479 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00005480 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005481
Douglas Gregor084d8552009-03-13 23:49:33 +00005482 // Build an empty overload set.
5483 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005484
5485 // Add the candidates from the given function set.
5486 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
5487
5488 // Add operator candidates that are member functions.
5489 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5490
5491 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005492 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005493
5494 // Perform overload resolution.
5495 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005496 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005497 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005498 // We found a built-in operator or an overloaded operator.
5499 FunctionDecl *FnDecl = Best->Function;
5500
5501 if (FnDecl) {
5502 // We matched an overloaded operator. Build a call to that
5503 // operator.
5504
5505 // Convert the arguments.
5506 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005507 OwningExprResult Arg1
5508 = PerformCopyInitialization(
5509 InitializedEntity::InitializeParameter(
5510 FnDecl->getParamDecl(0)),
5511 SourceLocation(),
5512 Owned(Args[1]));
5513 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005514 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005515
5516 if (PerformObjectArgumentInitialization(Args[0], Method))
5517 return ExprError();
5518
5519 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005520 } else {
5521 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005522 OwningExprResult Arg0
5523 = PerformCopyInitialization(
5524 InitializedEntity::InitializeParameter(
5525 FnDecl->getParamDecl(0)),
5526 SourceLocation(),
5527 Owned(Args[0]));
5528 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005529 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005530
5531 OwningExprResult Arg1
5532 = PerformCopyInitialization(
5533 InitializedEntity::InitializeParameter(
5534 FnDecl->getParamDecl(1)),
5535 SourceLocation(),
5536 Owned(Args[1]));
5537 if (Arg1.isInvalid())
5538 return ExprError();
5539 Args[0] = LHS = Arg0.takeAs<Expr>();
5540 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005541 }
5542
5543 // Determine the result type
5544 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00005545 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005546 ResultTy = ResultTy.getNonReferenceType();
5547
5548 // Build the actual expression node.
5549 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00005550 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005551 UsualUnaryConversions(FnExpr);
5552
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005553 ExprOwningPtr<CXXOperatorCallExpr>
5554 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5555 Args, 2, ResultTy,
5556 OpLoc));
5557
5558 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5559 FnDecl))
5560 return ExprError();
5561
5562 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005563 } else {
5564 // We matched a built-in operator. Convert the arguments, then
5565 // break out so that we will build the appropriate built-in
5566 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00005567 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005568 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00005569 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005570 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005571 return ExprError();
5572
5573 break;
5574 }
5575 }
5576
Douglas Gregor66950a32009-09-30 21:46:01 +00005577 case OR_No_Viable_Function: {
5578 // C++ [over.match.oper]p9:
5579 // If the operator is the operator , [...] and there are no
5580 // viable functions, then the operator is assumed to be the
5581 // built-in operator and interpreted according to clause 5.
5582 if (Opc == BinaryOperator::Comma)
5583 break;
5584
Sebastian Redl027de2a2009-05-21 11:50:50 +00005585 // For class as left operand for assignment or compound assigment operator
5586 // do not fall through to handling in built-in, but report that no overloaded
5587 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005588 OwningExprResult Result = ExprError();
5589 if (Args[0]->getType()->isRecordType() &&
5590 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005591 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5592 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005593 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005594 } else {
5595 // No viable function; try to create a built-in operation, which will
5596 // produce an error. Then, show the non-viable candidates.
5597 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005598 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005599 assert(Result.isInvalid() &&
5600 "C++ binary operator overloading is missing candidates!");
5601 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00005602 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005603 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005604 return move(Result);
5605 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005606
5607 case OR_Ambiguous:
5608 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5609 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005610 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005611 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005612 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005613 return ExprError();
5614
5615 case OR_Deleted:
5616 Diag(OpLoc, diag::err_ovl_deleted_oper)
5617 << Best->Function->isDeleted()
5618 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005619 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005620 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005621 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00005622 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005623
Douglas Gregor66950a32009-09-30 21:46:01 +00005624 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005625 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005626}
5627
Sebastian Redladba46e2009-10-29 20:17:01 +00005628Action::OwningExprResult
5629Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5630 SourceLocation RLoc,
5631 ExprArg Base, ExprArg Idx) {
5632 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5633 static_cast<Expr*>(Idx.get()) };
5634 DeclarationName OpName =
5635 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5636
5637 // If either side is type-dependent, create an appropriate dependent
5638 // expression.
5639 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5640
John McCalld14a8642009-11-21 08:51:07 +00005641 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005642 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5643 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005644 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005645 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005646
5647 Base.release();
5648 Idx.release();
5649 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5650 Args, 2,
5651 Context.DependentTy,
5652 RLoc));
5653 }
5654
5655 // Build an empty overload set.
5656 OverloadCandidateSet CandidateSet;
5657
5658 // Subscript can only be overloaded as a member function.
5659
5660 // Add operator candidates that are member functions.
5661 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5662
5663 // Add builtin operator candidates.
5664 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5665
5666 // Perform overload resolution.
5667 OverloadCandidateSet::iterator Best;
5668 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5669 case OR_Success: {
5670 // We found a built-in operator or an overloaded operator.
5671 FunctionDecl *FnDecl = Best->Function;
5672
5673 if (FnDecl) {
5674 // We matched an overloaded operator. Build a call to that
5675 // operator.
5676
5677 // Convert the arguments.
5678 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5679 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5680 PerformCopyInitialization(Args[1],
5681 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005682 AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005683 return ExprError();
5684
5685 // Determine the result type
5686 QualType ResultTy
5687 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5688 ResultTy = ResultTy.getNonReferenceType();
5689
5690 // Build the actual expression node.
5691 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5692 LLoc);
5693 UsualUnaryConversions(FnExpr);
5694
5695 Base.release();
5696 Idx.release();
5697 ExprOwningPtr<CXXOperatorCallExpr>
5698 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5699 FnExpr, Args, 2,
5700 ResultTy, RLoc));
5701
5702 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5703 FnDecl))
5704 return ExprError();
5705
5706 return MaybeBindToTemporary(TheCall.release());
5707 } else {
5708 // We matched a built-in operator. Convert the arguments, then
5709 // break out so that we will build the appropriate built-in
5710 // operator node.
5711 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005712 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00005713 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005714 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005715 return ExprError();
5716
5717 break;
5718 }
5719 }
5720
5721 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00005722 if (CandidateSet.empty())
5723 Diag(LLoc, diag::err_ovl_no_oper)
5724 << Args[0]->getType() << /*subscript*/ 0
5725 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5726 else
5727 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5728 << Args[0]->getType()
5729 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005730 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00005731 "[]", LLoc);
5732 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00005733 }
5734
5735 case OR_Ambiguous:
5736 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5737 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005738 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00005739 "[]", LLoc);
5740 return ExprError();
5741
5742 case OR_Deleted:
5743 Diag(LLoc, diag::err_ovl_deleted_oper)
5744 << Best->Function->isDeleted() << "[]"
5745 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005746 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00005747 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005748 return ExprError();
5749 }
5750
5751 // We matched a built-in operator; build it.
5752 Base.release();
5753 Idx.release();
5754 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5755 Owned(Args[1]), RLoc);
5756}
5757
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005758/// BuildCallToMemberFunction - Build a call to a member
5759/// function. MemExpr is the expression that refers to the member
5760/// function (and includes the object parameter), Args/NumArgs are the
5761/// arguments to the function call (not including the object
5762/// parameter). The caller needs to validate that the member
5763/// expression refers to a member function or an overloaded member
5764/// function.
John McCall2d74de92009-12-01 22:10:20 +00005765Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005766Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5767 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005768 unsigned NumArgs, SourceLocation *CommaLocs,
5769 SourceLocation RParenLoc) {
5770 // Dig out the member expression. This holds both the object
5771 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00005772 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5773
John McCall10eae182009-11-30 22:42:35 +00005774 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005775 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00005776 if (isa<MemberExpr>(NakedMemExpr)) {
5777 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00005778 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5779 } else {
5780 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCall2d74de92009-12-01 22:10:20 +00005781
John McCall6e9f8f62009-12-03 04:06:58 +00005782 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00005783
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005784 // Add overload candidates
5785 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00005786
John McCall2d74de92009-12-01 22:10:20 +00005787 // FIXME: avoid copy.
5788 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5789 if (UnresExpr->hasExplicitTemplateArgs()) {
5790 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5791 TemplateArgs = &TemplateArgsBuffer;
5792 }
5793
John McCall10eae182009-11-30 22:42:35 +00005794 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5795 E = UnresExpr->decls_end(); I != E; ++I) {
5796
John McCall6e9f8f62009-12-03 04:06:58 +00005797 NamedDecl *Func = *I;
5798 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5799 if (isa<UsingShadowDecl>(Func))
5800 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5801
John McCall10eae182009-11-30 22:42:35 +00005802 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00005803 // If explicit template arguments were provided, we can't call a
5804 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00005805 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00005806 continue;
5807
John McCall6e9f8f62009-12-03 04:06:58 +00005808 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5809 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005810 } else {
John McCall10eae182009-11-30 22:42:35 +00005811 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall6e9f8f62009-12-03 04:06:58 +00005812 ActingDC, TemplateArgs,
5813 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005814 CandidateSet,
5815 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005816 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005817 }
Mike Stump11289f42009-09-09 15:08:12 +00005818
John McCall10eae182009-11-30 22:42:35 +00005819 DeclarationName DeclName = UnresExpr->getMemberName();
5820
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005821 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00005822 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005823 case OR_Success:
5824 Method = cast<CXXMethodDecl>(Best->Function);
5825 break;
5826
5827 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00005828 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005829 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005830 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005831 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005832 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005833 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005834
5835 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00005836 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_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 Gregor171c45a2009-02-18 21:56:37 +00005841
5842 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00005843 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00005844 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005845 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005846 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005847 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005848 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005849 }
5850
Douglas Gregor51c538b2009-11-20 19:42:02 +00005851 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00005852
John McCall2d74de92009-12-01 22:10:20 +00005853 // If overload resolution picked a static member, build a
5854 // non-member call based on that function.
5855 if (Method->isStatic()) {
5856 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5857 Args, NumArgs, RParenLoc);
5858 }
5859
John McCall10eae182009-11-30 22:42:35 +00005860 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005861 }
5862
5863 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005864 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00005865 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005866 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005867 Method->getResultType().getNonReferenceType(),
5868 RParenLoc));
5869
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005870 // Check for a valid return type.
5871 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5872 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00005873 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005874
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005875 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00005876 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00005877 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005878 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCall2d74de92009-12-01 22:10:20 +00005879 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005880 MemExpr->setBase(ObjectArg);
5881
5882 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005883 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005884 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005885 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00005886 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005887
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005888 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00005889 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00005890
John McCall2d74de92009-12-01 22:10:20 +00005891 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005892}
5893
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005894/// BuildCallToObjectOfClassType - Build a call to an object of class
5895/// type (C++ [over.call.object]), which can end up invoking an
5896/// overloaded function call operator (@c operator()) or performing a
5897/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005898Sema::ExprResult
5899Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005900 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005901 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005902 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005903 SourceLocation RParenLoc) {
5904 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005905 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005906
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005907 // C++ [over.call.object]p1:
5908 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005909 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005910 // candidate functions includes at least the function call
5911 // operators of T. The function call operators of T are obtained by
5912 // ordinary lookup of the name operator() in the context of
5913 // (E).operator().
5914 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005915 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005916
5917 if (RequireCompleteType(LParenLoc, Object->getType(),
5918 PartialDiagnostic(diag::err_incomplete_object_call)
5919 << Object->getSourceRange()))
5920 return true;
5921
John McCall27b18f82009-11-17 02:14:36 +00005922 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5923 LookupQualifiedName(R, Record->getDecl());
5924 R.suppressDiagnostics();
5925
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005926 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00005927 Oper != OperEnd; ++Oper) {
John McCall6e9f8f62009-12-03 04:06:58 +00005928 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005929 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005930 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005931
Douglas Gregorab7897a2008-11-19 22:57:39 +00005932 // C++ [over.call.object]p2:
5933 // In addition, for each conversion function declared in T of the
5934 // form
5935 //
5936 // operator conversion-type-id () cv-qualifier;
5937 //
5938 // where cv-qualifier is the same cv-qualification as, or a
5939 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005940 // denotes the type "pointer to function of (P1,...,Pn) returning
5941 // R", or the type "reference to pointer to function of
5942 // (P1,...,Pn) returning R", or the type "reference to function
5943 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005944 // is also considered as a candidate function. Similarly,
5945 // surrogate call functions are added to the set of candidate
5946 // functions for each conversion function declared in an
5947 // accessible base class provided the function is not hidden
5948 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00005949 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00005950 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00005951 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005952 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00005953 NamedDecl *D = *I;
5954 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5955 if (isa<UsingShadowDecl>(D))
5956 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5957
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005958 // Skip over templated conversion functions; they aren't
5959 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00005960 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005961 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005962
John McCall6e9f8f62009-12-03 04:06:58 +00005963 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00005964
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005965 // Strip the reference type (if any) and then the pointer type (if
5966 // any) to get down to what might be a function type.
5967 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5968 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5969 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005970
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005971 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall6e9f8f62009-12-03 04:06:58 +00005972 AddSurrogateCandidate(Conv, ActingContext, Proto,
5973 Object->getType(), Args, NumArgs,
5974 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005975 }
Mike Stump11289f42009-09-09 15:08:12 +00005976
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005977 // Perform overload resolution.
5978 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005979 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005980 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005981 // Overload resolution succeeded; we'll build the appropriate call
5982 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005983 break;
5984
5985 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00005986 if (CandidateSet.empty())
5987 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
5988 << Object->getType() << /*call*/ 1
5989 << Object->getSourceRange();
5990 else
5991 Diag(Object->getSourceRange().getBegin(),
5992 diag::err_ovl_no_viable_object_call)
5993 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005994 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005995 break;
5996
5997 case OR_Ambiguous:
5998 Diag(Object->getSourceRange().getBegin(),
5999 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006000 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006001 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006002 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006003
6004 case OR_Deleted:
6005 Diag(Object->getSourceRange().getBegin(),
6006 diag::err_ovl_deleted_object_call)
6007 << Best->Function->isDeleted()
6008 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006009 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006010 break;
Mike Stump11289f42009-09-09 15:08:12 +00006011 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006012
Douglas Gregorab7897a2008-11-19 22:57:39 +00006013 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006014 // We had an error; delete all of the subexpressions and return
6015 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006016 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006017 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006018 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006019 return true;
6020 }
6021
Douglas Gregorab7897a2008-11-19 22:57:39 +00006022 if (Best->Function == 0) {
6023 // Since there is no function declaration, this is one of the
6024 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006025 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006026 = cast<CXXConversionDecl>(
6027 Best->Conversions[0].UserDefined.ConversionFunction);
6028
6029 // We selected one of the surrogate functions that converts the
6030 // object parameter to a function pointer. Perform the conversion
6031 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006032
6033 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006034 // and then call it.
Eli Friedmana958a012009-12-09 04:52:43 +00006035 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006036
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006037 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006038 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6039 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006040 }
6041
6042 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6043 // that calls this method, using Object for the implicit object
6044 // parameter and passing along the remaining arguments.
6045 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006046 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006047
6048 unsigned NumArgsInProto = Proto->getNumArgs();
6049 unsigned NumArgsToCheck = NumArgs;
6050
6051 // Build the full argument list for the method call (the
6052 // implicit object parameter is placed at the beginning of the
6053 // list).
6054 Expr **MethodArgs;
6055 if (NumArgs < NumArgsInProto) {
6056 NumArgsToCheck = NumArgsInProto;
6057 MethodArgs = new Expr*[NumArgsInProto + 1];
6058 } else {
6059 MethodArgs = new Expr*[NumArgs + 1];
6060 }
6061 MethodArgs[0] = Object;
6062 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6063 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006064
6065 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006066 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006067 UsualUnaryConversions(NewFn);
6068
6069 // Once we've built TheCall, all of the expressions are properly
6070 // owned.
6071 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006072 ExprOwningPtr<CXXOperatorCallExpr>
6073 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006074 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006075 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006076 delete [] MethodArgs;
6077
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006078 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6079 Method))
6080 return true;
6081
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006082 // We may have default arguments. If so, we need to allocate more
6083 // slots in the call for them.
6084 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006085 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006086 else if (NumArgs > NumArgsInProto)
6087 NumArgsToCheck = NumArgsInProto;
6088
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006089 bool IsError = false;
6090
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006091 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006092 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006093 TheCall->setArg(0, Object);
6094
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006095
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006096 // Check the argument types.
6097 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006098 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006099 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006100 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006101
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006102 // Pass the argument.
6103 QualType ProtoArgType = Proto->getArgType(i);
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006104 IsError |= PerformCopyInitialization(Arg, ProtoArgType, AA_Passing);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006105 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006106 OwningExprResult DefArg
6107 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6108 if (DefArg.isInvalid()) {
6109 IsError = true;
6110 break;
6111 }
6112
6113 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006114 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006115
6116 TheCall->setArg(i + 1, Arg);
6117 }
6118
6119 // If this is a variadic call, handle args passed through "...".
6120 if (Proto->isVariadic()) {
6121 // Promote the arguments (C99 6.5.2.2p7).
6122 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6123 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006124 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006125 TheCall->setArg(i + 1, Arg);
6126 }
6127 }
6128
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006129 if (IsError) return true;
6130
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006131 if (CheckFunctionCall(Method, TheCall.get()))
6132 return true;
6133
Anders Carlsson1c83deb2009-08-16 03:53:54 +00006134 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006135}
6136
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006137/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006138/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006139/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006140Sema::OwningExprResult
6141Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6142 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006143 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006144
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006145 // C++ [over.ref]p1:
6146 //
6147 // [...] An expression x->m is interpreted as (x.operator->())->m
6148 // for a class object x of type T if T::operator->() exists and if
6149 // the operator is selected as the best match function by the
6150 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006151 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
6152 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006153 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006154
Eli Friedman132e70b2009-11-18 01:28:03 +00006155 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
6156 PDiag(diag::err_typecheck_incomplete_tag)
6157 << Base->getSourceRange()))
6158 return ExprError();
6159
John McCall27b18f82009-11-17 02:14:36 +00006160 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6161 LookupQualifiedName(R, BaseRecord->getDecl());
6162 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006163
6164 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006165 Oper != OperEnd; ++Oper) {
6166 NamedDecl *D = *Oper;
6167 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6168 if (isa<UsingShadowDecl>(D))
6169 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6170
6171 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
6172 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006173 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006174 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006175
6176 // Perform overload resolution.
6177 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006178 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006179 case OR_Success:
6180 // Overload resolution succeeded; we'll build the call below.
6181 break;
6182
6183 case OR_No_Viable_Function:
6184 if (CandidateSet.empty())
6185 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006186 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006187 else
6188 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006189 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006190 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006191 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006192
6193 case OR_Ambiguous:
6194 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006195 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006196 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006197 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006198
6199 case OR_Deleted:
6200 Diag(OpLoc, diag::err_ovl_deleted_oper)
6201 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006202 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006203 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006204 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006205 }
6206
6207 // Convert the object parameter.
6208 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00006209 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006210 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006211
6212 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006213 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006214
6215 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006216 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6217 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006218 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006219
6220 QualType ResultTy = Method->getResultType().getNonReferenceType();
6221 ExprOwningPtr<CXXOperatorCallExpr>
6222 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6223 &Base, 1, ResultTy, OpLoc));
6224
6225 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6226 Method))
6227 return ExprError();
6228 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006229}
6230
Douglas Gregorcd695e52008-11-10 20:40:00 +00006231/// FixOverloadedFunctionReference - E is an expression that refers to
6232/// a C++ overloaded function (possibly with some parentheses and
6233/// perhaps a '&' around it). We have resolved the overloaded function
6234/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006235/// refer (possibly indirectly) to Fn. Returns the new expr.
6236Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006237 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00006238 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6239 if (SubExpr == PE->getSubExpr())
6240 return PE->Retain();
6241
6242 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6243 }
6244
6245 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6246 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006247 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006248 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006249 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006250 if (SubExpr == ICE->getSubExpr())
6251 return ICE->Retain();
6252
6253 return new (Context) ImplicitCastExpr(ICE->getType(),
6254 ICE->getCastKind(),
6255 SubExpr,
6256 ICE->isLvalueCast());
6257 }
6258
6259 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006260 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006261 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006262 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6263 if (Method->isStatic()) {
6264 // Do nothing: static member functions aren't any different
6265 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006266 } else {
John McCalle66edc12009-11-24 19:00:30 +00006267 // Fix the sub expression, which really has to be an
6268 // UnresolvedLookupExpr holding an overloaded member function
6269 // or template.
John McCalld14a8642009-11-21 08:51:07 +00006270 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6271 if (SubExpr == UnOp->getSubExpr())
6272 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006273
John McCalld14a8642009-11-21 08:51:07 +00006274 assert(isa<DeclRefExpr>(SubExpr)
6275 && "fixed to something other than a decl ref");
6276 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6277 && "fixed to a member ref with no nested name qualifier");
6278
6279 // We have taken the address of a pointer to member
6280 // function. Perform the computation here so that we get the
6281 // appropriate pointer to member type.
6282 QualType ClassType
6283 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6284 QualType MemPtrType
6285 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6286
6287 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6288 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006289 }
6290 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00006291 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6292 if (SubExpr == UnOp->getSubExpr())
6293 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006294
Douglas Gregor51c538b2009-11-20 19:42:02 +00006295 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6296 Context.getPointerType(SubExpr->getType()),
6297 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006298 }
John McCalld14a8642009-11-21 08:51:07 +00006299
6300 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006301 // FIXME: avoid copy.
6302 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006303 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006304 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6305 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006306 }
6307
John McCalld14a8642009-11-21 08:51:07 +00006308 return DeclRefExpr::Create(Context,
6309 ULE->getQualifier(),
6310 ULE->getQualifierRange(),
6311 Fn,
6312 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006313 Fn->getType(),
6314 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006315 }
6316
John McCall10eae182009-11-30 22:42:35 +00006317 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006318 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006319 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6320 if (MemExpr->hasExplicitTemplateArgs()) {
6321 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6322 TemplateArgs = &TemplateArgsBuffer;
6323 }
John McCall6b51f282009-11-23 01:53:49 +00006324
John McCall2d74de92009-12-01 22:10:20 +00006325 Expr *Base;
6326
6327 // If we're filling in
6328 if (MemExpr->isImplicitAccess()) {
6329 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6330 return DeclRefExpr::Create(Context,
6331 MemExpr->getQualifier(),
6332 MemExpr->getQualifierRange(),
6333 Fn,
6334 MemExpr->getMemberLoc(),
6335 Fn->getType(),
6336 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006337 } else {
6338 SourceLocation Loc = MemExpr->getMemberLoc();
6339 if (MemExpr->getQualifier())
6340 Loc = MemExpr->getQualifierRange().getBegin();
6341 Base = new (Context) CXXThisExpr(Loc,
6342 MemExpr->getBaseType(),
6343 /*isImplicit=*/true);
6344 }
John McCall2d74de92009-12-01 22:10:20 +00006345 } else
6346 Base = MemExpr->getBase()->Retain();
6347
6348 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006349 MemExpr->isArrow(),
6350 MemExpr->getQualifier(),
6351 MemExpr->getQualifierRange(),
6352 Fn,
John McCall6b51f282009-11-23 01:53:49 +00006353 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006354 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006355 Fn->getType());
6356 }
6357
Douglas Gregor51c538b2009-11-20 19:42:02 +00006358 assert(false && "Invalid reference to overloaded function");
6359 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006360}
6361
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006362Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6363 FunctionDecl *Fn) {
6364 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6365}
6366
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006367} // end namespace clang