blob: 8b5a72de361dbf4ef55ea6c413f1edf8c0ae428a [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) {
92 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
93 "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 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
149 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
150
151 // Note that FromType has not necessarily been transformed by the
152 // array-to-pointer or function-to-pointer implicit conversions, so
153 // check for their presence as well as checking whether FromType is
154 // a pointer.
155 if (ToType->isBooleanType() &&
Douglas Gregor033f56d2008-12-23 00:53:59 +0000156 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000157 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
158 return true;
159
160 return false;
161}
162
Douglas Gregor5c407d92008-10-23 00:40:37 +0000163/// isPointerConversionToVoidPointer - Determines whether this
164/// conversion is a conversion of a pointer to a void pointer. This is
165/// used as part of the ranking of standard conversion sequences (C++
166/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000167bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000168StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000169isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregor5c407d92008-10-23 00:40:37 +0000170 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
171 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
172
173 // Note that FromType has not necessarily been transformed by the
174 // array-to-pointer implicit conversion, so check for its presence
175 // and redo the conversion to get a pointer.
176 if (First == ICK_Array_To_Pointer)
177 FromType = Context.getArrayDecayedType(FromType);
178
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000179 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000180 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000181 return ToPtrType->getPointeeType()->isVoidType();
182
183 return false;
184}
185
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000186/// DebugPrint - Print this standard conversion sequence to standard
187/// error. Useful for debugging overloading issues.
188void StandardConversionSequence::DebugPrint() const {
189 bool PrintedSomething = false;
190 if (First != ICK_Identity) {
191 fprintf(stderr, "%s", GetImplicitConversionName(First));
192 PrintedSomething = true;
193 }
194
195 if (Second != ICK_Identity) {
196 if (PrintedSomething) {
197 fprintf(stderr, " -> ");
198 }
199 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor2fe98832008-11-03 19:09:14 +0000200
201 if (CopyConstructor) {
202 fprintf(stderr, " (by copy constructor)");
203 } else if (DirectBinding) {
204 fprintf(stderr, " (direct reference binding)");
205 } else if (ReferenceBinding) {
206 fprintf(stderr, " (reference binding)");
207 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000208 PrintedSomething = true;
209 }
210
211 if (Third != ICK_Identity) {
212 if (PrintedSomething) {
213 fprintf(stderr, " -> ");
214 }
215 fprintf(stderr, "%s", GetImplicitConversionName(Third));
216 PrintedSomething = true;
217 }
218
219 if (!PrintedSomething) {
220 fprintf(stderr, "No conversions required");
221 }
222}
223
224/// DebugPrint - Print this user-defined conversion sequence to standard
225/// error. Useful for debugging overloading issues.
226void UserDefinedConversionSequence::DebugPrint() const {
227 if (Before.First || Before.Second || Before.Third) {
228 Before.DebugPrint();
229 fprintf(stderr, " -> ");
230 }
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000231 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000232 if (After.First || After.Second || After.Third) {
233 fprintf(stderr, " -> ");
234 After.DebugPrint();
235 }
236}
237
238/// DebugPrint - Print this implicit conversion sequence to standard
239/// error. Useful for debugging overloading issues.
240void ImplicitConversionSequence::DebugPrint() const {
241 switch (ConversionKind) {
242 case StandardConversion:
243 fprintf(stderr, "Standard conversion: ");
244 Standard.DebugPrint();
245 break;
246 case UserDefinedConversion:
247 fprintf(stderr, "User-defined conversion: ");
248 UserDefined.DebugPrint();
249 break;
250 case EllipsisConversion:
251 fprintf(stderr, "Ellipsis conversion");
252 break;
253 case BadConversion:
254 fprintf(stderr, "Bad conversion");
255 break;
256 }
257
258 fprintf(stderr, "\n");
259}
260
261// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000262// overload of the declarations in Old. This routine returns false if
263// New and Old cannot be overloaded, e.g., if New has the same
264// signature as some function in Old (C++ 1.3.10) or if the Old
265// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000266// it does return false, MatchedDecl will point to the decl that New
267// cannot be overloaded with. This decl may be a UsingShadowDecl on
268// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000269//
270// Example: Given the following input:
271//
272// void f(int, float); // #1
273// void f(int, int); // #2
274// int f(int, int); // #3
275//
276// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000277// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000278//
John McCall3d988d92009-12-02 08:47:38 +0000279// When we process #2, Old contains only the FunctionDecl for #1. By
280// comparing the parameter types, we see that #1 and #2 are overloaded
281// (since they have different signatures), so this routine returns
282// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000283//
John McCall3d988d92009-12-02 08:47:38 +0000284// When we process #3, Old is an overload set containing #1 and #2. We
285// compare the signatures of #3 to #1 (they're overloaded, so we do
286// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
287// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000288// signature), IsOverload returns false and MatchedDecl will be set to
289// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000290Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000291Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
292 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000293 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000294 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000295 NamedDecl *OldD = (*I)->getUnderlyingDecl();
296 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000297 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000298 Match = *I;
299 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000300 }
John McCall3d988d92009-12-02 08:47:38 +0000301 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000302 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000303 Match = *I;
304 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000305 }
John McCall84d87672009-12-10 09:41:52 +0000306 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
307 // We can overload with these, which can show up when doing
308 // redeclaration checks for UsingDecls.
309 assert(Old.getLookupKind() == LookupUsingDeclName);
310 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
311 // Optimistically assume that an unresolved using decl will
312 // overload; if it doesn't, we'll have to diagnose during
313 // template instantiation.
314 } else {
John McCall1f82f242009-11-18 22:49:29 +0000315 // (C++ 13p1):
316 // Only function declarations can be overloaded; object and type
317 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000318 Match = *I;
319 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000320 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000321 }
John McCall1f82f242009-11-18 22:49:29 +0000322
John McCalldaa3d6b2009-12-09 03:35:25 +0000323 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000324}
325
326bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
327 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
328 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
329
330 // C++ [temp.fct]p2:
331 // A function template can be overloaded with other function templates
332 // and with normal (non-template) functions.
333 if ((OldTemplate == 0) != (NewTemplate == 0))
334 return true;
335
336 // Is the function New an overload of the function Old?
337 QualType OldQType = Context.getCanonicalType(Old->getType());
338 QualType NewQType = Context.getCanonicalType(New->getType());
339
340 // Compare the signatures (C++ 1.3.10) of the two functions to
341 // determine whether they are overloads. If we find any mismatch
342 // in the signature, they are overloads.
343
344 // If either of these functions is a K&R-style function (no
345 // prototype), then we consider them to have matching signatures.
346 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
347 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
348 return false;
349
350 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
351 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
352
353 // The signature of a function includes the types of its
354 // parameters (C++ 1.3.10), which includes the presence or absence
355 // of the ellipsis; see C++ DR 357).
356 if (OldQType != NewQType &&
357 (OldType->getNumArgs() != NewType->getNumArgs() ||
358 OldType->isVariadic() != NewType->isVariadic() ||
359 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
360 NewType->arg_type_begin())))
361 return true;
362
363 // C++ [temp.over.link]p4:
364 // The signature of a function template consists of its function
365 // signature, its return type and its template parameter list. The names
366 // of the template parameters are significant only for establishing the
367 // relationship between the template parameters and the rest of the
368 // signature.
369 //
370 // We check the return type and template parameter lists for function
371 // templates first; the remaining checks follow.
372 if (NewTemplate &&
373 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
374 OldTemplate->getTemplateParameters(),
375 false, TPL_TemplateMatch) ||
376 OldType->getResultType() != NewType->getResultType()))
377 return true;
378
379 // If the function is a class member, its signature includes the
380 // cv-qualifiers (if any) on the function itself.
381 //
382 // As part of this, also check whether one of the member functions
383 // is static, in which case they are not overloads (C++
384 // 13.1p2). While not part of the definition of the signature,
385 // this check is important to determine whether these functions
386 // can be overloaded.
387 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
388 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
389 if (OldMethod && NewMethod &&
390 !OldMethod->isStatic() && !NewMethod->isStatic() &&
391 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
392 return true;
393
394 // The signatures match; this is not an overload.
395 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000396}
397
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000398/// TryImplicitConversion - Attempt to perform an implicit conversion
399/// from the given expression (Expr) to the given type (ToType). This
400/// function returns an implicit conversion sequence that can be used
401/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000402///
403/// void f(float f);
404/// void g(int i) { f(i); }
405///
406/// this routine would produce an implicit conversion sequence to
407/// describe the initialization of f from i, which will be a standard
408/// conversion sequence containing an lvalue-to-rvalue conversion (C++
409/// 4.1) followed by a floating-integral conversion (C++ 4.9).
410//
411/// Note that this routine only determines how the conversion can be
412/// performed; it does not actually perform the conversion. As such,
413/// it will not produce any diagnostics if no conversion is available,
414/// but will instead return an implicit conversion sequence of kind
415/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000416///
417/// If @p SuppressUserConversions, then user-defined conversions are
418/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000419/// If @p AllowExplicit, then explicit user-defined conversions are
420/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000421/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
422/// no matter its actual lvalueness.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000423/// If @p UserCast, the implicit conversion is being done for a user-specified
424/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000425ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000426Sema::TryImplicitConversion(Expr* From, QualType ToType,
427 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000428 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000429 bool InOverloadResolution,
430 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000431 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000432 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000433 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000434 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000435 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000436 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000437 (UserDefResult = IsUserDefinedConversion(From, ToType,
438 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000439 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000440 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000441 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000442 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000443 // C++ [over.ics.user]p4:
444 // A conversion of an expression of class type to the same class
445 // type is given Exact Match rank, and a conversion of an
446 // expression of class type to a base class of that type is
447 // given Conversion rank, in spite of the fact that a copy
448 // constructor (i.e., a user-defined conversion function) is
449 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000450 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000451 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000452 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000453 = Context.getCanonicalType(From->getType().getUnqualifiedType());
454 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000455 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000456 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000457 // Turn this into a "standard" conversion sequence, so that it
458 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000459 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
460 ICS.Standard.setAsIdentityConversion();
461 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
462 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000463 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000464 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000465 ICS.Standard.Second = ICK_Derived_To_Base;
466 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000467 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000468
469 // C++ [over.best.ics]p4:
470 // However, when considering the argument of a user-defined
471 // conversion function that is a candidate by 13.3.1.3 when
472 // invoked for the copying of the temporary in the second step
473 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
474 // 13.3.1.6 in all cases, only standard conversion sequences and
475 // ellipsis conversion sequences are allowed.
476 if (SuppressUserConversions &&
477 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
478 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000479 } else {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000480 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000481 if (UserDefResult == OR_Ambiguous) {
482 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
483 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian574de2c2009-10-12 17:51:19 +0000484 if (Cand->Viable)
485 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000486 }
487 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000488
489 return ICS;
490}
491
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000492/// \brief Determine whether the conversion from FromType to ToType is a valid
493/// conversion that strips "noreturn" off the nested function type.
494static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
495 QualType ToType, QualType &ResultTy) {
496 if (Context.hasSameUnqualifiedType(FromType, ToType))
497 return false;
498
499 // Strip the noreturn off the type we're converting from; noreturn can
500 // safely be removed.
501 FromType = Context.getNoReturnType(FromType, false);
502 if (!Context.hasSameUnqualifiedType(FromType, ToType))
503 return false;
504
505 ResultTy = FromType;
506 return true;
507}
508
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000509/// IsStandardConversion - Determines whether there is a standard
510/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
511/// expression From to the type ToType. Standard conversion sequences
512/// only consider non-class types; for conversions that involve class
513/// types, use TryImplicitConversion. If a conversion exists, SCS will
514/// contain the standard conversion sequence required to perform this
515/// conversion and this routine will return true. Otherwise, this
516/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000517bool
518Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000519 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000520 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000521 QualType FromType = From->getType();
522
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000523 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000524 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000525 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000526 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000527 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000528 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000529
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000530 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000531 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000532 if (FromType->isRecordType() || ToType->isRecordType()) {
533 if (getLangOptions().CPlusPlus)
534 return false;
535
Mike Stump11289f42009-09-09 15:08:12 +0000536 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000537 }
538
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000539 // The first conversion can be an lvalue-to-rvalue conversion,
540 // array-to-pointer conversion, or function-to-pointer conversion
541 // (C++ 4p1).
542
Mike Stump11289f42009-09-09 15:08:12 +0000543 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000544 // An lvalue (3.10) of a non-function, non-array type T can be
545 // converted to an rvalue.
546 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000547 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000548 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000549 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000550 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000551
552 // If T is a non-class type, the type of the rvalue is the
553 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000554 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
555 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000556 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000557 } else if (FromType->isArrayType()) {
558 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000559 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000560
561 // An lvalue or rvalue of type "array of N T" or "array of unknown
562 // bound of T" can be converted to an rvalue of type "pointer to
563 // T" (C++ 4.2p1).
564 FromType = Context.getArrayDecayedType(FromType);
565
566 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
567 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000568 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000569
570 // For the purpose of ranking in overload resolution
571 // (13.3.3.1.1), this conversion is considered an
572 // array-to-pointer conversion followed by a qualification
573 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000574 SCS.Second = ICK_Identity;
575 SCS.Third = ICK_Qualification;
576 SCS.ToTypePtr = ToType.getAsOpaquePtr();
577 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000578 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000579 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
580 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000581 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000582
583 // An lvalue of function type T can be converted to an rvalue of
584 // type "pointer to T." The result is a pointer to the
585 // function. (C++ 4.3p1).
586 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000587 } else if (FunctionDecl *Fn
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000588 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000589 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000590 SCS.First = ICK_Function_To_Pointer;
591
592 // We were able to resolve the address of the overloaded function,
593 // so we can convert to the type of that function.
594 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000595 if (ToType->isLValueReferenceType())
596 FromType = Context.getLValueReferenceType(FromType);
597 else if (ToType->isRValueReferenceType())
598 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000599 else if (ToType->isMemberPointerType()) {
600 // Resolve address only succeeds if both sides are member pointers,
601 // but it doesn't have to be the same class. See DR 247.
602 // Note that this means that the type of &Derived::fn can be
603 // Ret (Base::*)(Args) if the fn overload actually found is from the
604 // base class, even if it was brought into the derived class via a
605 // using declaration. The standard isn't clear on this issue at all.
606 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
607 FromType = Context.getMemberPointerType(FromType,
608 Context.getTypeDeclType(M->getParent()).getTypePtr());
609 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000610 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000611 } else {
612 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000613 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000614 }
615
616 // The second conversion can be an integral promotion, floating
617 // point promotion, integral conversion, floating point conversion,
618 // floating-integral conversion, pointer conversion,
619 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000620 // For overloading in C, this can also be a "compatible-type"
621 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000622 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000623 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000624 // The unqualified versions of the types are the same: there's no
625 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000626 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000627 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000628 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000629 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000630 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000631 } else if (IsFloatingPointPromotion(FromType, ToType)) {
632 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000633 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000634 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000635 } else if (IsComplexPromotion(FromType, ToType)) {
636 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000637 SCS.Second = ICK_Complex_Promotion;
638 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000639 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000640 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000641 // Integral conversions (C++ 4.7).
642 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000643 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000644 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000645 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
646 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000647 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000648 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000649 } else if (FromType->isComplexType() && ToType->isComplexType()) {
650 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000651 SCS.Second = ICK_Complex_Conversion;
652 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000653 } else if ((FromType->isFloatingType() &&
654 ToType->isIntegralType() && (!ToType->isBooleanType() &&
655 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000656 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000657 ToType->isFloatingType())) {
658 // Floating-integral conversions (C++ 4.9).
659 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000660 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000661 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000662 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
663 (ToType->isComplexType() && FromType->isArithmeticType())) {
664 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000665 SCS.Second = ICK_Complex_Real;
666 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000667 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
668 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000669 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000670 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000671 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000672 } else if (IsMemberPointerConversion(From, FromType, ToType,
673 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000674 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000675 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000676 } else if (ToType->isBooleanType() &&
677 (FromType->isArithmeticType() ||
678 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000679 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000680 FromType->isBlockPointerType() ||
681 FromType->isMemberPointerType() ||
682 FromType->isNullPtrType())) {
683 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000684 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000685 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000686 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000687 Context.typesAreCompatible(ToType, FromType)) {
688 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000689 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000690 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
691 // Treat a conversion that strips "noreturn" as an identity conversion.
692 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000693 } else {
694 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000695 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000696 }
697
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000698 QualType CanonFrom;
699 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000700 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000701 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000702 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000703 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000704 CanonFrom = Context.getCanonicalType(FromType);
705 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000706 } else {
707 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000708 SCS.Third = ICK_Identity;
709
Mike Stump11289f42009-09-09 15:08:12 +0000710 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000711 // [...] Any difference in top-level cv-qualification is
712 // subsumed by the initialization itself and does not constitute
713 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000714 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000715 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000716 if (CanonFrom.getLocalUnqualifiedType()
717 == CanonTo.getLocalUnqualifiedType() &&
718 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000719 FromType = ToType;
720 CanonFrom = CanonTo;
721 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000722 }
723
724 // If we have not converted the argument type to the parameter type,
725 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000726 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000727 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000728
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000729 SCS.ToTypePtr = FromType.getAsOpaquePtr();
730 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000731}
732
733/// IsIntegralPromotion - Determines whether the conversion from the
734/// expression From (whose potentially-adjusted type is FromType) to
735/// ToType is an integral promotion (C++ 4.5). If so, returns true and
736/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000737bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000738 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000739 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000740 if (!To) {
741 return false;
742 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000743
744 // An rvalue of type char, signed char, unsigned char, short int, or
745 // unsigned short int can be converted to an rvalue of type int if
746 // int can represent all the values of the source type; otherwise,
747 // the source rvalue can be converted to an rvalue of type unsigned
748 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000749 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000750 if (// We can promote any signed, promotable integer type to an int
751 (FromType->isSignedIntegerType() ||
752 // We can promote any unsigned integer type whose size is
753 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000754 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000755 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000756 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000757 }
758
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000759 return To->getKind() == BuiltinType::UInt;
760 }
761
762 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
763 // can be converted to an rvalue of the first of the following types
764 // that can represent all the values of its underlying type: int,
765 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000766
767 // We pre-calculate the promotion type for enum types.
768 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
769 if (ToType->isIntegerType())
770 return Context.hasSameUnqualifiedType(ToType,
771 FromEnumType->getDecl()->getPromotionType());
772
773 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000774 // Determine whether the type we're converting from is signed or
775 // unsigned.
776 bool FromIsSigned;
777 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000778
779 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
780 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000781
782 // The types we'll try to promote to, in the appropriate
783 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000784 QualType PromoteTypes[6] = {
785 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000786 Context.LongTy, Context.UnsignedLongTy ,
787 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000788 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000789 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000790 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
791 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000792 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000793 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
794 // We found the type that we can promote to. If this is the
795 // type we wanted, we have a promotion. Otherwise, no
796 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000797 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000798 }
799 }
800 }
801
802 // An rvalue for an integral bit-field (9.6) can be converted to an
803 // rvalue of type int if int can represent all the values of the
804 // bit-field; otherwise, it can be converted to unsigned int if
805 // unsigned int can represent all the values of the bit-field. If
806 // the bit-field is larger yet, no integral promotion applies to
807 // it. If the bit-field has an enumerated type, it is treated as any
808 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000809 // FIXME: We should delay checking of bit-fields until we actually perform the
810 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000811 using llvm::APSInt;
812 if (From)
813 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000814 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000815 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
816 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
817 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
818 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000819
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000820 // Are we promoting to an int from a bitfield that fits in an int?
821 if (BitWidth < ToSize ||
822 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
823 return To->getKind() == BuiltinType::Int;
824 }
Mike Stump11289f42009-09-09 15:08:12 +0000825
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000826 // Are we promoting to an unsigned int from an unsigned bitfield
827 // that fits into an unsigned int?
828 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
829 return To->getKind() == BuiltinType::UInt;
830 }
Mike Stump11289f42009-09-09 15:08:12 +0000831
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000832 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000833 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000834 }
Mike Stump11289f42009-09-09 15:08:12 +0000835
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000836 // An rvalue of type bool can be converted to an rvalue of type int,
837 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000838 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000839 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000840 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000841
842 return false;
843}
844
845/// IsFloatingPointPromotion - Determines whether the conversion from
846/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
847/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000848bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000849 /// An rvalue of type float can be converted to an rvalue of type
850 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000851 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
852 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000853 if (FromBuiltin->getKind() == BuiltinType::Float &&
854 ToBuiltin->getKind() == BuiltinType::Double)
855 return true;
856
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000857 // C99 6.3.1.5p1:
858 // When a float is promoted to double or long double, or a
859 // double is promoted to long double [...].
860 if (!getLangOptions().CPlusPlus &&
861 (FromBuiltin->getKind() == BuiltinType::Float ||
862 FromBuiltin->getKind() == BuiltinType::Double) &&
863 (ToBuiltin->getKind() == BuiltinType::LongDouble))
864 return true;
865 }
866
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000867 return false;
868}
869
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000870/// \brief Determine if a conversion is a complex promotion.
871///
872/// A complex promotion is defined as a complex -> complex conversion
873/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000874/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000875bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000876 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000877 if (!FromComplex)
878 return false;
879
John McCall9dd450b2009-09-21 23:43:11 +0000880 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000881 if (!ToComplex)
882 return false;
883
884 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000885 ToComplex->getElementType()) ||
886 IsIntegralPromotion(0, FromComplex->getElementType(),
887 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000888}
889
Douglas Gregor237f96c2008-11-26 23:31:11 +0000890/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
891/// the pointer type FromPtr to a pointer to type ToPointee, with the
892/// same type qualifiers as FromPtr has on its pointee type. ToType,
893/// if non-empty, will be a pointer to ToType that may or may not have
894/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000895static QualType
896BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000897 QualType ToPointee, QualType ToType,
898 ASTContext &Context) {
899 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
900 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000901 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000902
903 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000904 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000905 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000906 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000907 return ToType;
908
909 // Build a pointer to ToPointee. It has the right qualifiers
910 // already.
911 return Context.getPointerType(ToPointee);
912 }
913
914 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000915 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000916 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
917 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000918}
919
Fariborz Jahanian01cbe442009-12-16 23:13:33 +0000920/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
921/// the FromType, which is an objective-c pointer, to ToType, which may or may
922/// not have the right set of qualifiers.
923static QualType
924BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
925 QualType ToType,
926 ASTContext &Context) {
927 QualType CanonFromType = Context.getCanonicalType(FromType);
928 QualType CanonToType = Context.getCanonicalType(ToType);
929 Qualifiers Quals = CanonFromType.getQualifiers();
930
931 // Exact qualifier match -> return the pointer type we're converting to.
932 if (CanonToType.getLocalQualifiers() == Quals)
933 return ToType;
934
935 // Just build a canonical type that has the right qualifiers.
936 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
937}
938
Mike Stump11289f42009-09-09 15:08:12 +0000939static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000940 bool InOverloadResolution,
941 ASTContext &Context) {
942 // Handle value-dependent integral null pointer constants correctly.
943 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
944 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
945 Expr->getType()->isIntegralType())
946 return !InOverloadResolution;
947
Douglas Gregor56751b52009-09-25 04:25:58 +0000948 return Expr->isNullPointerConstant(Context,
949 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
950 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000951}
Mike Stump11289f42009-09-09 15:08:12 +0000952
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000953/// IsPointerConversion - Determines whether the conversion of the
954/// expression From, which has the (possibly adjusted) type FromType,
955/// can be converted to the type ToType via a pointer conversion (C++
956/// 4.10). If so, returns true and places the converted type (that
957/// might differ from ToType in its cv-qualifiers at some level) into
958/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000959///
Douglas Gregora29dc052008-11-27 01:19:21 +0000960/// This routine also supports conversions to and from block pointers
961/// and conversions with Objective-C's 'id', 'id<protocols...>', and
962/// pointers to interfaces. FIXME: Once we've determined the
963/// appropriate overloading rules for Objective-C, we may want to
964/// split the Objective-C checks into a different routine; however,
965/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000966/// conversions, so for now they live here. IncompatibleObjC will be
967/// set if the conversion is an allowed Objective-C conversion that
968/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000969bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000970 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000971 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000972 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000973 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000974 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
975 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000976
Mike Stump11289f42009-09-09 15:08:12 +0000977 // Conversion from a null pointer constant to any Objective-C pointer type.
978 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000979 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000980 ConvertedType = ToType;
981 return true;
982 }
983
Douglas Gregor231d1c62008-11-27 00:15:41 +0000984 // Blocks: Block pointers can be converted to void*.
985 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000986 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000987 ConvertedType = ToType;
988 return true;
989 }
990 // Blocks: A null pointer constant can be converted to a block
991 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000992 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000993 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000994 ConvertedType = ToType;
995 return true;
996 }
997
Sebastian Redl576fd422009-05-10 18:38:11 +0000998 // If the left-hand-side is nullptr_t, the right side can be a null
999 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001000 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001001 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001002 ConvertedType = ToType;
1003 return true;
1004 }
1005
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001006 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001007 if (!ToTypePtr)
1008 return false;
1009
1010 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001011 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001012 ConvertedType = ToType;
1013 return true;
1014 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001015
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001016 // Beyond this point, both types need to be pointers
1017 // , including objective-c pointers.
1018 QualType ToPointeeType = ToTypePtr->getPointeeType();
1019 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1020 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1021 ToType, Context);
1022 return true;
1023
1024 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001025 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001026 if (!FromTypePtr)
1027 return false;
1028
1029 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001030
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001031 // An rvalue of type "pointer to cv T," where T is an object type,
1032 // can be converted to an rvalue of type "pointer to cv void" (C++
1033 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001034 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001035 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001036 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001037 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001038 return true;
1039 }
1040
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001041 // When we're overloading in C, we allow a special kind of pointer
1042 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001043 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001044 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001045 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001046 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001047 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001048 return true;
1049 }
1050
Douglas Gregor5c407d92008-10-23 00:40:37 +00001051 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001052 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001053 // An rvalue of type "pointer to cv D," where D is a class type,
1054 // can be converted to an rvalue of type "pointer to cv B," where
1055 // B is a base class (clause 10) of D. If B is an inaccessible
1056 // (clause 11) or ambiguous (10.2) base class of D, a program that
1057 // necessitates this conversion is ill-formed. The result of the
1058 // conversion is a pointer to the base class sub-object of the
1059 // derived class object. The null pointer value is converted to
1060 // the null pointer value of the destination type.
1061 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001062 // Note that we do not check for ambiguity or inaccessibility
1063 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001064 if (getLangOptions().CPlusPlus &&
1065 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001066 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001067 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001068 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001069 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001070 ToType, Context);
1071 return true;
1072 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001073
Douglas Gregora119f102008-12-19 19:13:09 +00001074 return false;
1075}
1076
1077/// isObjCPointerConversion - Determines whether this is an
1078/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1079/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001080bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001081 QualType& ConvertedType,
1082 bool &IncompatibleObjC) {
1083 if (!getLangOptions().ObjC1)
1084 return false;
1085
Steve Naroff7cae42b2009-07-10 23:34:53 +00001086 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001087 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001088 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001089 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001090
Steve Naroff7cae42b2009-07-10 23:34:53 +00001091 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001092 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001093 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001094 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001095 ConvertedType = ToType;
1096 return true;
1097 }
1098 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001099 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001100 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001101 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001102 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001103 ConvertedType = ToType;
1104 return true;
1105 }
1106 // Objective C++: We're able to convert from a pointer to an
1107 // interface to a pointer to a different interface.
1108 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1109 ConvertedType = ToType;
1110 return true;
1111 }
1112
1113 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1114 // Okay: this is some kind of implicit downcast of Objective-C
1115 // interfaces, which is permitted. However, we're going to
1116 // complain about it.
1117 IncompatibleObjC = true;
1118 ConvertedType = FromType;
1119 return true;
1120 }
Mike Stump11289f42009-09-09 15:08:12 +00001121 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001122 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001123 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001124 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001125 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001126 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001127 ToPointeeType = ToBlockPtr->getPointeeType();
1128 else
Douglas Gregora119f102008-12-19 19:13:09 +00001129 return false;
1130
Douglas Gregor033f56d2008-12-23 00:53:59 +00001131 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001132 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001133 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001134 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001135 FromPointeeType = FromBlockPtr->getPointeeType();
1136 else
Douglas Gregora119f102008-12-19 19:13:09 +00001137 return false;
1138
Douglas Gregora119f102008-12-19 19:13:09 +00001139 // If we have pointers to pointers, recursively check whether this
1140 // is an Objective-C conversion.
1141 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1142 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1143 IncompatibleObjC)) {
1144 // We always complain about this conversion.
1145 IncompatibleObjC = true;
1146 ConvertedType = ToType;
1147 return true;
1148 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001149 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001150 // differences in the argument and result types are in Objective-C
1151 // pointer conversions. If so, we permit the conversion (but
1152 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001153 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001154 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001155 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001156 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001157 if (FromFunctionType && ToFunctionType) {
1158 // If the function types are exactly the same, this isn't an
1159 // Objective-C pointer conversion.
1160 if (Context.getCanonicalType(FromPointeeType)
1161 == Context.getCanonicalType(ToPointeeType))
1162 return false;
1163
1164 // Perform the quick checks that will tell us whether these
1165 // function types are obviously different.
1166 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1167 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1168 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1169 return false;
1170
1171 bool HasObjCConversion = false;
1172 if (Context.getCanonicalType(FromFunctionType->getResultType())
1173 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1174 // Okay, the types match exactly. Nothing to do.
1175 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1176 ToFunctionType->getResultType(),
1177 ConvertedType, IncompatibleObjC)) {
1178 // Okay, we have an Objective-C pointer conversion.
1179 HasObjCConversion = true;
1180 } else {
1181 // Function types are too different. Abort.
1182 return false;
1183 }
Mike Stump11289f42009-09-09 15:08:12 +00001184
Douglas Gregora119f102008-12-19 19:13:09 +00001185 // Check argument types.
1186 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1187 ArgIdx != NumArgs; ++ArgIdx) {
1188 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1189 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1190 if (Context.getCanonicalType(FromArgType)
1191 == Context.getCanonicalType(ToArgType)) {
1192 // Okay, the types match exactly. Nothing to do.
1193 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1194 ConvertedType, IncompatibleObjC)) {
1195 // Okay, we have an Objective-C pointer conversion.
1196 HasObjCConversion = true;
1197 } else {
1198 // Argument types are too different. Abort.
1199 return false;
1200 }
1201 }
1202
1203 if (HasObjCConversion) {
1204 // We had an Objective-C conversion. Allow this pointer
1205 // conversion, but complain about it.
1206 ConvertedType = ToType;
1207 IncompatibleObjC = true;
1208 return true;
1209 }
1210 }
1211
Sebastian Redl72b597d2009-01-25 19:43:20 +00001212 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001213}
1214
Douglas Gregor39c16d42008-10-24 04:54:22 +00001215/// CheckPointerConversion - Check the pointer conversion from the
1216/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001217/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001218/// conversions for which IsPointerConversion has already returned
1219/// true. It returns true and produces a diagnostic if there was an
1220/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001221bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001222 CastExpr::CastKind &Kind,
1223 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001224 QualType FromType = From->getType();
1225
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001226 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1227 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001228 QualType FromPointeeType = FromPtrType->getPointeeType(),
1229 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001230
Douglas Gregor39c16d42008-10-24 04:54:22 +00001231 if (FromPointeeType->isRecordType() &&
1232 ToPointeeType->isRecordType()) {
1233 // We must have a derived-to-base conversion. Check an
1234 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001235 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1236 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001237 From->getSourceRange(),
1238 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001239 return true;
1240
1241 // The conversion was successful.
1242 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001243 }
1244 }
Mike Stump11289f42009-09-09 15:08:12 +00001245 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001246 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001247 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001248 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001249 // Objective-C++ conversions are always okay.
1250 // FIXME: We should have a different class of conversions for the
1251 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001252 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001253 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001254
Steve Naroff7cae42b2009-07-10 23:34:53 +00001255 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001256 return false;
1257}
1258
Sebastian Redl72b597d2009-01-25 19:43:20 +00001259/// IsMemberPointerConversion - Determines whether the conversion of the
1260/// expression From, which has the (possibly adjusted) type FromType, can be
1261/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1262/// If so, returns true and places the converted type (that might differ from
1263/// ToType in its cv-qualifiers at some level) into ConvertedType.
1264bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001265 QualType ToType,
1266 bool InOverloadResolution,
1267 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001268 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001269 if (!ToTypePtr)
1270 return false;
1271
1272 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001273 if (From->isNullPointerConstant(Context,
1274 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1275 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001276 ConvertedType = ToType;
1277 return true;
1278 }
1279
1280 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001281 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001282 if (!FromTypePtr)
1283 return false;
1284
1285 // A pointer to member of B can be converted to a pointer to member of D,
1286 // where D is derived from B (C++ 4.11p2).
1287 QualType FromClass(FromTypePtr->getClass(), 0);
1288 QualType ToClass(ToTypePtr->getClass(), 0);
1289 // FIXME: What happens when these are dependent? Is this function even called?
1290
1291 if (IsDerivedFrom(ToClass, FromClass)) {
1292 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1293 ToClass.getTypePtr());
1294 return true;
1295 }
1296
1297 return false;
1298}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001299
Sebastian Redl72b597d2009-01-25 19:43:20 +00001300/// CheckMemberPointerConversion - Check the member pointer conversion from the
1301/// expression From to the type ToType. This routine checks for ambiguous or
1302/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1303/// for which IsMemberPointerConversion has already returned true. It returns
1304/// true and produces a diagnostic if there was an error, or returns false
1305/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001306bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001307 CastExpr::CastKind &Kind,
1308 bool IgnoreBaseAccess) {
1309 (void)IgnoreBaseAccess;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001310 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001311 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001312 if (!FromPtrType) {
1313 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001314 assert(From->isNullPointerConstant(Context,
1315 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001316 "Expr must be null pointer constant!");
1317 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001318 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001319 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001320
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001321 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001322 assert(ToPtrType && "No member pointer cast has a target type "
1323 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001324
Sebastian Redled8f2002009-01-28 18:33:18 +00001325 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1326 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001327
Sebastian Redled8f2002009-01-28 18:33:18 +00001328 // FIXME: What about dependent types?
1329 assert(FromClass->isRecordType() && "Pointer into non-class.");
1330 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001331
Douglas Gregor36d1b142009-10-06 17:59:45 +00001332 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1333 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001334 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1335 assert(DerivationOkay &&
1336 "Should not have been called if derivation isn't OK.");
1337 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001338
Sebastian Redled8f2002009-01-28 18:33:18 +00001339 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1340 getUnqualifiedType())) {
1341 // Derivation is ambiguous. Redo the check to find the exact paths.
1342 Paths.clear();
1343 Paths.setRecordingPaths(true);
1344 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1345 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1346 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001347
Sebastian Redled8f2002009-01-28 18:33:18 +00001348 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1349 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1350 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1351 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001352 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001353
Douglas Gregor89ee6822009-02-28 01:32:25 +00001354 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001355 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1356 << FromClass << ToClass << QualType(VBase, 0)
1357 << From->getSourceRange();
1358 return true;
1359 }
1360
Anders Carlssond7923c62009-08-22 23:33:40 +00001361 // Must be a base to derived member conversion.
1362 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001363 return false;
1364}
1365
Douglas Gregor9a657932008-10-21 23:43:52 +00001366/// IsQualificationConversion - Determines whether the conversion from
1367/// an rvalue of type FromType to ToType is a qualification conversion
1368/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001369bool
1370Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001371 FromType = Context.getCanonicalType(FromType);
1372 ToType = Context.getCanonicalType(ToType);
1373
1374 // If FromType and ToType are the same type, this is not a
1375 // qualification conversion.
1376 if (FromType == ToType)
1377 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001378
Douglas Gregor9a657932008-10-21 23:43:52 +00001379 // (C++ 4.4p4):
1380 // A conversion can add cv-qualifiers at levels other than the first
1381 // in multi-level pointers, subject to the following rules: [...]
1382 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001383 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001384 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001385 // Within each iteration of the loop, we check the qualifiers to
1386 // determine if this still looks like a qualification
1387 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001388 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001389 // until there are no more pointers or pointers-to-members left to
1390 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001391 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001392
1393 // -- for every j > 0, if const is in cv 1,j then const is in cv
1394 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001395 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001396 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001397
Douglas Gregor9a657932008-10-21 23:43:52 +00001398 // -- if the cv 1,j and cv 2,j are different, then const is in
1399 // every cv for 0 < k < j.
1400 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001401 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001402 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001403
Douglas Gregor9a657932008-10-21 23:43:52 +00001404 // Keep track of whether all prior cv-qualifiers in the "to" type
1405 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001406 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001407 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001408 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001409
1410 // We are left with FromType and ToType being the pointee types
1411 // after unwrapping the original FromType and ToType the same number
1412 // of types. If we unwrapped any pointers, and if FromType and
1413 // ToType have the same unqualified type (since we checked
1414 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001415 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001416}
1417
Douglas Gregor576e98c2009-01-30 23:27:23 +00001418/// Determines whether there is a user-defined conversion sequence
1419/// (C++ [over.ics.user]) that converts expression From to the type
1420/// ToType. If such a conversion exists, User will contain the
1421/// user-defined conversion sequence that performs such a conversion
1422/// and this routine will return true. Otherwise, this routine returns
1423/// false and User is unspecified.
1424///
1425/// \param AllowConversionFunctions true if the conversion should
1426/// consider conversion functions at all. If false, only constructors
1427/// will be considered.
1428///
1429/// \param AllowExplicit true if the conversion should consider C++0x
1430/// "explicit" conversion functions as well as non-explicit conversion
1431/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001432///
1433/// \param ForceRValue true if the expression should be treated as an rvalue
1434/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001435/// \param UserCast true if looking for user defined conversion for a static
1436/// cast.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001437OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1438 UserDefinedConversionSequence& User,
1439 OverloadCandidateSet& CandidateSet,
1440 bool AllowConversionFunctions,
1441 bool AllowExplicit,
1442 bool ForceRValue,
1443 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001444 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001445 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1446 // We're not going to find any constructors.
1447 } else if (CXXRecordDecl *ToRecordDecl
1448 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001449 // C++ [over.match.ctor]p1:
1450 // When objects of class type are direct-initialized (8.5), or
1451 // copy-initialized from an expression of the same or a
1452 // derived class type (8.5), overload resolution selects the
1453 // constructor. [...] For copy-initialization, the candidate
1454 // functions are all the converting constructors (12.3.1) of
1455 // that class. The argument list is the expression-list within
1456 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001457 bool SuppressUserConversions = !UserCast;
1458 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1459 IsDerivedFrom(From->getType(), ToType)) {
1460 SuppressUserConversions = false;
1461 AllowConversionFunctions = false;
1462 }
1463
Mike Stump11289f42009-09-09 15:08:12 +00001464 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001465 = Context.DeclarationNames.getCXXConstructorName(
1466 Context.getCanonicalType(ToType).getUnqualifiedType());
1467 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001468 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001469 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001470 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001471 // Find the constructor (which may be a template).
1472 CXXConstructorDecl *Constructor = 0;
1473 FunctionTemplateDecl *ConstructorTmpl
1474 = dyn_cast<FunctionTemplateDecl>(*Con);
1475 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001476 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001477 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1478 else
1479 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001480
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001481 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001482 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001483 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00001484 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1485 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001486 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001487 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001488 // Allow one user-defined conversion when user specifies a
1489 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001490 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001491 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001492 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001493 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001494 }
1495 }
1496
Douglas Gregor576e98c2009-01-30 23:27:23 +00001497 if (!AllowConversionFunctions) {
1498 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001499 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1500 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001501 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001502 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001503 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001504 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001505 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001506 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1507 // Add all of the conversion functions as candidates.
John McCalld14a8642009-11-21 08:51:07 +00001508 const UnresolvedSet *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001509 = FromRecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00001510 for (UnresolvedSet::iterator I = Conversions->begin(),
1511 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00001512 NamedDecl *D = *I;
1513 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1514 if (isa<UsingShadowDecl>(D))
1515 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1516
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001517 CXXConversionDecl *Conv;
1518 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001519 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001520 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1521 else
John McCalld14a8642009-11-21 08:51:07 +00001522 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001523
1524 if (AllowExplicit || !Conv->isExplicit()) {
1525 if (ConvTemplate)
John McCall6e9f8f62009-12-03 04:06:58 +00001526 AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1527 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001528 else
John McCall6e9f8f62009-12-03 04:06:58 +00001529 AddConversionCandidate(Conv, ActingContext, From, ToType,
1530 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001531 }
1532 }
1533 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001534 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001535
1536 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001537 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001538 case OR_Success:
1539 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001540 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001541 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1542 // C++ [over.ics.user]p1:
1543 // If the user-defined conversion is specified by a
1544 // constructor (12.3.1), the initial standard conversion
1545 // sequence converts the source type to the type required by
1546 // the argument of the constructor.
1547 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001548 QualType ThisType = Constructor->getThisType(Context);
Fariborz Jahanian55824512009-11-06 00:23:08 +00001549 if (Best->Conversions[0].ConversionKind ==
1550 ImplicitConversionSequence::EllipsisConversion)
1551 User.EllipsisConversion = true;
1552 else {
1553 User.Before = Best->Conversions[0].Standard;
1554 User.EllipsisConversion = false;
1555 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001556 User.ConversionFunction = Constructor;
1557 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001558 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001559 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001560 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001561 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001562 } else if (CXXConversionDecl *Conversion
1563 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1564 // C++ [over.ics.user]p1:
1565 //
1566 // [...] If the user-defined conversion is specified by a
1567 // conversion function (12.3.2), the initial standard
1568 // conversion sequence converts the source type to the
1569 // implicit object parameter of the conversion function.
1570 User.Before = Best->Conversions[0].Standard;
1571 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001572 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001573
1574 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001575 // The second standard conversion sequence converts the
1576 // result of the user-defined conversion to the target type
1577 // for the sequence. Since an implicit conversion sequence
1578 // is an initialization, the special rules for
1579 // initialization by user-defined conversion apply when
1580 // selecting the best user-defined conversion for a
1581 // user-defined conversion sequence (see 13.3.3 and
1582 // 13.3.3.1).
1583 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001584 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001585 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001586 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001587 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001588 }
Mike Stump11289f42009-09-09 15:08:12 +00001589
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001590 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001591 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001592 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001593 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001594 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001595
1596 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001597 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001598 }
1599
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001600 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001601}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001602
1603bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001604Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001605 ImplicitConversionSequence ICS;
1606 OverloadCandidateSet CandidateSet;
1607 OverloadingResult OvResult =
1608 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1609 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001610 if (OvResult == OR_Ambiguous)
1611 Diag(From->getSourceRange().getBegin(),
1612 diag::err_typecheck_ambiguous_condition)
1613 << From->getType() << ToType << From->getSourceRange();
1614 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1615 Diag(From->getSourceRange().getBegin(),
1616 diag::err_typecheck_nonviable_condition)
1617 << From->getType() << ToType << From->getSourceRange();
1618 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001619 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00001620 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001621 return true;
1622}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001623
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001624/// CompareImplicitConversionSequences - Compare two implicit
1625/// conversion sequences to determine whether one is better than the
1626/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001627ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001628Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1629 const ImplicitConversionSequence& ICS2)
1630{
1631 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1632 // conversion sequences (as defined in 13.3.3.1)
1633 // -- a standard conversion sequence (13.3.3.1.1) is a better
1634 // conversion sequence than a user-defined conversion sequence or
1635 // an ellipsis conversion sequence, and
1636 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1637 // conversion sequence than an ellipsis conversion sequence
1638 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001639 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001640 if (ICS1.ConversionKind < ICS2.ConversionKind)
1641 return ImplicitConversionSequence::Better;
1642 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1643 return ImplicitConversionSequence::Worse;
1644
1645 // Two implicit conversion sequences of the same form are
1646 // indistinguishable conversion sequences unless one of the
1647 // following rules apply: (C++ 13.3.3.2p3):
1648 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1649 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001650 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001651 ImplicitConversionSequence::UserDefinedConversion) {
1652 // User-defined conversion sequence U1 is a better conversion
1653 // sequence than another user-defined conversion sequence U2 if
1654 // they contain the same user-defined conversion function or
1655 // constructor and if the second standard conversion sequence of
1656 // U1 is better than the second standard conversion sequence of
1657 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001658 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001659 ICS2.UserDefined.ConversionFunction)
1660 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1661 ICS2.UserDefined.After);
1662 }
1663
1664 return ImplicitConversionSequence::Indistinguishable;
1665}
1666
1667/// CompareStandardConversionSequences - Compare two standard
1668/// conversion sequences to determine whether one is better than the
1669/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001670ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001671Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1672 const StandardConversionSequence& SCS2)
1673{
1674 // Standard conversion sequence S1 is a better conversion sequence
1675 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1676
1677 // -- S1 is a proper subsequence of S2 (comparing the conversion
1678 // sequences in the canonical form defined by 13.3.3.1.1,
1679 // excluding any Lvalue Transformation; the identity conversion
1680 // sequence is considered to be a subsequence of any
1681 // non-identity conversion sequence) or, if not that,
1682 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1683 // Neither is a proper subsequence of the other. Do nothing.
1684 ;
1685 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1686 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001687 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001688 SCS1.Third == ICK_Identity))
1689 // SCS1 is a proper subsequence of SCS2.
1690 return ImplicitConversionSequence::Better;
1691 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1692 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001693 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001694 SCS2.Third == ICK_Identity))
1695 // SCS2 is a proper subsequence of SCS1.
1696 return ImplicitConversionSequence::Worse;
1697
1698 // -- the rank of S1 is better than the rank of S2 (by the rules
1699 // defined below), or, if not that,
1700 ImplicitConversionRank Rank1 = SCS1.getRank();
1701 ImplicitConversionRank Rank2 = SCS2.getRank();
1702 if (Rank1 < Rank2)
1703 return ImplicitConversionSequence::Better;
1704 else if (Rank2 < Rank1)
1705 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001707 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1708 // are indistinguishable unless one of the following rules
1709 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001710
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001711 // A conversion that is not a conversion of a pointer, or
1712 // pointer to member, to bool is better than another conversion
1713 // that is such a conversion.
1714 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1715 return SCS2.isPointerConversionToBool()
1716 ? ImplicitConversionSequence::Better
1717 : ImplicitConversionSequence::Worse;
1718
Douglas Gregor5c407d92008-10-23 00:40:37 +00001719 // C++ [over.ics.rank]p4b2:
1720 //
1721 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001722 // conversion of B* to A* is better than conversion of B* to
1723 // void*, and conversion of A* to void* is better than conversion
1724 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001725 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001726 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001727 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001728 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001729 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1730 // Exactly one of the conversion sequences is a conversion to
1731 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001732 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1733 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001734 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1735 // Neither conversion sequence converts to a void pointer; compare
1736 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001737 if (ImplicitConversionSequence::CompareKind DerivedCK
1738 = CompareDerivedToBaseConversions(SCS1, SCS2))
1739 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001740 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1741 // Both conversion sequences are conversions to void
1742 // pointers. Compare the source types to determine if there's an
1743 // inheritance relationship in their sources.
1744 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1745 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1746
1747 // Adjust the types we're converting from via the array-to-pointer
1748 // conversion, if we need to.
1749 if (SCS1.First == ICK_Array_To_Pointer)
1750 FromType1 = Context.getArrayDecayedType(FromType1);
1751 if (SCS2.First == ICK_Array_To_Pointer)
1752 FromType2 = Context.getArrayDecayedType(FromType2);
1753
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001754 QualType FromPointee1
1755 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1756 QualType FromPointee2
1757 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001758
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001759 if (IsDerivedFrom(FromPointee2, FromPointee1))
1760 return ImplicitConversionSequence::Better;
1761 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1762 return ImplicitConversionSequence::Worse;
1763
1764 // Objective-C++: If one interface is more specific than the
1765 // other, it is the better one.
1766 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1767 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1768 if (FromIface1 && FromIface1) {
1769 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1770 return ImplicitConversionSequence::Better;
1771 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1772 return ImplicitConversionSequence::Worse;
1773 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001774 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001775
1776 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1777 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001778 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001779 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001780 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001781
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001782 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001783 // C++0x [over.ics.rank]p3b4:
1784 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1785 // implicit object parameter of a non-static member function declared
1786 // without a ref-qualifier, and S1 binds an rvalue reference to an
1787 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001788 // FIXME: We don't know if we're dealing with the implicit object parameter,
1789 // or if the member function in this case has a ref qualifier.
1790 // (Of course, we don't have ref qualifiers yet.)
1791 if (SCS1.RRefBinding != SCS2.RRefBinding)
1792 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1793 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001794
1795 // C++ [over.ics.rank]p3b4:
1796 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1797 // which the references refer are the same type except for
1798 // top-level cv-qualifiers, and the type to which the reference
1799 // initialized by S2 refers is more cv-qualified than the type
1800 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001801 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1802 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001803 T1 = Context.getCanonicalType(T1);
1804 T2 = Context.getCanonicalType(T2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001805 if (Context.hasSameUnqualifiedType(T1, T2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001806 if (T2.isMoreQualifiedThan(T1))
1807 return ImplicitConversionSequence::Better;
1808 else if (T1.isMoreQualifiedThan(T2))
1809 return ImplicitConversionSequence::Worse;
1810 }
1811 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001812
1813 return ImplicitConversionSequence::Indistinguishable;
1814}
1815
1816/// CompareQualificationConversions - Compares two standard conversion
1817/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001818/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1819ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001820Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001821 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001822 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001823 // -- S1 and S2 differ only in their qualification conversion and
1824 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1825 // cv-qualification signature of type T1 is a proper subset of
1826 // the cv-qualification signature of type T2, and S1 is not the
1827 // deprecated string literal array-to-pointer conversion (4.2).
1828 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1829 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1830 return ImplicitConversionSequence::Indistinguishable;
1831
1832 // FIXME: the example in the standard doesn't use a qualification
1833 // conversion (!)
1834 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1835 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1836 T1 = Context.getCanonicalType(T1);
1837 T2 = Context.getCanonicalType(T2);
1838
1839 // If the types are the same, we won't learn anything by unwrapped
1840 // them.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001841 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001842 return ImplicitConversionSequence::Indistinguishable;
1843
Mike Stump11289f42009-09-09 15:08:12 +00001844 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001845 = ImplicitConversionSequence::Indistinguishable;
1846 while (UnwrapSimilarPointerTypes(T1, T2)) {
1847 // Within each iteration of the loop, we check the qualifiers to
1848 // determine if this still looks like a qualification
1849 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001850 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001851 // until there are no more pointers or pointers-to-members left
1852 // to unwrap. This essentially mimics what
1853 // IsQualificationConversion does, but here we're checking for a
1854 // strict subset of qualifiers.
1855 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1856 // The qualifiers are the same, so this doesn't tell us anything
1857 // about how the sequences rank.
1858 ;
1859 else if (T2.isMoreQualifiedThan(T1)) {
1860 // T1 has fewer qualifiers, so it could be the better sequence.
1861 if (Result == ImplicitConversionSequence::Worse)
1862 // Neither has qualifiers that are a subset of the other's
1863 // qualifiers.
1864 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001865
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001866 Result = ImplicitConversionSequence::Better;
1867 } else if (T1.isMoreQualifiedThan(T2)) {
1868 // T2 has fewer qualifiers, so it could be the better sequence.
1869 if (Result == ImplicitConversionSequence::Better)
1870 // Neither has qualifiers that are a subset of the other's
1871 // qualifiers.
1872 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001873
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001874 Result = ImplicitConversionSequence::Worse;
1875 } else {
1876 // Qualifiers are disjoint.
1877 return ImplicitConversionSequence::Indistinguishable;
1878 }
1879
1880 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001881 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001882 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001883 }
1884
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001885 // Check that the winning standard conversion sequence isn't using
1886 // the deprecated string literal array to pointer conversion.
1887 switch (Result) {
1888 case ImplicitConversionSequence::Better:
1889 if (SCS1.Deprecated)
1890 Result = ImplicitConversionSequence::Indistinguishable;
1891 break;
1892
1893 case ImplicitConversionSequence::Indistinguishable:
1894 break;
1895
1896 case ImplicitConversionSequence::Worse:
1897 if (SCS2.Deprecated)
1898 Result = ImplicitConversionSequence::Indistinguishable;
1899 break;
1900 }
1901
1902 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001903}
1904
Douglas Gregor5c407d92008-10-23 00:40:37 +00001905/// CompareDerivedToBaseConversions - Compares two standard conversion
1906/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001907/// various kinds of derived-to-base conversions (C++
1908/// [over.ics.rank]p4b3). As part of these checks, we also look at
1909/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001910ImplicitConversionSequence::CompareKind
1911Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1912 const StandardConversionSequence& SCS2) {
1913 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1914 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1915 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1916 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1917
1918 // Adjust the types we're converting from via the array-to-pointer
1919 // conversion, if we need to.
1920 if (SCS1.First == ICK_Array_To_Pointer)
1921 FromType1 = Context.getArrayDecayedType(FromType1);
1922 if (SCS2.First == ICK_Array_To_Pointer)
1923 FromType2 = Context.getArrayDecayedType(FromType2);
1924
1925 // Canonicalize all of the types.
1926 FromType1 = Context.getCanonicalType(FromType1);
1927 ToType1 = Context.getCanonicalType(ToType1);
1928 FromType2 = Context.getCanonicalType(FromType2);
1929 ToType2 = Context.getCanonicalType(ToType2);
1930
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001931 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001932 //
1933 // If class B is derived directly or indirectly from class A and
1934 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001935 //
1936 // For Objective-C, we let A, B, and C also be Objective-C
1937 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001938
1939 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001940 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001941 SCS2.Second == ICK_Pointer_Conversion &&
1942 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1943 FromType1->isPointerType() && FromType2->isPointerType() &&
1944 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001945 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001946 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001947 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001948 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001949 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001950 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001951 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001952 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001953
John McCall9dd450b2009-09-21 23:43:11 +00001954 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1955 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1956 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1957 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001958
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001959 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001960 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1961 if (IsDerivedFrom(ToPointee1, ToPointee2))
1962 return ImplicitConversionSequence::Better;
1963 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1964 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001965
1966 if (ToIface1 && ToIface2) {
1967 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1968 return ImplicitConversionSequence::Better;
1969 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1970 return ImplicitConversionSequence::Worse;
1971 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001972 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001973
1974 // -- conversion of B* to A* is better than conversion of C* to A*,
1975 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1976 if (IsDerivedFrom(FromPointee2, FromPointee1))
1977 return ImplicitConversionSequence::Better;
1978 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1979 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001980
Douglas Gregor237f96c2008-11-26 23:31:11 +00001981 if (FromIface1 && FromIface2) {
1982 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1983 return ImplicitConversionSequence::Better;
1984 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1985 return ImplicitConversionSequence::Worse;
1986 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001987 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001988 }
1989
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001990 // Compare based on reference bindings.
1991 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1992 SCS1.Second == ICK_Derived_To_Base) {
1993 // -- binding of an expression of type C to a reference of type
1994 // B& is better than binding an expression of type C to a
1995 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001996 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1997 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001998 if (IsDerivedFrom(ToType1, ToType2))
1999 return ImplicitConversionSequence::Better;
2000 else if (IsDerivedFrom(ToType2, ToType1))
2001 return ImplicitConversionSequence::Worse;
2002 }
2003
Douglas Gregor2fe98832008-11-03 19:09:14 +00002004 // -- binding of an expression of type B to a reference of type
2005 // A& is better than binding an expression of type C to a
2006 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002007 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2008 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002009 if (IsDerivedFrom(FromType2, FromType1))
2010 return ImplicitConversionSequence::Better;
2011 else if (IsDerivedFrom(FromType1, FromType2))
2012 return ImplicitConversionSequence::Worse;
2013 }
2014 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002015
2016 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002017 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2018 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2019 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2020 const MemberPointerType * FromMemPointer1 =
2021 FromType1->getAs<MemberPointerType>();
2022 const MemberPointerType * ToMemPointer1 =
2023 ToType1->getAs<MemberPointerType>();
2024 const MemberPointerType * FromMemPointer2 =
2025 FromType2->getAs<MemberPointerType>();
2026 const MemberPointerType * ToMemPointer2 =
2027 ToType2->getAs<MemberPointerType>();
2028 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2029 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2030 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2031 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2032 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2033 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2034 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2035 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002036 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002037 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2038 if (IsDerivedFrom(ToPointee1, ToPointee2))
2039 return ImplicitConversionSequence::Worse;
2040 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2041 return ImplicitConversionSequence::Better;
2042 }
2043 // conversion of B::* to C::* is better than conversion of A::* to C::*
2044 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2045 if (IsDerivedFrom(FromPointee1, FromPointee2))
2046 return ImplicitConversionSequence::Better;
2047 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2048 return ImplicitConversionSequence::Worse;
2049 }
2050 }
2051
Douglas Gregor2fe98832008-11-03 19:09:14 +00002052 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2053 SCS1.Second == ICK_Derived_To_Base) {
2054 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002055 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2056 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002057 if (IsDerivedFrom(ToType1, ToType2))
2058 return ImplicitConversionSequence::Better;
2059 else if (IsDerivedFrom(ToType2, ToType1))
2060 return ImplicitConversionSequence::Worse;
2061 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002062
Douglas Gregor2fe98832008-11-03 19:09:14 +00002063 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002064 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2065 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002066 if (IsDerivedFrom(FromType2, FromType1))
2067 return ImplicitConversionSequence::Better;
2068 else if (IsDerivedFrom(FromType1, FromType2))
2069 return ImplicitConversionSequence::Worse;
2070 }
2071 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002072
Douglas Gregor5c407d92008-10-23 00:40:37 +00002073 return ImplicitConversionSequence::Indistinguishable;
2074}
2075
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002076/// TryCopyInitialization - Try to copy-initialize a value of type
2077/// ToType from the expression From. Return the implicit conversion
2078/// sequence required to pass this argument, which may be a bad
2079/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002080/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002081/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2082/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002083ImplicitConversionSequence
2084Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002085 bool SuppressUserConversions, bool ForceRValue,
2086 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002087 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002088 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00002089 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002090 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002091 SuppressUserConversions,
2092 /*AllowExplicit=*/false,
2093 ForceRValue,
2094 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002095 return ICS;
2096 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002097 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002098 SuppressUserConversions,
2099 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002100 ForceRValue,
2101 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002102 }
2103}
2104
Sebastian Redl42e92c42009-04-12 17:16:29 +00002105/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2106/// the expression @p From. Returns true (and emits a diagnostic) if there was
2107/// an error, returns false if the initialization succeeded. Elidable should
2108/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2109/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002110bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002111 AssignmentAction Action, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002112 if (!getLangOptions().CPlusPlus) {
2113 // In C, argument passing is the same as performing an assignment.
2114 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002115
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002116 AssignConvertType ConvTy =
2117 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002118 if (ConvTy != Compatible &&
2119 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2120 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002121
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002122 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002123 FromType, From, Action);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002124 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002125
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002126 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002127 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002128 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002129 /*SuppressUserConversions=*/false,
2130 /*AllowExplicit=*/false,
2131 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002132
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002133 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002134 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002135 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002136 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002137 return Diag(From->getSourceRange().getBegin(),
2138 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002139 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002140 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002141}
2142
Douglas Gregor436424c2008-11-18 23:14:02 +00002143/// TryObjectArgumentInitialization - Try to initialize the object
2144/// parameter of the given member function (@c Method) from the
2145/// expression @p From.
2146ImplicitConversionSequence
John McCall6e9f8f62009-12-03 04:06:58 +00002147Sema::TryObjectArgumentInitialization(QualType FromType,
2148 CXXMethodDecl *Method,
2149 CXXRecordDecl *ActingContext) {
2150 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002151 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2152 // const volatile object.
2153 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2154 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2155 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002156
2157 // Set up the conversion sequence as a "bad" conversion, to allow us
2158 // to exit early.
2159 ImplicitConversionSequence ICS;
2160 ICS.Standard.setAsIdentityConversion();
2161 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2162
2163 // We need to have an object of class type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002164 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002165 FromType = PT->getPointeeType();
2166
2167 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002168
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002169 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002170 // where X is the class of which the function is a member
2171 // (C++ [over.match.funcs]p4). However, when finding an implicit
2172 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002173 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002174 // (C++ [over.match.funcs]p5). We perform a simplified version of
2175 // reference binding here, that allows class rvalues to bind to
2176 // non-constant references.
2177
2178 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2179 // with the implicit object parameter (C++ [over.match.funcs]p5).
2180 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002181 if (ImplicitParamType.getCVRQualifiers()
2182 != FromTypeCanon.getLocalCVRQualifiers() &&
Douglas Gregor01df9462009-11-05 00:07:36 +00002183 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor436424c2008-11-18 23:14:02 +00002184 return ICS;
2185
2186 // Check that we have either the same type or a derived type. It
2187 // affects the conversion rank.
2188 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002189 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002190 ICS.Standard.Second = ICK_Identity;
2191 else if (IsDerivedFrom(FromType, ClassType))
2192 ICS.Standard.Second = ICK_Derived_To_Base;
2193 else
2194 return ICS;
2195
2196 // Success. Mark this as a reference binding.
2197 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2198 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2199 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2200 ICS.Standard.ReferenceBinding = true;
2201 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002202 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002203 return ICS;
2204}
2205
2206/// PerformObjectArgumentInitialization - Perform initialization of
2207/// the implicit object parameter for the given Method with the given
2208/// expression.
2209bool
2210Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002211 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002212 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002213 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002214
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002215 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002216 FromRecordType = PT->getPointeeType();
2217 DestType = Method->getThisType(Context);
2218 } else {
2219 FromRecordType = From->getType();
2220 DestType = ImplicitParamRecordType;
2221 }
2222
John McCall6e9f8f62009-12-03 04:06:58 +00002223 // Note that we always use the true parent context when performing
2224 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002225 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002226 = TryObjectArgumentInitialization(From->getType(), Method,
2227 Method->getParent());
Douglas Gregor436424c2008-11-18 23:14:02 +00002228 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2229 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002230 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002231 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002232
Douglas Gregor436424c2008-11-18 23:14:02 +00002233 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002234 CheckDerivedToBaseConversion(FromRecordType,
2235 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002236 From->getSourceRange().getBegin(),
2237 From->getSourceRange()))
2238 return true;
2239
Mike Stump11289f42009-09-09 15:08:12 +00002240 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002241 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002242 return false;
2243}
2244
Douglas Gregor5fb53972009-01-14 15:45:31 +00002245/// TryContextuallyConvertToBool - Attempt to contextually convert the
2246/// expression From to bool (C++0x [conv]p3).
2247ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002248 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002249 // FIXME: Are these flags correct?
2250 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002251 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002252 /*ForceRValue=*/false,
2253 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002254}
2255
2256/// PerformContextuallyConvertToBool - Perform a contextual conversion
2257/// of the expression From to bool (C++0x [conv]p3).
2258bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2259 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002260 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting))
Douglas Gregor5fb53972009-01-14 15:45:31 +00002261 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002262
Fariborz Jahanian76197412009-11-18 18:26:29 +00002263 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002264 return Diag(From->getSourceRange().getBegin(),
2265 diag::err_typecheck_bool_condition)
2266 << From->getType() << From->getSourceRange();
2267 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002268}
2269
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002270/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002271/// candidate functions, using the given function call arguments. If
2272/// @p SuppressUserConversions, then don't allow user-defined
2273/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002274/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2275/// hacky way to implement the overloading rules for elidable copy
2276/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002277///
2278/// \para PartialOverloading true if we are performing "partial" overloading
2279/// based on an incomplete set of function arguments. This feature is used by
2280/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002281void
2282Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002283 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002284 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002285 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002286 bool ForceRValue,
2287 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002288 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002289 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002290 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002291 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002292 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002293 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002294 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002295
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002296 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002297 if (!isa<CXXConstructorDecl>(Method)) {
2298 // If we get here, it's because we're calling a member function
2299 // that is named without a member access expression (e.g.,
2300 // "this->f") that was either written explicitly or created
2301 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002302 // function, e.g., X::f(). We use an empty type for the implied
2303 // object argument (C++ [over.call.func]p3), and the acting context
2304 // is irrelevant.
2305 AddMethodCandidate(Method, Method->getParent(),
2306 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002307 SuppressUserConversions, ForceRValue);
2308 return;
2309 }
2310 // We treat a constructor like a non-member function, since its object
2311 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002312 }
2313
Douglas Gregorff7028a2009-11-13 23:59:09 +00002314 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002315 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002316
Douglas Gregor27381f32009-11-23 12:27:39 +00002317 // Overload resolution is always an unevaluated context.
2318 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2319
Douglas Gregorffe14e32009-11-14 01:20:54 +00002320 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2321 // C++ [class.copy]p3:
2322 // A member function template is never instantiated to perform the copy
2323 // of a class object to an object of its class type.
2324 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2325 if (NumArgs == 1 &&
2326 Constructor->isCopyConstructorLikeSpecialization() &&
2327 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2328 return;
2329 }
2330
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002331 // Add this candidate
2332 CandidateSet.push_back(OverloadCandidate());
2333 OverloadCandidate& Candidate = CandidateSet.back();
2334 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002335 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002336 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002337 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002338
2339 unsigned NumArgsInProto = Proto->getNumArgs();
2340
2341 // (C++ 13.3.2p2): A candidate function having fewer than m
2342 // parameters is viable only if it has an ellipsis in its parameter
2343 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002344 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2345 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002346 Candidate.Viable = false;
2347 return;
2348 }
2349
2350 // (C++ 13.3.2p2): A candidate function having more than m parameters
2351 // is viable only if the (m+1)st parameter has a default argument
2352 // (8.3.6). For the purposes of overload resolution, the
2353 // parameter list is truncated on the right, so that there are
2354 // exactly m parameters.
2355 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002356 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002357 // Not enough arguments.
2358 Candidate.Viable = false;
2359 return;
2360 }
2361
2362 // Determine the implicit conversion sequences for each of the
2363 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002364 Candidate.Conversions.resize(NumArgs);
2365 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2366 if (ArgIdx < NumArgsInProto) {
2367 // (C++ 13.3.2p3): for F to be a viable function, there shall
2368 // exist for each argument an implicit conversion sequence
2369 // (13.3.3.1) that converts that argument to the corresponding
2370 // parameter of F.
2371 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002372 Candidate.Conversions[ArgIdx]
2373 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002374 SuppressUserConversions, ForceRValue,
2375 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002376 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002377 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002378 // 13.3.3.1-p10 If several different sequences of conversions exist that
2379 // each convert the argument to the parameter type, the implicit conversion
2380 // sequence associated with the parameter is defined to be the unique conversion
2381 // sequence designated the ambiguous conversion sequence. For the purpose of
2382 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2383 // conversion sequence is treated as a user-defined sequence that is
2384 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002385 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002386 Candidate.Conversions[ArgIdx].ConversionKind =
2387 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002388 // Set the conversion function to one of them. As due to ambiguity,
2389 // they carry the same weight and is needed for overload resolution
2390 // later.
2391 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2392 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2393 }
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002394 else {
2395 Candidate.Viable = false;
2396 break;
2397 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002398 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002399 } else {
2400 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2401 // argument for which there is no corresponding parameter is
2402 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002403 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002404 = ImplicitConversionSequence::EllipsisConversion;
2405 }
2406 }
2407}
2408
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002409/// \brief Add all of the function declarations in the given function set to
2410/// the overload canddiate set.
2411void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2412 Expr **Args, unsigned NumArgs,
2413 OverloadCandidateSet& CandidateSet,
2414 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002415 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002416 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002417 F != FEnd; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002418 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002419 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2420 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2421 AddMethodCandidate(cast<CXXMethodDecl>(FD),
John McCall6e9f8f62009-12-03 04:06:58 +00002422 cast<CXXMethodDecl>(FD)->getParent(),
2423 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002424 CandidateSet, SuppressUserConversions);
2425 else
2426 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2427 SuppressUserConversions);
2428 } else {
2429 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2430 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2431 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2432 AddMethodTemplateCandidate(FunTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002433 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002434 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002435 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002436 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002437 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002438 else
2439 AddTemplateOverloadCandidate(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002440 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002441 Args, NumArgs, CandidateSet,
2442 SuppressUserConversions);
2443 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002444 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002445}
2446
John McCallf0f1cf02009-11-17 07:50:12 +00002447/// AddMethodCandidate - Adds a named decl (which is some kind of
2448/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002449void Sema::AddMethodCandidate(NamedDecl *Decl,
2450 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002451 Expr **Args, unsigned NumArgs,
2452 OverloadCandidateSet& CandidateSet,
2453 bool SuppressUserConversions, bool ForceRValue) {
2454
2455 // FIXME: use this
John McCall6e9f8f62009-12-03 04:06:58 +00002456 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002457
2458 if (isa<UsingShadowDecl>(Decl))
2459 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2460
2461 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2462 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2463 "Expected a member function template");
John McCall6e9f8f62009-12-03 04:06:58 +00002464 AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2465 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002466 CandidateSet,
2467 SuppressUserConversions,
2468 ForceRValue);
2469 } else {
John McCall6e9f8f62009-12-03 04:06:58 +00002470 AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2471 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002472 CandidateSet, SuppressUserConversions, ForceRValue);
2473 }
2474}
2475
Douglas Gregor436424c2008-11-18 23:14:02 +00002476/// AddMethodCandidate - Adds the given C++ member function to the set
2477/// of candidate functions, using the given function call arguments
2478/// and the object argument (@c Object). For example, in a call
2479/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2480/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2481/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002482/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2483/// a slightly hacky way to implement the overloading rules for elidable copy
2484/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002485void
John McCall6e9f8f62009-12-03 04:06:58 +00002486Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2487 QualType ObjectType, Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002488 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002489 bool SuppressUserConversions, bool ForceRValue) {
2490 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002491 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002492 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002493 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002494 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002495 assert(!isa<CXXConstructorDecl>(Method) &&
2496 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002497
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002498 if (!CandidateSet.isNewCandidate(Method))
2499 return;
2500
Douglas Gregor27381f32009-11-23 12:27:39 +00002501 // Overload resolution is always an unevaluated context.
2502 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2503
Douglas Gregor436424c2008-11-18 23:14:02 +00002504 // Add this candidate
2505 CandidateSet.push_back(OverloadCandidate());
2506 OverloadCandidate& Candidate = CandidateSet.back();
2507 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002508 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002509 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002510
2511 unsigned NumArgsInProto = Proto->getNumArgs();
2512
2513 // (C++ 13.3.2p2): A candidate function having fewer than m
2514 // parameters is viable only if it has an ellipsis in its parameter
2515 // list (8.3.5).
2516 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2517 Candidate.Viable = false;
2518 return;
2519 }
2520
2521 // (C++ 13.3.2p2): A candidate function having more than m parameters
2522 // is viable only if the (m+1)st parameter has a default argument
2523 // (8.3.6). For the purposes of overload resolution, the
2524 // parameter list is truncated on the right, so that there are
2525 // exactly m parameters.
2526 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2527 if (NumArgs < MinRequiredArgs) {
2528 // Not enough arguments.
2529 Candidate.Viable = false;
2530 return;
2531 }
2532
2533 Candidate.Viable = true;
2534 Candidate.Conversions.resize(NumArgs + 1);
2535
John McCall6e9f8f62009-12-03 04:06:58 +00002536 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002537 // The implicit object argument is ignored.
2538 Candidate.IgnoreObjectArgument = true;
2539 else {
2540 // Determine the implicit conversion sequence for the object
2541 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002542 Candidate.Conversions[0]
2543 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
Mike Stump11289f42009-09-09 15:08:12 +00002544 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002545 == ImplicitConversionSequence::BadConversion) {
2546 Candidate.Viable = false;
2547 return;
2548 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002549 }
2550
2551 // Determine the implicit conversion sequences for each of the
2552 // arguments.
2553 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2554 if (ArgIdx < NumArgsInProto) {
2555 // (C++ 13.3.2p3): for F to be a viable function, there shall
2556 // exist for each argument an implicit conversion sequence
2557 // (13.3.3.1) that converts that argument to the corresponding
2558 // parameter of F.
2559 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002560 Candidate.Conversions[ArgIdx + 1]
2561 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002562 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002563 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002564 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002565 == ImplicitConversionSequence::BadConversion) {
2566 Candidate.Viable = false;
2567 break;
2568 }
2569 } else {
2570 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2571 // argument for which there is no corresponding parameter is
2572 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002573 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002574 = ImplicitConversionSequence::EllipsisConversion;
2575 }
2576 }
2577}
2578
Douglas Gregor97628d62009-08-21 00:16:32 +00002579/// \brief Add a C++ member function template as a candidate to the candidate
2580/// set, using template argument deduction to produce an appropriate member
2581/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002582void
Douglas Gregor97628d62009-08-21 00:16:32 +00002583Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002584 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002585 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002586 QualType ObjectType,
2587 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002588 OverloadCandidateSet& CandidateSet,
2589 bool SuppressUserConversions,
2590 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002591 if (!CandidateSet.isNewCandidate(MethodTmpl))
2592 return;
2593
Douglas Gregor97628d62009-08-21 00:16:32 +00002594 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002595 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002596 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002597 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002598 // candidate functions in the usual way.113) A given name can refer to one
2599 // or more function templates and also to a set of overloaded non-template
2600 // functions. In such a case, the candidate functions generated from each
2601 // function template are combined with the set of non-template candidate
2602 // functions.
2603 TemplateDeductionInfo Info(Context);
2604 FunctionDecl *Specialization = 0;
2605 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002606 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002607 Args, NumArgs, Specialization, Info)) {
2608 // FIXME: Record what happened with template argument deduction, so
2609 // that we can give the user a beautiful diagnostic.
2610 (void)Result;
2611 return;
2612 }
Mike Stump11289f42009-09-09 15:08:12 +00002613
Douglas Gregor97628d62009-08-21 00:16:32 +00002614 // Add the function template specialization produced by template argument
2615 // deduction as a candidate.
2616 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002617 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002618 "Specialization is not a member function?");
John McCall6e9f8f62009-12-03 04:06:58 +00002619 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2620 ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002621 CandidateSet, SuppressUserConversions, ForceRValue);
2622}
2623
Douglas Gregor05155d82009-08-21 23:19:43 +00002624/// \brief Add a C++ function template specialization as a candidate
2625/// in the candidate set, using template argument deduction to produce
2626/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002627void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002628Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002629 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002630 Expr **Args, unsigned NumArgs,
2631 OverloadCandidateSet& CandidateSet,
2632 bool SuppressUserConversions,
2633 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002634 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2635 return;
2636
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002637 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002638 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002639 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002640 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002641 // candidate functions in the usual way.113) A given name can refer to one
2642 // or more function templates and also to a set of overloaded non-template
2643 // functions. In such a case, the candidate functions generated from each
2644 // function template are combined with the set of non-template candidate
2645 // functions.
2646 TemplateDeductionInfo Info(Context);
2647 FunctionDecl *Specialization = 0;
2648 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002649 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002650 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002651 // FIXME: Record what happened with template argument deduction, so
2652 // that we can give the user a beautiful diagnostic.
John McCalld681c392009-12-16 08:11:27 +00002653 (void) Result;
2654
2655 CandidateSet.push_back(OverloadCandidate());
2656 OverloadCandidate &Candidate = CandidateSet.back();
2657 Candidate.Function = FunctionTemplate->getTemplatedDecl();
2658 Candidate.Viable = false;
2659 Candidate.IsSurrogate = false;
2660 Candidate.IgnoreObjectArgument = false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002661 return;
2662 }
Mike Stump11289f42009-09-09 15:08:12 +00002663
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002664 // Add the function template specialization produced by template argument
2665 // deduction as a candidate.
2666 assert(Specialization && "Missing function template specialization?");
2667 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2668 SuppressUserConversions, ForceRValue);
2669}
Mike Stump11289f42009-09-09 15:08:12 +00002670
Douglas Gregora1f013e2008-11-07 22:36:19 +00002671/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002672/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002673/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002674/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002675/// (which may or may not be the same type as the type that the
2676/// conversion function produces).
2677void
2678Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002679 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002680 Expr *From, QualType ToType,
2681 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002682 assert(!Conversion->getDescribedFunctionTemplate() &&
2683 "Conversion function templates use AddTemplateConversionCandidate");
2684
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002685 if (!CandidateSet.isNewCandidate(Conversion))
2686 return;
2687
Douglas Gregor27381f32009-11-23 12:27:39 +00002688 // Overload resolution is always an unevaluated context.
2689 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2690
Douglas Gregora1f013e2008-11-07 22:36:19 +00002691 // Add this candidate
2692 CandidateSet.push_back(OverloadCandidate());
2693 OverloadCandidate& Candidate = CandidateSet.back();
2694 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002695 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002696 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002697 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002698 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002699 = Conversion->getConversionType().getAsOpaquePtr();
2700 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2701
Douglas Gregor436424c2008-11-18 23:14:02 +00002702 // Determine the implicit conversion sequence for the implicit
2703 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002704 Candidate.Viable = true;
2705 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002706 Candidate.Conversions[0]
2707 = TryObjectArgumentInitialization(From->getType(), Conversion,
2708 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002709 // Conversion functions to a different type in the base class is visible in
2710 // the derived class. So, a derived to base conversion should not participate
2711 // in overload resolution.
2712 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2713 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002714 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002715 == ImplicitConversionSequence::BadConversion) {
2716 Candidate.Viable = false;
2717 return;
2718 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002719
2720 // We won't go through a user-define type conversion function to convert a
2721 // derived to base as such conversions are given Conversion Rank. They only
2722 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2723 QualType FromCanon
2724 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2725 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2726 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2727 Candidate.Viable = false;
2728 return;
2729 }
2730
Douglas Gregora1f013e2008-11-07 22:36:19 +00002731
2732 // To determine what the conversion from the result of calling the
2733 // conversion function to the type we're eventually trying to
2734 // convert to (ToType), we need to synthesize a call to the
2735 // conversion function and attempt copy initialization from it. This
2736 // makes sure that we get the right semantics with respect to
2737 // lvalues/rvalues and the type. Fortunately, we can allocate this
2738 // call on the stack and we don't need its arguments to be
2739 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002740 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002741 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002742 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002743 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002744 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002745
2746 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002747 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2748 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002749 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002750 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002751 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002752 ImplicitConversionSequence ICS =
2753 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002754 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002755 /*ForceRValue=*/false,
2756 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002757
Douglas Gregora1f013e2008-11-07 22:36:19 +00002758 switch (ICS.ConversionKind) {
2759 case ImplicitConversionSequence::StandardConversion:
2760 Candidate.FinalConversion = ICS.Standard;
2761 break;
2762
2763 case ImplicitConversionSequence::BadConversion:
2764 Candidate.Viable = false;
2765 break;
2766
2767 default:
Mike Stump11289f42009-09-09 15:08:12 +00002768 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002769 "Can only end up with a standard conversion sequence or failure");
2770 }
2771}
2772
Douglas Gregor05155d82009-08-21 23:19:43 +00002773/// \brief Adds a conversion function template specialization
2774/// candidate to the overload set, using template argument deduction
2775/// to deduce the template arguments of the conversion function
2776/// template from the type that we are converting to (C++
2777/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002778void
Douglas Gregor05155d82009-08-21 23:19:43 +00002779Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6e9f8f62009-12-03 04:06:58 +00002780 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002781 Expr *From, QualType ToType,
2782 OverloadCandidateSet &CandidateSet) {
2783 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2784 "Only conversion function templates permitted here");
2785
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002786 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2787 return;
2788
Douglas Gregor05155d82009-08-21 23:19:43 +00002789 TemplateDeductionInfo Info(Context);
2790 CXXConversionDecl *Specialization = 0;
2791 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002792 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002793 Specialization, Info)) {
2794 // FIXME: Record what happened with template argument deduction, so
2795 // that we can give the user a beautiful diagnostic.
2796 (void)Result;
2797 return;
2798 }
Mike Stump11289f42009-09-09 15:08:12 +00002799
Douglas Gregor05155d82009-08-21 23:19:43 +00002800 // Add the conversion function template specialization produced by
2801 // template argument deduction as a candidate.
2802 assert(Specialization && "Missing function template specialization?");
John McCall6e9f8f62009-12-03 04:06:58 +00002803 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002804}
2805
Douglas Gregorab7897a2008-11-19 22:57:39 +00002806/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2807/// converts the given @c Object to a function pointer via the
2808/// conversion function @c Conversion, and then attempts to call it
2809/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2810/// the type of function that we'll eventually be calling.
2811void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002812 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002813 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002814 QualType ObjectType,
2815 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002816 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002817 if (!CandidateSet.isNewCandidate(Conversion))
2818 return;
2819
Douglas Gregor27381f32009-11-23 12:27:39 +00002820 // Overload resolution is always an unevaluated context.
2821 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2822
Douglas Gregorab7897a2008-11-19 22:57:39 +00002823 CandidateSet.push_back(OverloadCandidate());
2824 OverloadCandidate& Candidate = CandidateSet.back();
2825 Candidate.Function = 0;
2826 Candidate.Surrogate = Conversion;
2827 Candidate.Viable = true;
2828 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002829 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002830 Candidate.Conversions.resize(NumArgs + 1);
2831
2832 // Determine the implicit conversion sequence for the implicit
2833 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002834 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002835 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
Douglas Gregorab7897a2008-11-19 22:57:39 +00002836 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2837 Candidate.Viable = false;
2838 return;
2839 }
2840
2841 // The first conversion is actually a user-defined conversion whose
2842 // first conversion is ObjectInit's standard conversion (which is
2843 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002844 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002845 = ImplicitConversionSequence::UserDefinedConversion;
2846 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002847 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002848 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002849 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002850 = Candidate.Conversions[0].UserDefined.Before;
2851 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2852
Mike Stump11289f42009-09-09 15:08:12 +00002853 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002854 unsigned NumArgsInProto = Proto->getNumArgs();
2855
2856 // (C++ 13.3.2p2): A candidate function having fewer than m
2857 // parameters is viable only if it has an ellipsis in its parameter
2858 // list (8.3.5).
2859 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2860 Candidate.Viable = false;
2861 return;
2862 }
2863
2864 // Function types don't have any default arguments, so just check if
2865 // we have enough arguments.
2866 if (NumArgs < NumArgsInProto) {
2867 // Not enough arguments.
2868 Candidate.Viable = false;
2869 return;
2870 }
2871
2872 // Determine the implicit conversion sequences for each of the
2873 // arguments.
2874 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2875 if (ArgIdx < NumArgsInProto) {
2876 // (C++ 13.3.2p3): for F to be a viable function, there shall
2877 // exist for each argument an implicit conversion sequence
2878 // (13.3.3.1) that converts that argument to the corresponding
2879 // parameter of F.
2880 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002881 Candidate.Conversions[ArgIdx + 1]
2882 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002883 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002884 /*ForceRValue=*/false,
2885 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002886 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002887 == ImplicitConversionSequence::BadConversion) {
2888 Candidate.Viable = false;
2889 break;
2890 }
2891 } else {
2892 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2893 // argument for which there is no corresponding parameter is
2894 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002895 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002896 = ImplicitConversionSequence::EllipsisConversion;
2897 }
2898 }
2899}
2900
Mike Stump87c57ac2009-05-16 07:39:55 +00002901// FIXME: This will eventually be removed, once we've migrated all of the
2902// operator overloading logic over to the scheme used by binary operators, which
2903// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002904void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002905 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002906 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002907 OverloadCandidateSet& CandidateSet,
2908 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002909 FunctionSet Functions;
2910
2911 QualType T1 = Args[0]->getType();
2912 QualType T2;
2913 if (NumArgs > 1)
2914 T2 = Args[1]->getType();
2915
2916 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002917 if (S)
2918 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002919 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002920 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2921 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002922 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002923}
2924
2925/// \brief Add overload candidates for overloaded operators that are
2926/// member functions.
2927///
2928/// Add the overloaded operator candidates that are member functions
2929/// for the operator Op that was used in an operator expression such
2930/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2931/// CandidateSet will store the added overload candidates. (C++
2932/// [over.match.oper]).
2933void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2934 SourceLocation OpLoc,
2935 Expr **Args, unsigned NumArgs,
2936 OverloadCandidateSet& CandidateSet,
2937 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002938 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2939
2940 // C++ [over.match.oper]p3:
2941 // For a unary operator @ with an operand of a type whose
2942 // cv-unqualified version is T1, and for a binary operator @ with
2943 // a left operand of a type whose cv-unqualified version is T1 and
2944 // a right operand of a type whose cv-unqualified version is T2,
2945 // three sets of candidate functions, designated member
2946 // candidates, non-member candidates and built-in candidates, are
2947 // constructed as follows:
2948 QualType T1 = Args[0]->getType();
2949 QualType T2;
2950 if (NumArgs > 1)
2951 T2 = Args[1]->getType();
2952
2953 // -- If T1 is a class type, the set of member candidates is the
2954 // result of the qualified lookup of T1::operator@
2955 // (13.3.1.1.1); otherwise, the set of member candidates is
2956 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002957 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002958 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002959 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002960 return;
Mike Stump11289f42009-09-09 15:08:12 +00002961
John McCall27b18f82009-11-17 02:14:36 +00002962 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2963 LookupQualifiedName(Operators, T1Rec->getDecl());
2964 Operators.suppressDiagnostics();
2965
Mike Stump11289f42009-09-09 15:08:12 +00002966 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002967 OperEnd = Operators.end();
2968 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00002969 ++Oper)
John McCall6e9f8f62009-12-03 04:06:58 +00002970 AddMethodCandidate(*Oper, Args[0]->getType(),
2971 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00002972 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002973 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002974}
2975
Douglas Gregora11693b2008-11-12 17:17:38 +00002976/// AddBuiltinCandidate - Add a candidate for a built-in
2977/// operator. ResultTy and ParamTys are the result and parameter types
2978/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002979/// arguments being passed to the candidate. IsAssignmentOperator
2980/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002981/// operator. NumContextualBoolArguments is the number of arguments
2982/// (at the beginning of the argument list) that will be contextually
2983/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002984void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002985 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002986 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002987 bool IsAssignmentOperator,
2988 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00002989 // Overload resolution is always an unevaluated context.
2990 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2991
Douglas Gregora11693b2008-11-12 17:17:38 +00002992 // Add this candidate
2993 CandidateSet.push_back(OverloadCandidate());
2994 OverloadCandidate& Candidate = CandidateSet.back();
2995 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002996 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002997 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002998 Candidate.BuiltinTypes.ResultTy = ResultTy;
2999 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3000 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3001
3002 // Determine the implicit conversion sequences for each of the
3003 // arguments.
3004 Candidate.Viable = true;
3005 Candidate.Conversions.resize(NumArgs);
3006 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003007 // C++ [over.match.oper]p4:
3008 // For the built-in assignment operators, conversions of the
3009 // left operand are restricted as follows:
3010 // -- no temporaries are introduced to hold the left operand, and
3011 // -- no user-defined conversions are applied to the left
3012 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003013 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003014 //
3015 // We block these conversions by turning off user-defined
3016 // conversions, since that is the only way that initialization of
3017 // a reference to a non-class type can occur from something that
3018 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003019 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003020 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003021 "Contextual conversion to bool requires bool type");
3022 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3023 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003024 Candidate.Conversions[ArgIdx]
3025 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003026 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003027 /*ForceRValue=*/false,
3028 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003029 }
Mike Stump11289f42009-09-09 15:08:12 +00003030 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00003031 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003032 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003033 break;
3034 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003035 }
3036}
3037
3038/// BuiltinCandidateTypeSet - A set of types that will be used for the
3039/// candidate operator functions for built-in operators (C++
3040/// [over.built]). The types are separated into pointer types and
3041/// enumeration types.
3042class BuiltinCandidateTypeSet {
3043 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003044 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003045
3046 /// PointerTypes - The set of pointer types that will be used in the
3047 /// built-in candidates.
3048 TypeSet PointerTypes;
3049
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003050 /// MemberPointerTypes - The set of member pointer types that will be
3051 /// used in the built-in candidates.
3052 TypeSet MemberPointerTypes;
3053
Douglas Gregora11693b2008-11-12 17:17:38 +00003054 /// EnumerationTypes - The set of enumeration types that will be
3055 /// used in the built-in candidates.
3056 TypeSet EnumerationTypes;
3057
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003058 /// Sema - The semantic analysis instance where we are building the
3059 /// candidate type set.
3060 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003061
Douglas Gregora11693b2008-11-12 17:17:38 +00003062 /// Context - The AST context in which we will build the type sets.
3063 ASTContext &Context;
3064
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003065 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3066 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003067 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003068
3069public:
3070 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003071 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003072
Mike Stump11289f42009-09-09 15:08:12 +00003073 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003074 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003075
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003076 void AddTypesConvertedFrom(QualType Ty,
3077 SourceLocation Loc,
3078 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003079 bool AllowExplicitConversions,
3080 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003081
3082 /// pointer_begin - First pointer type found;
3083 iterator pointer_begin() { return PointerTypes.begin(); }
3084
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003085 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003086 iterator pointer_end() { return PointerTypes.end(); }
3087
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003088 /// member_pointer_begin - First member pointer type found;
3089 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3090
3091 /// member_pointer_end - Past the last member pointer type found;
3092 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3093
Douglas Gregora11693b2008-11-12 17:17:38 +00003094 /// enumeration_begin - First enumeration type found;
3095 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3096
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003097 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003098 iterator enumeration_end() { return EnumerationTypes.end(); }
3099};
3100
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003101/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003102/// the set of pointer types along with any more-qualified variants of
3103/// that type. For example, if @p Ty is "int const *", this routine
3104/// will add "int const *", "int const volatile *", "int const
3105/// restrict *", and "int const volatile restrict *" to the set of
3106/// pointer types. Returns true if the add of @p Ty itself succeeded,
3107/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003108///
3109/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003110bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003111BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3112 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003113
Douglas Gregora11693b2008-11-12 17:17:38 +00003114 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003115 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003116 return false;
3117
John McCall8ccfcb52009-09-24 19:53:00 +00003118 const PointerType *PointerTy = Ty->getAs<PointerType>();
3119 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003120
John McCall8ccfcb52009-09-24 19:53:00 +00003121 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003122 // Don't add qualified variants of arrays. For one, they're not allowed
3123 // (the qualifier would sink to the element type), and for another, the
3124 // only overload situation where it matters is subscript or pointer +- int,
3125 // and those shouldn't have qualifier variants anyway.
3126 if (PointeeTy->isArrayType())
3127 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003128 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003129 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003130 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003131 bool hasVolatile = VisibleQuals.hasVolatile();
3132 bool hasRestrict = VisibleQuals.hasRestrict();
3133
John McCall8ccfcb52009-09-24 19:53:00 +00003134 // Iterate through all strict supersets of BaseCVR.
3135 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3136 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003137 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3138 // in the types.
3139 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3140 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003141 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3142 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003143 }
3144
3145 return true;
3146}
3147
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003148/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3149/// to the set of pointer types along with any more-qualified variants of
3150/// that type. For example, if @p Ty is "int const *", this routine
3151/// will add "int const *", "int const volatile *", "int const
3152/// restrict *", and "int const volatile restrict *" to the set of
3153/// pointer types. Returns true if the add of @p Ty itself succeeded,
3154/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003155///
3156/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003157bool
3158BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3159 QualType Ty) {
3160 // Insert this type.
3161 if (!MemberPointerTypes.insert(Ty))
3162 return false;
3163
John McCall8ccfcb52009-09-24 19:53:00 +00003164 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3165 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003166
John McCall8ccfcb52009-09-24 19:53:00 +00003167 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003168 // Don't add qualified variants of arrays. For one, they're not allowed
3169 // (the qualifier would sink to the element type), and for another, the
3170 // only overload situation where it matters is subscript or pointer +- int,
3171 // and those shouldn't have qualifier variants anyway.
3172 if (PointeeTy->isArrayType())
3173 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003174 const Type *ClassTy = PointerTy->getClass();
3175
3176 // Iterate through all strict supersets of the pointee type's CVR
3177 // qualifiers.
3178 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3179 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3180 if ((CVR | BaseCVR) != CVR) continue;
3181
3182 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3183 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003184 }
3185
3186 return true;
3187}
3188
Douglas Gregora11693b2008-11-12 17:17:38 +00003189/// AddTypesConvertedFrom - Add each of the types to which the type @p
3190/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003191/// primarily interested in pointer types and enumeration types. We also
3192/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003193/// AllowUserConversions is true if we should look at the conversion
3194/// functions of a class type, and AllowExplicitConversions if we
3195/// should also include the explicit conversion functions of a class
3196/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003197void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003198BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003199 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003200 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003201 bool AllowExplicitConversions,
3202 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003203 // Only deal with canonical types.
3204 Ty = Context.getCanonicalType(Ty);
3205
3206 // Look through reference types; they aren't part of the type of an
3207 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003208 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003209 Ty = RefTy->getPointeeType();
3210
3211 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003212 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003213
Sebastian Redl65ae2002009-11-05 16:36:20 +00003214 // If we're dealing with an array type, decay to the pointer.
3215 if (Ty->isArrayType())
3216 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3217
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003218 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003219 QualType PointeeTy = PointerTy->getPointeeType();
3220
3221 // Insert our type, and its more-qualified variants, into the set
3222 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003223 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003224 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003225 } else if (Ty->isMemberPointerType()) {
3226 // Member pointers are far easier, since the pointee can't be converted.
3227 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3228 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003229 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003230 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003231 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003232 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003233 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003234 // No conversion functions in incomplete types.
3235 return;
3236 }
Mike Stump11289f42009-09-09 15:08:12 +00003237
Douglas Gregora11693b2008-11-12 17:17:38 +00003238 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003239 const UnresolvedSet *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003240 = ClassDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00003241 for (UnresolvedSet::iterator I = Conversions->begin(),
3242 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003243
Mike Stump11289f42009-09-09 15:08:12 +00003244 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003245 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003246 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003247 continue;
3248
John McCalld14a8642009-11-21 08:51:07 +00003249 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003250 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003251 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003252 VisibleQuals);
3253 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003254 }
3255 }
3256 }
3257}
3258
Douglas Gregor84605ae2009-08-24 13:43:27 +00003259/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3260/// the volatile- and non-volatile-qualified assignment operators for the
3261/// given type to the candidate set.
3262static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3263 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003264 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003265 unsigned NumArgs,
3266 OverloadCandidateSet &CandidateSet) {
3267 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003268
Douglas Gregor84605ae2009-08-24 13:43:27 +00003269 // T& operator=(T&, T)
3270 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3271 ParamTypes[1] = T;
3272 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3273 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003274
Douglas Gregor84605ae2009-08-24 13:43:27 +00003275 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3276 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003277 ParamTypes[0]
3278 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003279 ParamTypes[1] = T;
3280 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003281 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003282 }
3283}
Mike Stump11289f42009-09-09 15:08:12 +00003284
Sebastian Redl1054fae2009-10-25 17:03:50 +00003285/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3286/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003287static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3288 Qualifiers VRQuals;
3289 const RecordType *TyRec;
3290 if (const MemberPointerType *RHSMPType =
3291 ArgExpr->getType()->getAs<MemberPointerType>())
3292 TyRec = cast<RecordType>(RHSMPType->getClass());
3293 else
3294 TyRec = ArgExpr->getType()->getAs<RecordType>();
3295 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003296 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003297 VRQuals.addVolatile();
3298 VRQuals.addRestrict();
3299 return VRQuals;
3300 }
3301
3302 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003303 const UnresolvedSet *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003304 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003305
John McCalld14a8642009-11-21 08:51:07 +00003306 for (UnresolvedSet::iterator I = Conversions->begin(),
3307 E = Conversions->end(); I != E; ++I) {
3308 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003309 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3310 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3311 CanTy = ResTypeRef->getPointeeType();
3312 // Need to go down the pointer/mempointer chain and add qualifiers
3313 // as see them.
3314 bool done = false;
3315 while (!done) {
3316 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3317 CanTy = ResTypePtr->getPointeeType();
3318 else if (const MemberPointerType *ResTypeMPtr =
3319 CanTy->getAs<MemberPointerType>())
3320 CanTy = ResTypeMPtr->getPointeeType();
3321 else
3322 done = true;
3323 if (CanTy.isVolatileQualified())
3324 VRQuals.addVolatile();
3325 if (CanTy.isRestrictQualified())
3326 VRQuals.addRestrict();
3327 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3328 return VRQuals;
3329 }
3330 }
3331 }
3332 return VRQuals;
3333}
3334
Douglas Gregord08452f2008-11-19 15:42:04 +00003335/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3336/// operator overloads to the candidate set (C++ [over.built]), based
3337/// on the operator @p Op and the arguments given. For example, if the
3338/// operator is a binary '+', this routine might add "int
3339/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003340void
Mike Stump11289f42009-09-09 15:08:12 +00003341Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003342 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003343 Expr **Args, unsigned NumArgs,
3344 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003345 // The set of "promoted arithmetic types", which are the arithmetic
3346 // types are that preserved by promotion (C++ [over.built]p2). Note
3347 // that the first few of these types are the promoted integral
3348 // types; these types need to be first.
3349 // FIXME: What about complex?
3350 const unsigned FirstIntegralType = 0;
3351 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003352 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003353 LastPromotedIntegralType = 13;
3354 const unsigned FirstPromotedArithmeticType = 7,
3355 LastPromotedArithmeticType = 16;
3356 const unsigned NumArithmeticTypes = 16;
3357 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003358 Context.BoolTy, Context.CharTy, Context.WCharTy,
3359// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003360 Context.SignedCharTy, Context.ShortTy,
3361 Context.UnsignedCharTy, Context.UnsignedShortTy,
3362 Context.IntTy, Context.LongTy, Context.LongLongTy,
3363 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3364 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3365 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003366 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3367 "Invalid first promoted integral type");
3368 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3369 == Context.UnsignedLongLongTy &&
3370 "Invalid last promoted integral type");
3371 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3372 "Invalid first promoted arithmetic type");
3373 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3374 == Context.LongDoubleTy &&
3375 "Invalid last promoted arithmetic type");
3376
Douglas Gregora11693b2008-11-12 17:17:38 +00003377 // Find all of the types that the arguments can convert to, but only
3378 // if the operator we're looking at has built-in operator candidates
3379 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003380 Qualifiers VisibleTypeConversionsQuals;
3381 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003382 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3383 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3384
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003385 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003386 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3387 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003388 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003389 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003390 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003391 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003392 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003393 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003394 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003395 true,
3396 (Op == OO_Exclaim ||
3397 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003398 Op == OO_PipePipe),
3399 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003400 }
3401
3402 bool isComparison = false;
3403 switch (Op) {
3404 case OO_None:
3405 case NUM_OVERLOADED_OPERATORS:
3406 assert(false && "Expected an overloaded operator");
3407 break;
3408
Douglas Gregord08452f2008-11-19 15:42:04 +00003409 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003410 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003411 goto UnaryStar;
3412 else
3413 goto BinaryStar;
3414 break;
3415
3416 case OO_Plus: // '+' is either unary or binary
3417 if (NumArgs == 1)
3418 goto UnaryPlus;
3419 else
3420 goto BinaryPlus;
3421 break;
3422
3423 case OO_Minus: // '-' is either unary or binary
3424 if (NumArgs == 1)
3425 goto UnaryMinus;
3426 else
3427 goto BinaryMinus;
3428 break;
3429
3430 case OO_Amp: // '&' is either unary or binary
3431 if (NumArgs == 1)
3432 goto UnaryAmp;
3433 else
3434 goto BinaryAmp;
3435
3436 case OO_PlusPlus:
3437 case OO_MinusMinus:
3438 // C++ [over.built]p3:
3439 //
3440 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3441 // is either volatile or empty, there exist candidate operator
3442 // functions of the form
3443 //
3444 // VQ T& operator++(VQ T&);
3445 // T operator++(VQ T&, int);
3446 //
3447 // C++ [over.built]p4:
3448 //
3449 // For every pair (T, VQ), where T is an arithmetic type other
3450 // than bool, and VQ is either volatile or empty, there exist
3451 // candidate operator functions of the form
3452 //
3453 // VQ T& operator--(VQ T&);
3454 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003455 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003456 Arith < NumArithmeticTypes; ++Arith) {
3457 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003458 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003459 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003460
3461 // Non-volatile version.
3462 if (NumArgs == 1)
3463 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3464 else
3465 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003466 // heuristic to reduce number of builtin candidates in the set.
3467 // Add volatile version only if there are conversions to a volatile type.
3468 if (VisibleTypeConversionsQuals.hasVolatile()) {
3469 // Volatile version
3470 ParamTypes[0]
3471 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3472 if (NumArgs == 1)
3473 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3474 else
3475 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3476 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003477 }
3478
3479 // C++ [over.built]p5:
3480 //
3481 // For every pair (T, VQ), where T is a cv-qualified or
3482 // cv-unqualified object type, and VQ is either volatile or
3483 // empty, there exist candidate operator functions of the form
3484 //
3485 // T*VQ& operator++(T*VQ&);
3486 // T*VQ& operator--(T*VQ&);
3487 // T* operator++(T*VQ&, int);
3488 // T* operator--(T*VQ&, int);
3489 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3490 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3491 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003492 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003493 continue;
3494
Mike Stump11289f42009-09-09 15:08:12 +00003495 QualType ParamTypes[2] = {
3496 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003497 };
Mike Stump11289f42009-09-09 15:08:12 +00003498
Douglas Gregord08452f2008-11-19 15:42:04 +00003499 // Without volatile
3500 if (NumArgs == 1)
3501 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3502 else
3503 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3504
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003505 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3506 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003507 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003508 ParamTypes[0]
3509 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003510 if (NumArgs == 1)
3511 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3512 else
3513 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3514 }
3515 }
3516 break;
3517
3518 UnaryStar:
3519 // C++ [over.built]p6:
3520 // For every cv-qualified or cv-unqualified object type T, there
3521 // exist candidate operator functions of the form
3522 //
3523 // T& operator*(T*);
3524 //
3525 // C++ [over.built]p7:
3526 // For every function type T, there exist candidate operator
3527 // functions of the form
3528 // T& operator*(T*);
3529 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3530 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3531 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003532 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003533 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003534 &ParamTy, Args, 1, CandidateSet);
3535 }
3536 break;
3537
3538 UnaryPlus:
3539 // C++ [over.built]p8:
3540 // For every type T, there exist candidate operator functions of
3541 // the form
3542 //
3543 // T* operator+(T*);
3544 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3545 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3546 QualType ParamTy = *Ptr;
3547 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3548 }
Mike Stump11289f42009-09-09 15:08:12 +00003549
Douglas Gregord08452f2008-11-19 15:42:04 +00003550 // Fall through
3551
3552 UnaryMinus:
3553 // C++ [over.built]p9:
3554 // For every promoted arithmetic type T, there exist candidate
3555 // operator functions of the form
3556 //
3557 // T operator+(T);
3558 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003559 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003560 Arith < LastPromotedArithmeticType; ++Arith) {
3561 QualType ArithTy = ArithmeticTypes[Arith];
3562 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3563 }
3564 break;
3565
3566 case OO_Tilde:
3567 // C++ [over.built]p10:
3568 // For every promoted integral type T, there exist candidate
3569 // operator functions of the form
3570 //
3571 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003572 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003573 Int < LastPromotedIntegralType; ++Int) {
3574 QualType IntTy = ArithmeticTypes[Int];
3575 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3576 }
3577 break;
3578
Douglas Gregora11693b2008-11-12 17:17:38 +00003579 case OO_New:
3580 case OO_Delete:
3581 case OO_Array_New:
3582 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003583 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003584 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003585 break;
3586
3587 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003588 UnaryAmp:
3589 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003590 // C++ [over.match.oper]p3:
3591 // -- For the operator ',', the unary operator '&', or the
3592 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003593 break;
3594
Douglas Gregor84605ae2009-08-24 13:43:27 +00003595 case OO_EqualEqual:
3596 case OO_ExclaimEqual:
3597 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003598 // For every pointer to member type T, there exist candidate operator
3599 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003600 //
3601 // bool operator==(T,T);
3602 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003603 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003604 MemPtr = CandidateTypes.member_pointer_begin(),
3605 MemPtrEnd = CandidateTypes.member_pointer_end();
3606 MemPtr != MemPtrEnd;
3607 ++MemPtr) {
3608 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3609 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3610 }
Mike Stump11289f42009-09-09 15:08:12 +00003611
Douglas Gregor84605ae2009-08-24 13:43:27 +00003612 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003613
Douglas Gregora11693b2008-11-12 17:17:38 +00003614 case OO_Less:
3615 case OO_Greater:
3616 case OO_LessEqual:
3617 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003618 // C++ [over.built]p15:
3619 //
3620 // For every pointer or enumeration type T, there exist
3621 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003622 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003623 // bool operator<(T, T);
3624 // bool operator>(T, T);
3625 // bool operator<=(T, T);
3626 // bool operator>=(T, T);
3627 // bool operator==(T, T);
3628 // bool operator!=(T, T);
3629 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3630 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3631 QualType ParamTypes[2] = { *Ptr, *Ptr };
3632 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3633 }
Mike Stump11289f42009-09-09 15:08:12 +00003634 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003635 = CandidateTypes.enumeration_begin();
3636 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3637 QualType ParamTypes[2] = { *Enum, *Enum };
3638 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3639 }
3640
3641 // Fall through.
3642 isComparison = true;
3643
Douglas Gregord08452f2008-11-19 15:42:04 +00003644 BinaryPlus:
3645 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003646 if (!isComparison) {
3647 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3648
3649 // C++ [over.built]p13:
3650 //
3651 // For every cv-qualified or cv-unqualified object type T
3652 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003653 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003654 // T* operator+(T*, ptrdiff_t);
3655 // T& operator[](T*, ptrdiff_t); [BELOW]
3656 // T* operator-(T*, ptrdiff_t);
3657 // T* operator+(ptrdiff_t, T*);
3658 // T& operator[](ptrdiff_t, T*); [BELOW]
3659 //
3660 // C++ [over.built]p14:
3661 //
3662 // For every T, where T is a pointer to object type, there
3663 // exist candidate operator functions of the form
3664 //
3665 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003666 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003667 = CandidateTypes.pointer_begin();
3668 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3669 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3670
3671 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3672 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3673
3674 if (Op == OO_Plus) {
3675 // T* operator+(ptrdiff_t, T*);
3676 ParamTypes[0] = ParamTypes[1];
3677 ParamTypes[1] = *Ptr;
3678 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3679 } else {
3680 // ptrdiff_t operator-(T, T);
3681 ParamTypes[1] = *Ptr;
3682 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3683 Args, 2, CandidateSet);
3684 }
3685 }
3686 }
3687 // Fall through
3688
Douglas Gregora11693b2008-11-12 17:17:38 +00003689 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003690 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003691 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003692 // C++ [over.built]p12:
3693 //
3694 // For every pair of promoted arithmetic types L and R, there
3695 // exist candidate operator functions of the form
3696 //
3697 // LR operator*(L, R);
3698 // LR operator/(L, R);
3699 // LR operator+(L, R);
3700 // LR operator-(L, R);
3701 // bool operator<(L, R);
3702 // bool operator>(L, R);
3703 // bool operator<=(L, R);
3704 // bool operator>=(L, R);
3705 // bool operator==(L, R);
3706 // bool operator!=(L, R);
3707 //
3708 // where LR is the result of the usual arithmetic conversions
3709 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003710 //
3711 // C++ [over.built]p24:
3712 //
3713 // For every pair of promoted arithmetic types L and R, there exist
3714 // candidate operator functions of the form
3715 //
3716 // LR operator?(bool, L, R);
3717 //
3718 // where LR is the result of the usual arithmetic conversions
3719 // between types L and R.
3720 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003721 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003722 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003723 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003724 Right < LastPromotedArithmeticType; ++Right) {
3725 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003726 QualType Result
3727 = isComparison
3728 ? Context.BoolTy
3729 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003730 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3731 }
3732 }
3733 break;
3734
3735 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003736 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003737 case OO_Caret:
3738 case OO_Pipe:
3739 case OO_LessLess:
3740 case OO_GreaterGreater:
3741 // C++ [over.built]p17:
3742 //
3743 // For every pair of promoted integral types L and R, there
3744 // exist candidate operator functions of the form
3745 //
3746 // LR operator%(L, R);
3747 // LR operator&(L, R);
3748 // LR operator^(L, R);
3749 // LR operator|(L, R);
3750 // L operator<<(L, R);
3751 // L operator>>(L, R);
3752 //
3753 // where LR is the result of the usual arithmetic conversions
3754 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003755 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003756 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003757 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003758 Right < LastPromotedIntegralType; ++Right) {
3759 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3760 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3761 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003762 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003763 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3764 }
3765 }
3766 break;
3767
3768 case OO_Equal:
3769 // C++ [over.built]p20:
3770 //
3771 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003772 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003773 // empty, there exist candidate operator functions of the form
3774 //
3775 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003776 for (BuiltinCandidateTypeSet::iterator
3777 Enum = CandidateTypes.enumeration_begin(),
3778 EnumEnd = CandidateTypes.enumeration_end();
3779 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003780 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003781 CandidateSet);
3782 for (BuiltinCandidateTypeSet::iterator
3783 MemPtr = CandidateTypes.member_pointer_begin(),
3784 MemPtrEnd = CandidateTypes.member_pointer_end();
3785 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003786 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003787 CandidateSet);
3788 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003789
3790 case OO_PlusEqual:
3791 case OO_MinusEqual:
3792 // C++ [over.built]p19:
3793 //
3794 // For every pair (T, VQ), where T is any type and VQ is either
3795 // volatile or empty, there exist candidate operator functions
3796 // of the form
3797 //
3798 // T*VQ& operator=(T*VQ&, T*);
3799 //
3800 // C++ [over.built]p21:
3801 //
3802 // For every pair (T, VQ), where T is a cv-qualified or
3803 // cv-unqualified object type and VQ is either volatile or
3804 // empty, there exist candidate operator functions of the form
3805 //
3806 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3807 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3808 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3809 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3810 QualType ParamTypes[2];
3811 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3812
3813 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003814 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003815 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3816 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003817
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003818 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3819 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003820 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003821 ParamTypes[0]
3822 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003823 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3824 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003825 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003826 }
3827 // Fall through.
3828
3829 case OO_StarEqual:
3830 case OO_SlashEqual:
3831 // C++ [over.built]p18:
3832 //
3833 // For every triple (L, VQ, R), where L is an arithmetic type,
3834 // VQ is either volatile or empty, and R is a promoted
3835 // arithmetic type, there exist candidate operator functions of
3836 // the form
3837 //
3838 // VQ L& operator=(VQ L&, R);
3839 // VQ L& operator*=(VQ L&, R);
3840 // VQ L& operator/=(VQ L&, R);
3841 // VQ L& operator+=(VQ L&, R);
3842 // VQ L& operator-=(VQ L&, R);
3843 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003844 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003845 Right < LastPromotedArithmeticType; ++Right) {
3846 QualType ParamTypes[2];
3847 ParamTypes[1] = ArithmeticTypes[Right];
3848
3849 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003850 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003851 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3852 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003853
3854 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003855 if (VisibleTypeConversionsQuals.hasVolatile()) {
3856 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3857 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3858 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3859 /*IsAssigmentOperator=*/Op == OO_Equal);
3860 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003861 }
3862 }
3863 break;
3864
3865 case OO_PercentEqual:
3866 case OO_LessLessEqual:
3867 case OO_GreaterGreaterEqual:
3868 case OO_AmpEqual:
3869 case OO_CaretEqual:
3870 case OO_PipeEqual:
3871 // C++ [over.built]p22:
3872 //
3873 // For every triple (L, VQ, R), where L is an integral type, VQ
3874 // is either volatile or empty, and R is a promoted integral
3875 // type, there exist candidate operator functions of the form
3876 //
3877 // VQ L& operator%=(VQ L&, R);
3878 // VQ L& operator<<=(VQ L&, R);
3879 // VQ L& operator>>=(VQ L&, R);
3880 // VQ L& operator&=(VQ L&, R);
3881 // VQ L& operator^=(VQ L&, R);
3882 // VQ L& operator|=(VQ L&, R);
3883 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003884 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003885 Right < LastPromotedIntegralType; ++Right) {
3886 QualType ParamTypes[2];
3887 ParamTypes[1] = ArithmeticTypes[Right];
3888
3889 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003890 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003891 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003892 if (VisibleTypeConversionsQuals.hasVolatile()) {
3893 // Add this built-in operator as a candidate (VQ is 'volatile').
3894 ParamTypes[0] = ArithmeticTypes[Left];
3895 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3896 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3897 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3898 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003899 }
3900 }
3901 break;
3902
Douglas Gregord08452f2008-11-19 15:42:04 +00003903 case OO_Exclaim: {
3904 // C++ [over.operator]p23:
3905 //
3906 // There also exist candidate operator functions of the form
3907 //
Mike Stump11289f42009-09-09 15:08:12 +00003908 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003909 // bool operator&&(bool, bool); [BELOW]
3910 // bool operator||(bool, bool); [BELOW]
3911 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003912 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3913 /*IsAssignmentOperator=*/false,
3914 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003915 break;
3916 }
3917
Douglas Gregora11693b2008-11-12 17:17:38 +00003918 case OO_AmpAmp:
3919 case OO_PipePipe: {
3920 // C++ [over.operator]p23:
3921 //
3922 // There also exist candidate operator functions of the form
3923 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003924 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003925 // bool operator&&(bool, bool);
3926 // bool operator||(bool, bool);
3927 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003928 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3929 /*IsAssignmentOperator=*/false,
3930 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003931 break;
3932 }
3933
3934 case OO_Subscript:
3935 // C++ [over.built]p13:
3936 //
3937 // For every cv-qualified or cv-unqualified object type T there
3938 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003939 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003940 // T* operator+(T*, ptrdiff_t); [ABOVE]
3941 // T& operator[](T*, ptrdiff_t);
3942 // T* operator-(T*, ptrdiff_t); [ABOVE]
3943 // T* operator+(ptrdiff_t, T*); [ABOVE]
3944 // T& operator[](ptrdiff_t, T*);
3945 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3946 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3947 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003948 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003949 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003950
3951 // T& operator[](T*, ptrdiff_t)
3952 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3953
3954 // T& operator[](ptrdiff_t, T*);
3955 ParamTypes[0] = ParamTypes[1];
3956 ParamTypes[1] = *Ptr;
3957 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3958 }
3959 break;
3960
3961 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003962 // C++ [over.built]p11:
3963 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3964 // C1 is the same type as C2 or is a derived class of C2, T is an object
3965 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3966 // there exist candidate operator functions of the form
3967 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3968 // where CV12 is the union of CV1 and CV2.
3969 {
3970 for (BuiltinCandidateTypeSet::iterator Ptr =
3971 CandidateTypes.pointer_begin();
3972 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3973 QualType C1Ty = (*Ptr);
3974 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003975 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003976 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003977 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003978 if (!isa<RecordType>(C1))
3979 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003980 // heuristic to reduce number of builtin candidates in the set.
3981 // Add volatile/restrict version only if there are conversions to a
3982 // volatile/restrict type.
3983 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3984 continue;
3985 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3986 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003987 }
3988 for (BuiltinCandidateTypeSet::iterator
3989 MemPtr = CandidateTypes.member_pointer_begin(),
3990 MemPtrEnd = CandidateTypes.member_pointer_end();
3991 MemPtr != MemPtrEnd; ++MemPtr) {
3992 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3993 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00003994 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003995 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3996 break;
3997 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3998 // build CV12 T&
3999 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004000 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4001 T.isVolatileQualified())
4002 continue;
4003 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4004 T.isRestrictQualified())
4005 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004006 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004007 QualType ResultTy = Context.getLValueReferenceType(T);
4008 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4009 }
4010 }
4011 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004012 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004013
4014 case OO_Conditional:
4015 // Note that we don't consider the first argument, since it has been
4016 // contextually converted to bool long ago. The candidates below are
4017 // therefore added as binary.
4018 //
4019 // C++ [over.built]p24:
4020 // For every type T, where T is a pointer or pointer-to-member type,
4021 // there exist candidate operator functions of the form
4022 //
4023 // T operator?(bool, T, T);
4024 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004025 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4026 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4027 QualType ParamTypes[2] = { *Ptr, *Ptr };
4028 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4029 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004030 for (BuiltinCandidateTypeSet::iterator Ptr =
4031 CandidateTypes.member_pointer_begin(),
4032 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4033 QualType ParamTypes[2] = { *Ptr, *Ptr };
4034 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4035 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004036 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004037 }
4038}
4039
Douglas Gregore254f902009-02-04 00:32:51 +00004040/// \brief Add function candidates found via argument-dependent lookup
4041/// to the set of overloading candidates.
4042///
4043/// This routine performs argument-dependent name lookup based on the
4044/// given function name (which may also be an operator name) and adds
4045/// all of the overload candidates found by ADL to the overload
4046/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004047void
Douglas Gregore254f902009-02-04 00:32:51 +00004048Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4049 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004050 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004051 OverloadCandidateSet& CandidateSet,
4052 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004053 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00004054
Douglas Gregorcabea402009-09-22 15:41:20 +00004055 // FIXME: Should we be trafficking in canonical function decls throughout?
4056
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004057 // Record all of the function candidates that we've already
4058 // added to the overload set, so that we don't add those same
4059 // candidates a second time.
4060 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4061 CandEnd = CandidateSet.end();
4062 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004063 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004064 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004065 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4066 Functions.insert(FunTmpl);
4067 }
Douglas Gregore254f902009-02-04 00:32:51 +00004068
Douglas Gregorcabea402009-09-22 15:41:20 +00004069 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00004070 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00004071
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004072 // Erase all of the candidates we already knew about.
4073 // FIXME: This is suboptimal. Is there a better way?
4074 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4075 CandEnd = CandidateSet.end();
4076 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004077 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004078 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004079 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4080 Functions.erase(FunTmpl);
4081 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004082
4083 // For each of the ADL candidates we found, add it to the overload
4084 // set.
4085 for (FunctionSet::iterator Func = Functions.begin(),
4086 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00004087 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004088 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCall6b51f282009-11-23 01:53:49 +00004089 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004090 continue;
4091
4092 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4093 false, false, PartialOverloading);
4094 } else
Mike Stump11289f42009-09-09 15:08:12 +00004095 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00004096 ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004097 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004098 }
Douglas Gregore254f902009-02-04 00:32:51 +00004099}
4100
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004101/// isBetterOverloadCandidate - Determines whether the first overload
4102/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004103bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004104Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00004105 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004106 // Define viable functions to be better candidates than non-viable
4107 // functions.
4108 if (!Cand2.Viable)
4109 return Cand1.Viable;
4110 else if (!Cand1.Viable)
4111 return false;
4112
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004113 // C++ [over.match.best]p1:
4114 //
4115 // -- if F is a static member function, ICS1(F) is defined such
4116 // that ICS1(F) is neither better nor worse than ICS1(G) for
4117 // any function G, and, symmetrically, ICS1(G) is neither
4118 // better nor worse than ICS1(F).
4119 unsigned StartArg = 0;
4120 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4121 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004122
Douglas Gregord3cb3562009-07-07 23:38:56 +00004123 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004124 // A viable function F1 is defined to be a better function than another
4125 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004126 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004127 unsigned NumArgs = Cand1.Conversions.size();
4128 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4129 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004130 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004131 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4132 Cand2.Conversions[ArgIdx])) {
4133 case ImplicitConversionSequence::Better:
4134 // Cand1 has a better conversion sequence.
4135 HasBetterConversion = true;
4136 break;
4137
4138 case ImplicitConversionSequence::Worse:
4139 // Cand1 can't be better than Cand2.
4140 return false;
4141
4142 case ImplicitConversionSequence::Indistinguishable:
4143 // Do nothing.
4144 break;
4145 }
4146 }
4147
Mike Stump11289f42009-09-09 15:08:12 +00004148 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004149 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004150 if (HasBetterConversion)
4151 return true;
4152
Mike Stump11289f42009-09-09 15:08:12 +00004153 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004154 // specialization, or, if not that,
4155 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4156 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4157 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004158
4159 // -- F1 and F2 are function template specializations, and the function
4160 // template for F1 is more specialized than the template for F2
4161 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004162 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004163 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4164 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004165 if (FunctionTemplateDecl *BetterTemplate
4166 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4167 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004168 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4169 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004170 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004171
Douglas Gregora1f013e2008-11-07 22:36:19 +00004172 // -- the context is an initialization by user-defined conversion
4173 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4174 // from the return type of F1 to the destination type (i.e.,
4175 // the type of the entity being initialized) is a better
4176 // conversion sequence than the standard conversion sequence
4177 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004178 if (Cand1.Function && Cand2.Function &&
4179 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004180 isa<CXXConversionDecl>(Cand2.Function)) {
4181 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4182 Cand2.FinalConversion)) {
4183 case ImplicitConversionSequence::Better:
4184 // Cand1 has a better conversion sequence.
4185 return true;
4186
4187 case ImplicitConversionSequence::Worse:
4188 // Cand1 can't be better than Cand2.
4189 return false;
4190
4191 case ImplicitConversionSequence::Indistinguishable:
4192 // Do nothing
4193 break;
4194 }
4195 }
4196
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004197 return false;
4198}
4199
Mike Stump11289f42009-09-09 15:08:12 +00004200/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004201/// within an overload candidate set.
4202///
4203/// \param CandidateSet the set of candidate functions.
4204///
4205/// \param Loc the location of the function name (or operator symbol) for
4206/// which overload resolution occurs.
4207///
Mike Stump11289f42009-09-09 15:08:12 +00004208/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004209/// function, Best points to the candidate function found.
4210///
4211/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004212OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4213 SourceLocation Loc,
4214 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004215 // Find the best viable function.
4216 Best = CandidateSet.end();
4217 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4218 Cand != CandidateSet.end(); ++Cand) {
4219 if (Cand->Viable) {
4220 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4221 Best = Cand;
4222 }
4223 }
4224
4225 // If we didn't find any viable functions, abort.
4226 if (Best == CandidateSet.end())
4227 return OR_No_Viable_Function;
4228
4229 // Make sure that this function is better than every other viable
4230 // function. If not, we have an ambiguity.
4231 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4232 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004233 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004234 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004235 !isBetterOverloadCandidate(*Best, *Cand)) {
4236 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004237 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004238 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004239 }
Mike Stump11289f42009-09-09 15:08:12 +00004240
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004241 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004242 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004243 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004244 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004245 return OR_Deleted;
4246
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004247 // C++ [basic.def.odr]p2:
4248 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004249 // when referred to from a potentially-evaluated expression. [Note: this
4250 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004251 // (clause 13), user-defined conversions (12.3.2), allocation function for
4252 // placement new (5.3.4), as well as non-default initialization (8.5).
4253 if (Best->Function)
4254 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004255 return OR_Success;
4256}
4257
4258/// PrintOverloadCandidates - When overload resolution fails, prints
4259/// diagnostic messages containing the candidates in the candidate
4260/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00004261void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004262Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004263 bool OnlyViable,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004264 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004265 SourceLocation OpLoc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004266 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4267 LastCand = CandidateSet.end();
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004268 bool Reported = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004269 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004270 if (Cand->Viable || !OnlyViable) {
4271 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004272 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004273 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004274 // Deleted or "unavailable" function.
4275 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4276 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00004277 } else if (FunctionTemplateDecl *FunTmpl
4278 = Cand->Function->getPrimaryTemplate()) {
4279 // Function template specialization
4280 // FIXME: Give a better reason!
4281 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4282 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4283 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00004284 } else {
4285 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00004286 bool errReported = false;
4287 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4288 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4289 const ImplicitConversionSequence &Conversion =
4290 Cand->Conversions[i];
4291 if ((Conversion.ConversionKind !=
4292 ImplicitConversionSequence::BadConversion) ||
4293 Conversion.ConversionFunctionSet.size() == 0)
4294 continue;
4295 Diag(Cand->Function->getLocation(),
4296 diag::err_ovl_candidate_not_viable) << (i+1);
4297 errReported = true;
4298 for (int j = Conversion.ConversionFunctionSet.size()-1;
4299 j >= 0; j--) {
4300 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4301 Diag(Func->getLocation(), diag::err_ovl_candidate);
4302 }
4303 }
4304 }
4305 if (!errReported)
4306 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004307 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004308 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004309 // Desugar the type of the surrogate down to a function type,
4310 // retaining as many typedefs as possible while still showing
4311 // the function type (and, therefore, its parameter types).
4312 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004313 bool isLValueReference = false;
4314 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004315 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004316 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004317 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004318 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004319 isLValueReference = true;
4320 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004321 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004322 FnType = FnTypeRef->getPointeeType();
4323 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004324 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004325 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004326 FnType = FnTypePtr->getPointeeType();
4327 isPointer = true;
4328 }
4329 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00004330 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004331 // Reconstruct the pointer/reference as appropriate.
4332 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004333 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4334 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004335
Douglas Gregorab7897a2008-11-19 22:57:39 +00004336 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004337 << FnType;
Douglas Gregor66950a32009-09-30 21:46:01 +00004338 } else if (OnlyViable) {
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004339 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanian0fe5e032009-10-09 17:09:58 +00004340 "builtin-binary-operator-not-binary");
Fariborz Jahanian956127d2009-10-16 23:25:02 +00004341 std::string TypeStr("operator");
4342 TypeStr += Opc;
4343 TypeStr += "(";
4344 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4345 if (Cand->Conversions.size() == 1) {
4346 TypeStr += ")";
4347 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4348 }
4349 else {
4350 TypeStr += ", ";
4351 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4352 TypeStr += ")";
4353 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4354 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004355 }
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004356 else if (!Cand->Viable && !Reported) {
4357 // Non-viability might be due to ambiguous user-defined conversions,
4358 // needed for built-in operators. Report them as well, but only once
4359 // as we have typically many built-in candidates.
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004360 unsigned NoOperands = Cand->Conversions.size();
4361 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004362 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4363 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4364 ICS.ConversionFunctionSet.empty())
4365 continue;
4366 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4367 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4368 QualType FromTy =
4369 QualType(
4370 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4371 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4372 << FromTy << Func->getConversionType();
4373 }
4374 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4375 FunctionDecl *Func =
4376 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4377 Diag(Func->getLocation(),diag::err_ovl_candidate);
4378 }
4379 }
4380 Reported = true;
4381 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004382 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004383 }
4384}
4385
Douglas Gregorcd695e52008-11-10 20:40:00 +00004386/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4387/// an overloaded function (C++ [over.over]), where @p From is an
4388/// expression with overloaded function type and @p ToType is the type
4389/// we're trying to resolve to. For example:
4390///
4391/// @code
4392/// int f(double);
4393/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004394///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004395/// int (*pfd)(double) = f; // selects f(double)
4396/// @endcode
4397///
4398/// This routine returns the resulting FunctionDecl if it could be
4399/// resolved, and NULL otherwise. When @p Complain is true, this
4400/// routine will emit diagnostics if there is an error.
4401FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004402Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004403 bool Complain) {
4404 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004405 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004406 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004407 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004408 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004409 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004410 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004411 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004412 FunctionType = MemTypePtr->getPointeeType();
4413 IsMember = true;
4414 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004415
4416 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004417 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004418 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004419 return 0;
4420
4421 // Find the actual overloaded function declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004422
Douglas Gregorcd695e52008-11-10 20:40:00 +00004423 // C++ [over.over]p1:
4424 // [...] [Note: any redundant set of parentheses surrounding the
4425 // overloaded function name is ignored (5.1). ]
4426 Expr *OvlExpr = From->IgnoreParens();
4427
4428 // C++ [over.over]p1:
4429 // [...] The overloaded function name can be preceded by the &
4430 // operator.
4431 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4432 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4433 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4434 }
4435
Anders Carlssonb68b0282009-10-20 22:53:47 +00004436 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004437 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCalld14a8642009-11-21 08:51:07 +00004438
4439 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004440
John McCall10eae182009-11-30 22:42:35 +00004441 // Look into the overloaded expression.
John McCalle66edc12009-11-24 19:00:30 +00004442 if (UnresolvedLookupExpr *UL
John McCalld14a8642009-11-21 08:51:07 +00004443 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4444 Fns.append(UL->decls_begin(), UL->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00004445 if (UL->hasExplicitTemplateArgs()) {
4446 HasExplicitTemplateArgs = true;
4447 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4448 }
John McCall10eae182009-11-30 22:42:35 +00004449 } else if (UnresolvedMemberExpr *ME
4450 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4451 Fns.append(ME->decls_begin(), ME->decls_end());
4452 if (ME->hasExplicitTemplateArgs()) {
4453 HasExplicitTemplateArgs = true;
John McCall6b51f282009-11-23 01:53:49 +00004454 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004455 }
Douglas Gregor9b146582009-07-08 20:55:45 +00004456 }
Mike Stump11289f42009-09-09 15:08:12 +00004457
John McCalld14a8642009-11-21 08:51:07 +00004458 // If we didn't actually find anything, we're done.
4459 if (Fns.empty())
4460 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004461
Douglas Gregorcd695e52008-11-10 20:40:00 +00004462 // Look through all of the overloaded functions, searching for one
4463 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004464 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004465 bool FoundNonTemplateFunction = false;
John McCalld14a8642009-11-21 08:51:07 +00004466 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4467 E = Fns.end(); I != E; ++I) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004468 // C++ [over.over]p3:
4469 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004470 // targets of type "pointer-to-function" or "reference-to-function."
4471 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004472 // type "pointer-to-member-function."
4473 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004474
Mike Stump11289f42009-09-09 15:08:12 +00004475 if (FunctionTemplateDecl *FunctionTemplate
John McCalld14a8642009-11-21 08:51:07 +00004476 = dyn_cast<FunctionTemplateDecl>(*I)) {
Mike Stump11289f42009-09-09 15:08:12 +00004477 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004478 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004479 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004480 // static when converting to member pointer.
4481 if (Method->isStatic() == IsMember)
4482 continue;
4483 } else if (IsMember)
4484 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004485
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004486 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004487 // If the name is a function template, template argument deduction is
4488 // done (14.8.2.2), and if the argument deduction succeeds, the
4489 // resulting template argument list is used to generate a single
4490 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004491 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004492 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004493 FunctionDecl *Specialization = 0;
4494 TemplateDeductionInfo Info(Context);
4495 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004496 = DeduceTemplateArguments(FunctionTemplate,
4497 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor9b146582009-07-08 20:55:45 +00004498 FunctionType, Specialization, Info)) {
4499 // FIXME: make a note of the failed deduction for diagnostics.
4500 (void)Result;
4501 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004502 // FIXME: If the match isn't exact, shouldn't we just drop this as
4503 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004504 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004505 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004506 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004507 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004508 }
John McCalld14a8642009-11-21 08:51:07 +00004509
4510 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00004511 }
Mike Stump11289f42009-09-09 15:08:12 +00004512
John McCalld14a8642009-11-21 08:51:07 +00004513 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004514 // Skip non-static functions when converting to pointer, and static
4515 // when converting to member pointer.
4516 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004517 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004518
4519 // If we have explicit template arguments, skip non-templates.
4520 if (HasExplicitTemplateArgs)
4521 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004522 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004523 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004524
John McCalld14a8642009-11-21 08:51:07 +00004525 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*I)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00004526 QualType ResultTy;
4527 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4528 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4529 ResultTy)) {
John McCalld14a8642009-11-21 08:51:07 +00004530 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004531 FoundNonTemplateFunction = true;
4532 }
Mike Stump11289f42009-09-09 15:08:12 +00004533 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004534 }
4535
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004536 // If there were 0 or 1 matches, we're done.
4537 if (Matches.empty())
4538 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004539 else if (Matches.size() == 1) {
4540 FunctionDecl *Result = *Matches.begin();
4541 MarkDeclarationReferenced(From->getLocStart(), Result);
4542 return Result;
4543 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004544
4545 // C++ [over.over]p4:
4546 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004547 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004548 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004549 // [...] and any given function template specialization F1 is
4550 // eliminated if the set contains a second function template
4551 // specialization whose function template is more specialized
4552 // than the function template of F1 according to the partial
4553 // ordering rules of 14.5.5.2.
4554
4555 // The algorithm specified above is quadratic. We instead use a
4556 // two-pass algorithm (similar to the one used to identify the
4557 // best viable function in an overload set) that identifies the
4558 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004559 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004560 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004561 FunctionDecl *Result =
4562 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4563 TPOC_Other, From->getLocStart(),
4564 PDiag(),
4565 PDiag(diag::err_addr_ovl_ambiguous)
4566 << TemplateMatches[0]->getDeclName(),
4567 PDiag(diag::err_ovl_template_candidate));
4568 MarkDeclarationReferenced(From->getLocStart(), Result);
4569 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004570 }
Mike Stump11289f42009-09-09 15:08:12 +00004571
Douglas Gregorfae1d712009-09-26 03:56:17 +00004572 // [...] any function template specializations in the set are
4573 // eliminated if the set also contains a non-template function, [...]
4574 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4575 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4576 if ((*M)->getPrimaryTemplate() == 0)
4577 RemainingMatches.push_back(*M);
4578
Mike Stump11289f42009-09-09 15:08:12 +00004579 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004580 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004581 if (RemainingMatches.size() == 1) {
4582 FunctionDecl *Result = RemainingMatches.front();
4583 MarkDeclarationReferenced(From->getLocStart(), Result);
4584 return Result;
4585 }
Mike Stump11289f42009-09-09 15:08:12 +00004586
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004587 // FIXME: We should probably return the same thing that BestViableFunction
4588 // returns (even if we issue the diagnostics here).
4589 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4590 << RemainingMatches[0]->getDeclName();
4591 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4592 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004593 return 0;
4594}
4595
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004596/// \brief Given an expression that refers to an overloaded function, try to
4597/// resolve that overloaded function expression down to a single function.
4598///
4599/// This routine can only resolve template-ids that refer to a single function
4600/// template, where that template-id refers to a single template whose template
4601/// arguments are either provided by the template-id or have defaults,
4602/// as described in C++0x [temp.arg.explicit]p3.
4603FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
4604 // C++ [over.over]p1:
4605 // [...] [Note: any redundant set of parentheses surrounding the
4606 // overloaded function name is ignored (5.1). ]
4607 Expr *OvlExpr = From->IgnoreParens();
4608
4609 // C++ [over.over]p1:
4610 // [...] The overloaded function name can be preceded by the &
4611 // operator.
4612 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4613 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4614 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4615 }
4616
4617 bool HasExplicitTemplateArgs = false;
4618 TemplateArgumentListInfo ExplicitTemplateArgs;
4619
4620 llvm::SmallVector<NamedDecl*,8> Fns;
4621
4622 // Look into the overloaded expression.
4623 if (UnresolvedLookupExpr *UL
4624 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4625 Fns.append(UL->decls_begin(), UL->decls_end());
4626 if (UL->hasExplicitTemplateArgs()) {
4627 HasExplicitTemplateArgs = true;
4628 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4629 }
4630 } else if (UnresolvedMemberExpr *ME
4631 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4632 Fns.append(ME->decls_begin(), ME->decls_end());
4633 if (ME->hasExplicitTemplateArgs()) {
4634 HasExplicitTemplateArgs = true;
4635 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4636 }
4637 }
4638
4639 // If we didn't actually find any template-ids, we're done.
4640 if (Fns.empty() || !HasExplicitTemplateArgs)
4641 return 0;
4642
4643 // Look through all of the overloaded functions, searching for one
4644 // whose type matches exactly.
4645 FunctionDecl *Matched = 0;
4646 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4647 E = Fns.end(); I != E; ++I) {
4648 // C++0x [temp.arg.explicit]p3:
4649 // [...] In contexts where deduction is done and fails, or in contexts
4650 // where deduction is not done, if a template argument list is
4651 // specified and it, along with any default template arguments,
4652 // identifies a single function template specialization, then the
4653 // template-id is an lvalue for the function template specialization.
4654 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
4655
4656 // C++ [over.over]p2:
4657 // If the name is a function template, template argument deduction is
4658 // done (14.8.2.2), and if the argument deduction succeeds, the
4659 // resulting template argument list is used to generate a single
4660 // function template specialization, which is added to the set of
4661 // overloaded functions considered.
4662 // FIXME: We don't really want to build the specialization here, do we?
4663 FunctionDecl *Specialization = 0;
4664 TemplateDeductionInfo Info(Context);
4665 if (TemplateDeductionResult Result
4666 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
4667 Specialization, Info)) {
4668 // FIXME: make a note of the failed deduction for diagnostics.
4669 (void)Result;
4670 continue;
4671 }
4672
4673 // Multiple matches; we can't resolve to a single declaration.
4674 if (Matched)
4675 return 0;
4676
4677 Matched = Specialization;
4678 }
4679
4680 return Matched;
4681}
4682
Douglas Gregorcabea402009-09-22 15:41:20 +00004683/// \brief Add a single candidate to the overload set.
4684static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00004685 NamedDecl *Callee,
John McCall6b51f282009-11-23 01:53:49 +00004686 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004687 Expr **Args, unsigned NumArgs,
4688 OverloadCandidateSet &CandidateSet,
4689 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004690 if (isa<UsingShadowDecl>(Callee))
4691 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4692
Douglas Gregorcabea402009-09-22 15:41:20 +00004693 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004694 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorcabea402009-09-22 15:41:20 +00004695 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4696 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004697 return;
John McCalld14a8642009-11-21 08:51:07 +00004698 }
4699
4700 if (FunctionTemplateDecl *FuncTemplate
4701 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004702 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004703 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00004704 return;
4705 }
4706
4707 assert(false && "unhandled case in overloaded call candidate");
4708
4709 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00004710}
4711
4712/// \brief Add the overload candidates named by callee and/or found by argument
4713/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00004714void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00004715 Expr **Args, unsigned NumArgs,
4716 OverloadCandidateSet &CandidateSet,
4717 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004718
4719#ifndef NDEBUG
4720 // Verify that ArgumentDependentLookup is consistent with the rules
4721 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00004722 //
Douglas Gregorcabea402009-09-22 15:41:20 +00004723 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4724 // and let Y be the lookup set produced by argument dependent
4725 // lookup (defined as follows). If X contains
4726 //
4727 // -- a declaration of a class member, or
4728 //
4729 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00004730 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00004731 //
4732 // -- a declaration that is neither a function or a function
4733 // template
4734 //
4735 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00004736
John McCall57500772009-12-16 12:17:52 +00004737 if (ULE->requiresADL()) {
4738 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
4739 E = ULE->decls_end(); I != E; ++I) {
4740 assert(!(*I)->getDeclContext()->isRecord());
4741 assert(isa<UsingShadowDecl>(*I) ||
4742 !(*I)->getDeclContext()->isFunctionOrMethod());
4743 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00004744 }
4745 }
4746#endif
4747
John McCall57500772009-12-16 12:17:52 +00004748 // It would be nice to avoid this copy.
4749 TemplateArgumentListInfo TABuffer;
4750 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
4751 if (ULE->hasExplicitTemplateArgs()) {
4752 ULE->copyTemplateArgumentsInto(TABuffer);
4753 ExplicitTemplateArgs = &TABuffer;
4754 }
4755
4756 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
4757 E = ULE->decls_end(); I != E; ++I)
John McCall6b51f282009-11-23 01:53:49 +00004758 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004759 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00004760 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00004761
John McCall57500772009-12-16 12:17:52 +00004762 if (ULE->requiresADL())
4763 AddArgumentDependentLookupCandidates(ULE->getName(), Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004764 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004765 CandidateSet,
4766 PartialOverloading);
4767}
John McCalld681c392009-12-16 08:11:27 +00004768
John McCall57500772009-12-16 12:17:52 +00004769static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
4770 Expr **Args, unsigned NumArgs) {
4771 Fn->Destroy(SemaRef.Context);
4772 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4773 Args[Arg]->Destroy(SemaRef.Context);
4774 return SemaRef.ExprError();
4775}
4776
John McCalld681c392009-12-16 08:11:27 +00004777/// Attempts to recover from a call where no functions were found.
4778///
4779/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00004780static Sema::OwningExprResult
4781BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
4782 UnresolvedLookupExpr *ULE,
4783 SourceLocation LParenLoc,
4784 Expr **Args, unsigned NumArgs,
4785 SourceLocation *CommaLocs,
4786 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00004787
4788 CXXScopeSpec SS;
4789 if (ULE->getQualifier()) {
4790 SS.setScopeRep(ULE->getQualifier());
4791 SS.setRange(ULE->getQualifierRange());
4792 }
4793
John McCall57500772009-12-16 12:17:52 +00004794 TemplateArgumentListInfo TABuffer;
4795 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
4796 if (ULE->hasExplicitTemplateArgs()) {
4797 ULE->copyTemplateArgumentsInto(TABuffer);
4798 ExplicitTemplateArgs = &TABuffer;
4799 }
4800
John McCalld681c392009-12-16 08:11:27 +00004801 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
4802 Sema::LookupOrdinaryName);
4803 if (SemaRef.DiagnoseEmptyLookup(SS, R))
John McCall57500772009-12-16 12:17:52 +00004804 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00004805
John McCall57500772009-12-16 12:17:52 +00004806 assert(!R.empty() && "lookup results empty despite recovery");
4807
4808 // Build an implicit member call if appropriate. Just drop the
4809 // casts and such from the call, we don't really care.
4810 Sema::OwningExprResult NewFn = SemaRef.ExprError();
4811 if ((*R.begin())->isCXXClassMember())
4812 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
4813 else if (ExplicitTemplateArgs)
4814 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
4815 else
4816 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
4817
4818 if (NewFn.isInvalid())
4819 return Destroy(SemaRef, Fn, Args, NumArgs);
4820
4821 Fn->Destroy(SemaRef.Context);
4822
4823 // This shouldn't cause an infinite loop because we're giving it
4824 // an expression with non-empty lookup results, which should never
4825 // end up here.
4826 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
4827 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
4828 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00004829}
Douglas Gregorcabea402009-09-22 15:41:20 +00004830
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004831/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004832/// (which eventually refers to the declaration Func) and the call
4833/// arguments Args/NumArgs, attempt to resolve the function call down
4834/// to a specific function. If overload resolution succeeds, returns
4835/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004836/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004837/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00004838Sema::OwningExprResult
4839Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
4840 SourceLocation LParenLoc,
4841 Expr **Args, unsigned NumArgs,
4842 SourceLocation *CommaLocs,
4843 SourceLocation RParenLoc) {
4844#ifndef NDEBUG
4845 if (ULE->requiresADL()) {
4846 // To do ADL, we must have found an unqualified name.
4847 assert(!ULE->getQualifier() && "qualified name with ADL");
4848
4849 // We don't perform ADL for implicit declarations of builtins.
4850 // Verify that this was correctly set up.
4851 FunctionDecl *F;
4852 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
4853 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
4854 F->getBuiltinID() && F->isImplicit())
4855 assert(0 && "performing ADL for builtin");
4856
4857 // We don't perform ADL in C.
4858 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
4859 }
4860#endif
4861
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004862 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004863
John McCall57500772009-12-16 12:17:52 +00004864 // Add the functions denoted by the callee to the set of candidate
4865 // functions, including those from argument-dependent lookup.
4866 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00004867
4868 // If we found nothing, try to recover.
4869 // AddRecoveryCallCandidates diagnoses the error itself, so we just
4870 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00004871 if (CandidateSet.empty())
4872 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
4873 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00004874
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004875 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004876 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00004877 case OR_Success: {
4878 FunctionDecl *FDecl = Best->Function;
4879 Fn = FixOverloadedFunctionReference(Fn, FDecl);
4880 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
4881 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004882
4883 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004884 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004885 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00004886 << ULE->getName() << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004887 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4888 break;
4889
4890 case OR_Ambiguous:
4891 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00004892 << ULE->getName() << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004893 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4894 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004895
4896 case OR_Deleted:
4897 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4898 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00004899 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00004900 << Fn->getSourceRange();
4901 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4902 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004903 }
4904
4905 // Overload resolution failed. Destroy all of the subexpressions and
4906 // return NULL.
4907 Fn->Destroy(Context);
4908 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4909 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00004910 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004911}
4912
John McCall283b9012009-11-22 00:44:51 +00004913static bool IsOverloaded(const Sema::FunctionSet &Functions) {
4914 return Functions.size() > 1 ||
4915 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
4916}
4917
Douglas Gregor084d8552009-03-13 23:49:33 +00004918/// \brief Create a unary operation that may resolve to an overloaded
4919/// operator.
4920///
4921/// \param OpLoc The location of the operator itself (e.g., '*').
4922///
4923/// \param OpcIn The UnaryOperator::Opcode that describes this
4924/// operator.
4925///
4926/// \param Functions The set of non-member functions that will be
4927/// considered by overload resolution. The caller needs to build this
4928/// set based on the context using, e.g.,
4929/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4930/// set should not contain any member functions; those will be added
4931/// by CreateOverloadedUnaryOp().
4932///
4933/// \param input The input argument.
4934Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4935 unsigned OpcIn,
4936 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004937 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004938 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4939 Expr *Input = (Expr *)input.get();
4940
4941 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4942 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4943 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4944
4945 Expr *Args[2] = { Input, 0 };
4946 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004947
Douglas Gregor084d8552009-03-13 23:49:33 +00004948 // For post-increment and post-decrement, add the implicit '0' as
4949 // the second argument, so that we know this is a post-increment or
4950 // post-decrement.
4951 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4952 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004953 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004954 SourceLocation());
4955 NumArgs = 2;
4956 }
4957
4958 if (Input->isTypeDependent()) {
John McCalld14a8642009-11-21 08:51:07 +00004959 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00004960 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4961 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00004962 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump11289f42009-09-09 15:08:12 +00004963 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004964 FuncEnd = Functions.end();
4965 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00004966 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00004967
Douglas Gregor084d8552009-03-13 23:49:33 +00004968 input.release();
4969 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4970 &Args[0], NumArgs,
4971 Context.DependentTy,
4972 OpLoc));
4973 }
4974
4975 // Build an empty overload set.
4976 OverloadCandidateSet CandidateSet;
4977
4978 // Add the candidates from the given function set.
4979 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4980
4981 // Add operator candidates that are member functions.
4982 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4983
4984 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004985 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00004986
4987 // Perform overload resolution.
4988 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004989 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004990 case OR_Success: {
4991 // We found a built-in operator or an overloaded operator.
4992 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004993
Douglas Gregor084d8552009-03-13 23:49:33 +00004994 if (FnDecl) {
4995 // We matched an overloaded operator. Build a call to that
4996 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004997
Douglas Gregor084d8552009-03-13 23:49:33 +00004998 // Convert the arguments.
4999 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
5000 if (PerformObjectArgumentInitialization(Input, Method))
5001 return ExprError();
5002 } else {
5003 // Convert the arguments.
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005004 input = PerformCopyInitialization(
5005 InitializedEntity::InitializeParameter(
5006 FnDecl->getParamDecl(0)),
5007 SourceLocation(),
5008 move(input));
5009 if (input.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005010 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005011
5012 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005013 }
5014
5015 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005016 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005017
Douglas Gregor084d8552009-03-13 23:49:33 +00005018 // Build the actual expression node.
5019 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5020 SourceLocation());
5021 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005022
Douglas Gregor084d8552009-03-13 23:49:33 +00005023 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005024 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005025 ExprOwningPtr<CallExpr> TheCall(this,
5026 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005027 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005028
5029 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5030 FnDecl))
5031 return ExprError();
5032
5033 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005034 } else {
5035 // We matched a built-in operator. Convert the arguments, then
5036 // break out so that we will build the appropriate built-in
5037 // operator node.
5038 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005039 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005040 return ExprError();
5041
5042 break;
5043 }
5044 }
5045
5046 case OR_No_Viable_Function:
5047 // No viable function; fall through to handling this as a
5048 // built-in operator, which will produce an error message for us.
5049 break;
5050
5051 case OR_Ambiguous:
5052 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5053 << UnaryOperator::getOpcodeStr(Opc)
5054 << Input->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005055 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5056 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005057 return ExprError();
5058
5059 case OR_Deleted:
5060 Diag(OpLoc, diag::err_ovl_deleted_oper)
5061 << Best->Function->isDeleted()
5062 << UnaryOperator::getOpcodeStr(Opc)
5063 << Input->getSourceRange();
5064 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5065 return ExprError();
5066 }
5067
5068 // Either we found no viable overloaded operator or we matched a
5069 // built-in operator. In either case, fall through to trying to
5070 // build a built-in operation.
5071 input.release();
5072 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5073}
5074
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005075/// \brief Create a binary operation that may resolve to an overloaded
5076/// operator.
5077///
5078/// \param OpLoc The location of the operator itself (e.g., '+').
5079///
5080/// \param OpcIn The BinaryOperator::Opcode that describes this
5081/// operator.
5082///
5083/// \param Functions The set of non-member functions that will be
5084/// considered by overload resolution. The caller needs to build this
5085/// set based on the context using, e.g.,
5086/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5087/// set should not contain any member functions; those will be added
5088/// by CreateOverloadedBinOp().
5089///
5090/// \param LHS Left-hand argument.
5091/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005092Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005093Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005094 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005095 FunctionSet &Functions,
5096 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005097 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005098 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005099
5100 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5101 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5102 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5103
5104 // If either side is type-dependent, create an appropriate dependent
5105 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005106 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005107 if (Functions.empty()) {
5108 // If there are no functions to store, just build a dependent
5109 // BinaryOperator or CompoundAssignment.
5110 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5111 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5112 Context.DependentTy, OpLoc));
5113
5114 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5115 Context.DependentTy,
5116 Context.DependentTy,
5117 Context.DependentTy,
5118 OpLoc));
5119 }
5120
John McCalld14a8642009-11-21 08:51:07 +00005121 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005122 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5123 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00005124 /* ADL */ true, IsOverloaded(Functions));
John McCalld14a8642009-11-21 08:51:07 +00005125
Mike Stump11289f42009-09-09 15:08:12 +00005126 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005127 FuncEnd = Functions.end();
5128 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00005129 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00005130
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005131 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00005132 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005133 Context.DependentTy,
5134 OpLoc));
5135 }
5136
5137 // If this is the .* operator, which is not overloadable, just
5138 // create a built-in binary operator.
5139 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00005140 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005141
Sebastian Redl6a96bf72009-11-18 23:10:33 +00005142 // If this is the assignment operator, we only perform overload resolution
5143 // if the left-hand side is a class or enumeration type. This is actually
5144 // a hack. The standard requires that we do overload resolution between the
5145 // various built-in candidates, but as DR507 points out, this can lead to
5146 // problems. So we do it this way, which pretty much follows what GCC does.
5147 // Note that we go the traditional code path for compound assignment forms.
5148 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00005149 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005150
Douglas Gregor084d8552009-03-13 23:49:33 +00005151 // Build an empty overload set.
5152 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005153
5154 // Add the candidates from the given function set.
5155 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
5156
5157 // Add operator candidates that are member functions.
5158 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5159
5160 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005161 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005162
5163 // Perform overload resolution.
5164 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005165 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005166 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005167 // We found a built-in operator or an overloaded operator.
5168 FunctionDecl *FnDecl = Best->Function;
5169
5170 if (FnDecl) {
5171 // We matched an overloaded operator. Build a call to that
5172 // operator.
5173
5174 // Convert the arguments.
5175 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005176 OwningExprResult Arg1
5177 = PerformCopyInitialization(
5178 InitializedEntity::InitializeParameter(
5179 FnDecl->getParamDecl(0)),
5180 SourceLocation(),
5181 Owned(Args[1]));
5182 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005183 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005184
5185 if (PerformObjectArgumentInitialization(Args[0], Method))
5186 return ExprError();
5187
5188 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005189 } else {
5190 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005191 OwningExprResult Arg0
5192 = PerformCopyInitialization(
5193 InitializedEntity::InitializeParameter(
5194 FnDecl->getParamDecl(0)),
5195 SourceLocation(),
5196 Owned(Args[0]));
5197 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005198 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005199
5200 OwningExprResult Arg1
5201 = PerformCopyInitialization(
5202 InitializedEntity::InitializeParameter(
5203 FnDecl->getParamDecl(1)),
5204 SourceLocation(),
5205 Owned(Args[1]));
5206 if (Arg1.isInvalid())
5207 return ExprError();
5208 Args[0] = LHS = Arg0.takeAs<Expr>();
5209 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005210 }
5211
5212 // Determine the result type
5213 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00005214 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005215 ResultTy = ResultTy.getNonReferenceType();
5216
5217 // Build the actual expression node.
5218 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00005219 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005220 UsualUnaryConversions(FnExpr);
5221
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005222 ExprOwningPtr<CXXOperatorCallExpr>
5223 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5224 Args, 2, ResultTy,
5225 OpLoc));
5226
5227 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5228 FnDecl))
5229 return ExprError();
5230
5231 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005232 } else {
5233 // We matched a built-in operator. Convert the arguments, then
5234 // break out so that we will build the appropriate built-in
5235 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00005236 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005237 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00005238 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005239 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005240 return ExprError();
5241
5242 break;
5243 }
5244 }
5245
Douglas Gregor66950a32009-09-30 21:46:01 +00005246 case OR_No_Viable_Function: {
5247 // C++ [over.match.oper]p9:
5248 // If the operator is the operator , [...] and there are no
5249 // viable functions, then the operator is assumed to be the
5250 // built-in operator and interpreted according to clause 5.
5251 if (Opc == BinaryOperator::Comma)
5252 break;
5253
Sebastian Redl027de2a2009-05-21 11:50:50 +00005254 // For class as left operand for assignment or compound assigment operator
5255 // do not fall through to handling in built-in, but report that no overloaded
5256 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005257 OwningExprResult Result = ExprError();
5258 if (Args[0]->getType()->isRecordType() &&
5259 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005260 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5261 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005262 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005263 } else {
5264 // No viable function; try to create a built-in operation, which will
5265 // produce an error. Then, show the non-viable candidates.
5266 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005267 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005268 assert(Result.isInvalid() &&
5269 "C++ binary operator overloading is missing candidates!");
5270 if (Result.isInvalid())
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005271 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5272 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005273 return move(Result);
5274 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005275
5276 case OR_Ambiguous:
5277 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5278 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005279 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005280 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5281 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005282 return ExprError();
5283
5284 case OR_Deleted:
5285 Diag(OpLoc, diag::err_ovl_deleted_oper)
5286 << Best->Function->isDeleted()
5287 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005288 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005289 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5290 return ExprError();
5291 }
5292
Douglas Gregor66950a32009-09-30 21:46:01 +00005293 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005294 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005295}
5296
Sebastian Redladba46e2009-10-29 20:17:01 +00005297Action::OwningExprResult
5298Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5299 SourceLocation RLoc,
5300 ExprArg Base, ExprArg Idx) {
5301 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5302 static_cast<Expr*>(Idx.get()) };
5303 DeclarationName OpName =
5304 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5305
5306 // If either side is type-dependent, create an appropriate dependent
5307 // expression.
5308 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5309
John McCalld14a8642009-11-21 08:51:07 +00005310 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005311 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5312 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005313 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005314 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005315
5316 Base.release();
5317 Idx.release();
5318 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5319 Args, 2,
5320 Context.DependentTy,
5321 RLoc));
5322 }
5323
5324 // Build an empty overload set.
5325 OverloadCandidateSet CandidateSet;
5326
5327 // Subscript can only be overloaded as a member function.
5328
5329 // Add operator candidates that are member functions.
5330 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5331
5332 // Add builtin operator candidates.
5333 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5334
5335 // Perform overload resolution.
5336 OverloadCandidateSet::iterator Best;
5337 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5338 case OR_Success: {
5339 // We found a built-in operator or an overloaded operator.
5340 FunctionDecl *FnDecl = Best->Function;
5341
5342 if (FnDecl) {
5343 // We matched an overloaded operator. Build a call to that
5344 // operator.
5345
5346 // Convert the arguments.
5347 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5348 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5349 PerformCopyInitialization(Args[1],
5350 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005351 AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005352 return ExprError();
5353
5354 // Determine the result type
5355 QualType ResultTy
5356 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5357 ResultTy = ResultTy.getNonReferenceType();
5358
5359 // Build the actual expression node.
5360 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5361 LLoc);
5362 UsualUnaryConversions(FnExpr);
5363
5364 Base.release();
5365 Idx.release();
5366 ExprOwningPtr<CXXOperatorCallExpr>
5367 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5368 FnExpr, Args, 2,
5369 ResultTy, RLoc));
5370
5371 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5372 FnDecl))
5373 return ExprError();
5374
5375 return MaybeBindToTemporary(TheCall.release());
5376 } else {
5377 // We matched a built-in operator. Convert the arguments, then
5378 // break out so that we will build the appropriate built-in
5379 // operator node.
5380 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005381 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00005382 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005383 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005384 return ExprError();
5385
5386 break;
5387 }
5388 }
5389
5390 case OR_No_Viable_Function: {
5391 // No viable function; try to create a built-in operation, which will
5392 // produce an error. Then, show the non-viable candidates.
5393 OwningExprResult Result =
5394 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5395 assert(Result.isInvalid() &&
5396 "C++ subscript operator overloading is missing candidates!");
5397 if (Result.isInvalid())
5398 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5399 "[]", LLoc);
5400 return move(Result);
5401 }
5402
5403 case OR_Ambiguous:
5404 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5405 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5406 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5407 "[]", LLoc);
5408 return ExprError();
5409
5410 case OR_Deleted:
5411 Diag(LLoc, diag::err_ovl_deleted_oper)
5412 << Best->Function->isDeleted() << "[]"
5413 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5414 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5415 return ExprError();
5416 }
5417
5418 // We matched a built-in operator; build it.
5419 Base.release();
5420 Idx.release();
5421 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5422 Owned(Args[1]), RLoc);
5423}
5424
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005425/// BuildCallToMemberFunction - Build a call to a member
5426/// function. MemExpr is the expression that refers to the member
5427/// function (and includes the object parameter), Args/NumArgs are the
5428/// arguments to the function call (not including the object
5429/// parameter). The caller needs to validate that the member
5430/// expression refers to a member function or an overloaded member
5431/// function.
John McCall2d74de92009-12-01 22:10:20 +00005432Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005433Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5434 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005435 unsigned NumArgs, SourceLocation *CommaLocs,
5436 SourceLocation RParenLoc) {
5437 // Dig out the member expression. This holds both the object
5438 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00005439 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5440
John McCall10eae182009-11-30 22:42:35 +00005441 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005442 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00005443 if (isa<MemberExpr>(NakedMemExpr)) {
5444 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00005445 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5446 } else {
5447 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCall2d74de92009-12-01 22:10:20 +00005448
John McCall6e9f8f62009-12-03 04:06:58 +00005449 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00005450
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005451 // Add overload candidates
5452 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00005453
John McCall2d74de92009-12-01 22:10:20 +00005454 // FIXME: avoid copy.
5455 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5456 if (UnresExpr->hasExplicitTemplateArgs()) {
5457 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5458 TemplateArgs = &TemplateArgsBuffer;
5459 }
5460
John McCall10eae182009-11-30 22:42:35 +00005461 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5462 E = UnresExpr->decls_end(); I != E; ++I) {
5463
John McCall6e9f8f62009-12-03 04:06:58 +00005464 NamedDecl *Func = *I;
5465 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5466 if (isa<UsingShadowDecl>(Func))
5467 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5468
John McCall10eae182009-11-30 22:42:35 +00005469 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00005470 // If explicit template arguments were provided, we can't call a
5471 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00005472 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00005473 continue;
5474
John McCall6e9f8f62009-12-03 04:06:58 +00005475 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5476 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005477 } else {
John McCall10eae182009-11-30 22:42:35 +00005478 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall6e9f8f62009-12-03 04:06:58 +00005479 ActingDC, TemplateArgs,
5480 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005481 CandidateSet,
5482 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005483 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005484 }
Mike Stump11289f42009-09-09 15:08:12 +00005485
John McCall10eae182009-11-30 22:42:35 +00005486 DeclarationName DeclName = UnresExpr->getMemberName();
5487
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005488 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00005489 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005490 case OR_Success:
5491 Method = cast<CXXMethodDecl>(Best->Function);
5492 break;
5493
5494 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00005495 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005496 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005497 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005498 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5499 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005500 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005501
5502 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00005503 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005504 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005505 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5506 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005507 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005508
5509 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00005510 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00005511 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005512 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005513 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5514 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005515 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005516 }
5517
Douglas Gregor51c538b2009-11-20 19:42:02 +00005518 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00005519
John McCall2d74de92009-12-01 22:10:20 +00005520 // If overload resolution picked a static member, build a
5521 // non-member call based on that function.
5522 if (Method->isStatic()) {
5523 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5524 Args, NumArgs, RParenLoc);
5525 }
5526
John McCall10eae182009-11-30 22:42:35 +00005527 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005528 }
5529
5530 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005531 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00005532 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005533 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005534 Method->getResultType().getNonReferenceType(),
5535 RParenLoc));
5536
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005537 // Check for a valid return type.
5538 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5539 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00005540 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005541
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005542 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00005543 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00005544 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005545 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCall2d74de92009-12-01 22:10:20 +00005546 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005547 MemExpr->setBase(ObjectArg);
5548
5549 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005550 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005551 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005552 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00005553 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005554
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005555 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00005556 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00005557
John McCall2d74de92009-12-01 22:10:20 +00005558 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005559}
5560
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005561/// BuildCallToObjectOfClassType - Build a call to an object of class
5562/// type (C++ [over.call.object]), which can end up invoking an
5563/// overloaded function call operator (@c operator()) or performing a
5564/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005565Sema::ExprResult
5566Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005567 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005568 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005569 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005570 SourceLocation RParenLoc) {
5571 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005572 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005573
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005574 // C++ [over.call.object]p1:
5575 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005576 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005577 // candidate functions includes at least the function call
5578 // operators of T. The function call operators of T are obtained by
5579 // ordinary lookup of the name operator() in the context of
5580 // (E).operator().
5581 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005582 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005583
5584 if (RequireCompleteType(LParenLoc, Object->getType(),
5585 PartialDiagnostic(diag::err_incomplete_object_call)
5586 << Object->getSourceRange()))
5587 return true;
5588
John McCall27b18f82009-11-17 02:14:36 +00005589 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5590 LookupQualifiedName(R, Record->getDecl());
5591 R.suppressDiagnostics();
5592
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005593 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00005594 Oper != OperEnd; ++Oper) {
John McCall6e9f8f62009-12-03 04:06:58 +00005595 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005596 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005597 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005598
Douglas Gregorab7897a2008-11-19 22:57:39 +00005599 // C++ [over.call.object]p2:
5600 // In addition, for each conversion function declared in T of the
5601 // form
5602 //
5603 // operator conversion-type-id () cv-qualifier;
5604 //
5605 // where cv-qualifier is the same cv-qualification as, or a
5606 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005607 // denotes the type "pointer to function of (P1,...,Pn) returning
5608 // R", or the type "reference to pointer to function of
5609 // (P1,...,Pn) returning R", or the type "reference to function
5610 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005611 // is also considered as a candidate function. Similarly,
5612 // surrogate call functions are added to the set of candidate
5613 // functions for each conversion function declared in an
5614 // accessible base class provided the function is not hidden
5615 // within T by another intervening declaration.
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005616 // FIXME: Look in base classes for more conversion operators!
John McCalld14a8642009-11-21 08:51:07 +00005617 const UnresolvedSet *Conversions
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005618 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00005619 for (UnresolvedSet::iterator I = Conversions->begin(),
5620 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00005621 NamedDecl *D = *I;
5622 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5623 if (isa<UsingShadowDecl>(D))
5624 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5625
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005626 // Skip over templated conversion functions; they aren't
5627 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00005628 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005629 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005630
John McCall6e9f8f62009-12-03 04:06:58 +00005631 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00005632
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005633 // Strip the reference type (if any) and then the pointer type (if
5634 // any) to get down to what might be a function type.
5635 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5636 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5637 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005638
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005639 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall6e9f8f62009-12-03 04:06:58 +00005640 AddSurrogateCandidate(Conv, ActingContext, Proto,
5641 Object->getType(), Args, NumArgs,
5642 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005643 }
Mike Stump11289f42009-09-09 15:08:12 +00005644
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005645 // Perform overload resolution.
5646 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005647 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005648 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005649 // Overload resolution succeeded; we'll build the appropriate call
5650 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005651 break;
5652
5653 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005654 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00005655 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00005656 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00005657 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005658 break;
5659
5660 case OR_Ambiguous:
5661 Diag(Object->getSourceRange().getBegin(),
5662 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005663 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005664 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5665 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005666
5667 case OR_Deleted:
5668 Diag(Object->getSourceRange().getBegin(),
5669 diag::err_ovl_deleted_object_call)
5670 << Best->Function->isDeleted()
5671 << Object->getType() << Object->getSourceRange();
5672 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5673 break;
Mike Stump11289f42009-09-09 15:08:12 +00005674 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005675
Douglas Gregorab7897a2008-11-19 22:57:39 +00005676 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005677 // We had an error; delete all of the subexpressions and return
5678 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005679 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005680 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005681 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005682 return true;
5683 }
5684
Douglas Gregorab7897a2008-11-19 22:57:39 +00005685 if (Best->Function == 0) {
5686 // Since there is no function declaration, this is one of the
5687 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00005688 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00005689 = cast<CXXConversionDecl>(
5690 Best->Conversions[0].UserDefined.ConversionFunction);
5691
5692 // We selected one of the surrogate functions that converts the
5693 // object parameter to a function pointer. Perform the conversion
5694 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005695
5696 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005697 // and then call it.
Eli Friedmana958a012009-12-09 04:52:43 +00005698 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005699
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005700 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005701 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5702 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005703 }
5704
5705 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5706 // that calls this method, using Object for the implicit object
5707 // parameter and passing along the remaining arguments.
5708 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00005709 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005710
5711 unsigned NumArgsInProto = Proto->getNumArgs();
5712 unsigned NumArgsToCheck = NumArgs;
5713
5714 // Build the full argument list for the method call (the
5715 // implicit object parameter is placed at the beginning of the
5716 // list).
5717 Expr **MethodArgs;
5718 if (NumArgs < NumArgsInProto) {
5719 NumArgsToCheck = NumArgsInProto;
5720 MethodArgs = new Expr*[NumArgsInProto + 1];
5721 } else {
5722 MethodArgs = new Expr*[NumArgs + 1];
5723 }
5724 MethodArgs[0] = Object;
5725 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5726 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00005727
5728 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00005729 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005730 UsualUnaryConversions(NewFn);
5731
5732 // Once we've built TheCall, all of the expressions are properly
5733 // owned.
5734 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005735 ExprOwningPtr<CXXOperatorCallExpr>
5736 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005737 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005738 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005739 delete [] MethodArgs;
5740
Anders Carlsson3d5829c2009-10-13 21:49:31 +00005741 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5742 Method))
5743 return true;
5744
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005745 // We may have default arguments. If so, we need to allocate more
5746 // slots in the call for them.
5747 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005748 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005749 else if (NumArgs > NumArgsInProto)
5750 NumArgsToCheck = NumArgsInProto;
5751
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005752 bool IsError = false;
5753
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005754 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005755 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005756 TheCall->setArg(0, Object);
5757
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005758
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005759 // Check the argument types.
5760 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005761 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005762 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005763 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00005764
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005765 // Pass the argument.
5766 QualType ProtoArgType = Proto->getArgType(i);
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005767 IsError |= PerformCopyInitialization(Arg, ProtoArgType, AA_Passing);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005768 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00005769 OwningExprResult DefArg
5770 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5771 if (DefArg.isInvalid()) {
5772 IsError = true;
5773 break;
5774 }
5775
5776 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005777 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005778
5779 TheCall->setArg(i + 1, Arg);
5780 }
5781
5782 // If this is a variadic call, handle args passed through "...".
5783 if (Proto->isVariadic()) {
5784 // Promote the arguments (C99 6.5.2.2p7).
5785 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5786 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005787 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005788 TheCall->setArg(i + 1, Arg);
5789 }
5790 }
5791
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005792 if (IsError) return true;
5793
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005794 if (CheckFunctionCall(Method, TheCall.get()))
5795 return true;
5796
Anders Carlsson1c83deb2009-08-16 03:53:54 +00005797 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005798}
5799
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005800/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00005801/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005802/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00005803Sema::OwningExprResult
5804Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5805 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005806 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00005807
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005808 // C++ [over.ref]p1:
5809 //
5810 // [...] An expression x->m is interpreted as (x.operator->())->m
5811 // for a class object x of type T if T::operator->() exists and if
5812 // the operator is selected as the best match function by the
5813 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005814 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5815 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005816 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00005817
Eli Friedman132e70b2009-11-18 01:28:03 +00005818 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5819 PDiag(diag::err_typecheck_incomplete_tag)
5820 << Base->getSourceRange()))
5821 return ExprError();
5822
John McCall27b18f82009-11-17 02:14:36 +00005823 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5824 LookupQualifiedName(R, BaseRecord->getDecl());
5825 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00005826
5827 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00005828 Oper != OperEnd; ++Oper) {
5829 NamedDecl *D = *Oper;
5830 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5831 if (isa<UsingShadowDecl>(D))
5832 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5833
5834 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
5835 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005836 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00005837 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005838
5839 // Perform overload resolution.
5840 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005841 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005842 case OR_Success:
5843 // Overload resolution succeeded; we'll build the call below.
5844 break;
5845
5846 case OR_No_Viable_Function:
5847 if (CandidateSet.empty())
5848 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00005849 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005850 else
5851 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00005852 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005853 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00005854 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005855
5856 case OR_Ambiguous:
5857 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005858 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005859 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005860 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005861
5862 case OR_Deleted:
5863 Diag(OpLoc, diag::err_ovl_deleted_oper)
5864 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005865 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005866 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005867 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005868 }
5869
5870 // Convert the object parameter.
5871 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005872 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005873 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005874
5875 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005876 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005877
5878 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005879 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5880 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005881 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005882
5883 QualType ResultTy = Method->getResultType().getNonReferenceType();
5884 ExprOwningPtr<CXXOperatorCallExpr>
5885 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5886 &Base, 1, ResultTy, OpLoc));
5887
5888 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5889 Method))
5890 return ExprError();
5891 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005892}
5893
Douglas Gregorcd695e52008-11-10 20:40:00 +00005894/// FixOverloadedFunctionReference - E is an expression that refers to
5895/// a C++ overloaded function (possibly with some parentheses and
5896/// perhaps a '&' around it). We have resolved the overloaded function
5897/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005898/// refer (possibly indirectly) to Fn. Returns the new expr.
5899Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005900 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00005901 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5902 if (SubExpr == PE->getSubExpr())
5903 return PE->Retain();
5904
5905 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
5906 }
5907
5908 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5909 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00005910 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00005911 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00005912 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00005913 if (SubExpr == ICE->getSubExpr())
5914 return ICE->Retain();
5915
5916 return new (Context) ImplicitCastExpr(ICE->getType(),
5917 ICE->getCastKind(),
5918 SubExpr,
5919 ICE->isLvalueCast());
5920 }
5921
5922 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005923 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005924 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005925 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5926 if (Method->isStatic()) {
5927 // Do nothing: static member functions aren't any different
5928 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00005929 } else {
John McCalle66edc12009-11-24 19:00:30 +00005930 // Fix the sub expression, which really has to be an
5931 // UnresolvedLookupExpr holding an overloaded member function
5932 // or template.
John McCalld14a8642009-11-21 08:51:07 +00005933 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5934 if (SubExpr == UnOp->getSubExpr())
5935 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00005936
John McCalld14a8642009-11-21 08:51:07 +00005937 assert(isa<DeclRefExpr>(SubExpr)
5938 && "fixed to something other than a decl ref");
5939 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
5940 && "fixed to a member ref with no nested name qualifier");
5941
5942 // We have taken the address of a pointer to member
5943 // function. Perform the computation here so that we get the
5944 // appropriate pointer to member type.
5945 QualType ClassType
5946 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5947 QualType MemPtrType
5948 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
5949
5950 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5951 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005952 }
5953 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00005954 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5955 if (SubExpr == UnOp->getSubExpr())
5956 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005957
Douglas Gregor51c538b2009-11-20 19:42:02 +00005958 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5959 Context.getPointerType(SubExpr->getType()),
5960 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00005961 }
John McCalld14a8642009-11-21 08:51:07 +00005962
5963 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00005964 // FIXME: avoid copy.
5965 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00005966 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00005967 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
5968 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00005969 }
5970
John McCalld14a8642009-11-21 08:51:07 +00005971 return DeclRefExpr::Create(Context,
5972 ULE->getQualifier(),
5973 ULE->getQualifierRange(),
5974 Fn,
5975 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00005976 Fn->getType(),
5977 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00005978 }
5979
John McCall10eae182009-11-30 22:42:35 +00005980 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00005981 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00005982 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5983 if (MemExpr->hasExplicitTemplateArgs()) {
5984 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5985 TemplateArgs = &TemplateArgsBuffer;
5986 }
John McCall6b51f282009-11-23 01:53:49 +00005987
John McCall2d74de92009-12-01 22:10:20 +00005988 Expr *Base;
5989
5990 // If we're filling in
5991 if (MemExpr->isImplicitAccess()) {
5992 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
5993 return DeclRefExpr::Create(Context,
5994 MemExpr->getQualifier(),
5995 MemExpr->getQualifierRange(),
5996 Fn,
5997 MemExpr->getMemberLoc(),
5998 Fn->getType(),
5999 TemplateArgs);
6000 } else
6001 Base = new (Context) CXXThisExpr(SourceLocation(),
6002 MemExpr->getBaseType());
6003 } else
6004 Base = MemExpr->getBase()->Retain();
6005
6006 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006007 MemExpr->isArrow(),
6008 MemExpr->getQualifier(),
6009 MemExpr->getQualifierRange(),
6010 Fn,
John McCall6b51f282009-11-23 01:53:49 +00006011 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006012 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006013 Fn->getType());
6014 }
6015
Douglas Gregor51c538b2009-11-20 19:42:02 +00006016 assert(false && "Invalid reference to overloaded function");
6017 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006018}
6019
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006020Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6021 FunctionDecl *Fn) {
6022 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6023}
6024
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006025} // end namespace clang