blob: 4565e94ebe8a23eb8514aeba94092d483aefd885 [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000020#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000022#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000024#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000025#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000026#include <algorithm>
Torok Edwindb714922009-08-24 13:25:12 +000027#include <cstdio>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000028
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000082 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000083 ICR_Conversion
84 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
91 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
92 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118 First = ICK_Identity;
119 Second = ICK_Identity;
120 Third = ICK_Identity;
121 Deprecated = false;
122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000126}
127
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132 ImplicitConversionRank Rank = ICR_Exact_Match;
133 if (GetConversionRank(First) > Rank)
134 Rank = GetConversionRank(First);
135 if (GetConversionRank(Second) > Rank)
136 Rank = GetConversionRank(Second);
137 if (GetConversionRank(Third) > Rank)
138 Rank = GetConversionRank(Third);
139 return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
148 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
149
150 // Note that FromType has not necessarily been transformed by the
151 // array-to-pointer or function-to-pointer implicit conversions, so
152 // check for their presence as well as checking whether FromType is
153 // a pointer.
154 if (ToType->isBooleanType() &&
Douglas Gregor033f56d2008-12-23 00:53:59 +0000155 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000156 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
157 return true;
158
159 return false;
160}
161
Douglas Gregor5c407d92008-10-23 00:40:37 +0000162/// isPointerConversionToVoidPointer - Determines whether this
163/// conversion is a conversion of a pointer to a void pointer. This is
164/// used as part of the ranking of standard conversion sequences (C++
165/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000166bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000167StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000168isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregor5c407d92008-10-23 00:40:37 +0000169 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
170 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
171
172 // Note that FromType has not necessarily been transformed by the
173 // array-to-pointer implicit conversion, so check for its presence
174 // and redo the conversion to get a pointer.
175 if (First == ICK_Array_To_Pointer)
176 FromType = Context.getArrayDecayedType(FromType);
177
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000178 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000179 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000180 return ToPtrType->getPointeeType()->isVoidType();
181
182 return false;
183}
184
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000185/// DebugPrint - Print this standard conversion sequence to standard
186/// error. Useful for debugging overloading issues.
187void StandardConversionSequence::DebugPrint() const {
188 bool PrintedSomething = false;
189 if (First != ICK_Identity) {
190 fprintf(stderr, "%s", GetImplicitConversionName(First));
191 PrintedSomething = true;
192 }
193
194 if (Second != ICK_Identity) {
195 if (PrintedSomething) {
196 fprintf(stderr, " -> ");
197 }
198 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor2fe98832008-11-03 19:09:14 +0000199
200 if (CopyConstructor) {
201 fprintf(stderr, " (by copy constructor)");
202 } else if (DirectBinding) {
203 fprintf(stderr, " (direct reference binding)");
204 } else if (ReferenceBinding) {
205 fprintf(stderr, " (reference binding)");
206 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000207 PrintedSomething = true;
208 }
209
210 if (Third != ICK_Identity) {
211 if (PrintedSomething) {
212 fprintf(stderr, " -> ");
213 }
214 fprintf(stderr, "%s", GetImplicitConversionName(Third));
215 PrintedSomething = true;
216 }
217
218 if (!PrintedSomething) {
219 fprintf(stderr, "No conversions required");
220 }
221}
222
223/// DebugPrint - Print this user-defined conversion sequence to standard
224/// error. Useful for debugging overloading issues.
225void UserDefinedConversionSequence::DebugPrint() const {
226 if (Before.First || Before.Second || Before.Third) {
227 Before.DebugPrint();
228 fprintf(stderr, " -> ");
229 }
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000230 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000231 if (After.First || After.Second || After.Third) {
232 fprintf(stderr, " -> ");
233 After.DebugPrint();
234 }
235}
236
237/// DebugPrint - Print this implicit conversion sequence to standard
238/// error. Useful for debugging overloading issues.
239void ImplicitConversionSequence::DebugPrint() const {
240 switch (ConversionKind) {
241 case StandardConversion:
242 fprintf(stderr, "Standard conversion: ");
243 Standard.DebugPrint();
244 break;
245 case UserDefinedConversion:
246 fprintf(stderr, "User-defined conversion: ");
247 UserDefined.DebugPrint();
248 break;
249 case EllipsisConversion:
250 fprintf(stderr, "Ellipsis conversion");
251 break;
252 case BadConversion:
253 fprintf(stderr, "Bad conversion");
254 break;
255 }
256
257 fprintf(stderr, "\n");
258}
259
260// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000261// overload of the declarations in Old. This routine returns false if
262// New and Old cannot be overloaded, e.g., if New has the same
263// signature as some function in Old (C++ 1.3.10) or if the Old
264// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000265// it does return false, MatchedDecl will point to the decl that New
266// cannot be overloaded with. This decl may be a UsingShadowDecl on
267// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000268//
269// Example: Given the following input:
270//
271// void f(int, float); // #1
272// void f(int, int); // #2
273// int f(int, int); // #3
274//
275// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000276// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000277//
John McCall3d988d92009-12-02 08:47:38 +0000278// When we process #2, Old contains only the FunctionDecl for #1. By
279// comparing the parameter types, we see that #1 and #2 are overloaded
280// (since they have different signatures), so this routine returns
281// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000282//
John McCall3d988d92009-12-02 08:47:38 +0000283// When we process #3, Old is an overload set containing #1 and #2. We
284// compare the signatures of #3 to #1 (they're overloaded, so we do
285// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
286// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000287// signature), IsOverload returns false and MatchedDecl will be set to
288// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000289Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000290Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
291 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000292 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000293 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000294 NamedDecl *OldD = (*I)->getUnderlyingDecl();
295 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000296 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000297 Match = *I;
298 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000299 }
John McCall3d988d92009-12-02 08:47:38 +0000300 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000301 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000302 Match = *I;
303 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000304 }
John McCall84d87672009-12-10 09:41:52 +0000305 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
306 // We can overload with these, which can show up when doing
307 // redeclaration checks for UsingDecls.
308 assert(Old.getLookupKind() == LookupUsingDeclName);
309 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
310 // Optimistically assume that an unresolved using decl will
311 // overload; if it doesn't, we'll have to diagnose during
312 // template instantiation.
313 } else {
John McCall1f82f242009-11-18 22:49:29 +0000314 // (C++ 13p1):
315 // Only function declarations can be overloaded; object and type
316 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000317 Match = *I;
318 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000319 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000320 }
John McCall1f82f242009-11-18 22:49:29 +0000321
John McCalldaa3d6b2009-12-09 03:35:25 +0000322 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000323}
324
325bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
326 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
327 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
328
329 // C++ [temp.fct]p2:
330 // A function template can be overloaded with other function templates
331 // and with normal (non-template) functions.
332 if ((OldTemplate == 0) != (NewTemplate == 0))
333 return true;
334
335 // Is the function New an overload of the function Old?
336 QualType OldQType = Context.getCanonicalType(Old->getType());
337 QualType NewQType = Context.getCanonicalType(New->getType());
338
339 // Compare the signatures (C++ 1.3.10) of the two functions to
340 // determine whether they are overloads. If we find any mismatch
341 // in the signature, they are overloads.
342
343 // If either of these functions is a K&R-style function (no
344 // prototype), then we consider them to have matching signatures.
345 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
346 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
347 return false;
348
349 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
350 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
351
352 // The signature of a function includes the types of its
353 // parameters (C++ 1.3.10), which includes the presence or absence
354 // of the ellipsis; see C++ DR 357).
355 if (OldQType != NewQType &&
356 (OldType->getNumArgs() != NewType->getNumArgs() ||
357 OldType->isVariadic() != NewType->isVariadic() ||
358 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
359 NewType->arg_type_begin())))
360 return true;
361
362 // C++ [temp.over.link]p4:
363 // The signature of a function template consists of its function
364 // signature, its return type and its template parameter list. The names
365 // of the template parameters are significant only for establishing the
366 // relationship between the template parameters and the rest of the
367 // signature.
368 //
369 // We check the return type and template parameter lists for function
370 // templates first; the remaining checks follow.
371 if (NewTemplate &&
372 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
373 OldTemplate->getTemplateParameters(),
374 false, TPL_TemplateMatch) ||
375 OldType->getResultType() != NewType->getResultType()))
376 return true;
377
378 // If the function is a class member, its signature includes the
379 // cv-qualifiers (if any) on the function itself.
380 //
381 // As part of this, also check whether one of the member functions
382 // is static, in which case they are not overloads (C++
383 // 13.1p2). While not part of the definition of the signature,
384 // this check is important to determine whether these functions
385 // can be overloaded.
386 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
387 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
388 if (OldMethod && NewMethod &&
389 !OldMethod->isStatic() && !NewMethod->isStatic() &&
390 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
391 return true;
392
393 // The signatures match; this is not an overload.
394 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000395}
396
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000397/// TryImplicitConversion - Attempt to perform an implicit conversion
398/// from the given expression (Expr) to the given type (ToType). This
399/// function returns an implicit conversion sequence that can be used
400/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000401///
402/// void f(float f);
403/// void g(int i) { f(i); }
404///
405/// this routine would produce an implicit conversion sequence to
406/// describe the initialization of f from i, which will be a standard
407/// conversion sequence containing an lvalue-to-rvalue conversion (C++
408/// 4.1) followed by a floating-integral conversion (C++ 4.9).
409//
410/// Note that this routine only determines how the conversion can be
411/// performed; it does not actually perform the conversion. As such,
412/// it will not produce any diagnostics if no conversion is available,
413/// but will instead return an implicit conversion sequence of kind
414/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000415///
416/// If @p SuppressUserConversions, then user-defined conversions are
417/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000418/// If @p AllowExplicit, then explicit user-defined conversions are
419/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000420/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
421/// no matter its actual lvalueness.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000422/// If @p UserCast, the implicit conversion is being done for a user-specified
423/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000424ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000425Sema::TryImplicitConversion(Expr* From, QualType ToType,
426 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000427 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000428 bool InOverloadResolution,
429 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000430 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000431 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000432 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000433 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000434 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000435 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000436 (UserDefResult = IsUserDefinedConversion(From, ToType,
437 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000438 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000439 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000440 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000441 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000442 // C++ [over.ics.user]p4:
443 // A conversion of an expression of class type to the same class
444 // type is given Exact Match rank, and a conversion of an
445 // expression of class type to a base class of that type is
446 // given Conversion rank, in spite of the fact that a copy
447 // constructor (i.e., a user-defined conversion function) is
448 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000449 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000450 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000451 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000452 = Context.getCanonicalType(From->getType().getUnqualifiedType());
453 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
454 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000455 // Turn this into a "standard" conversion sequence, so that it
456 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000457 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
458 ICS.Standard.setAsIdentityConversion();
459 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
460 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000461 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000462 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000463 ICS.Standard.Second = ICK_Derived_To_Base;
464 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000465 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000466
467 // C++ [over.best.ics]p4:
468 // However, when considering the argument of a user-defined
469 // conversion function that is a candidate by 13.3.1.3 when
470 // invoked for the copying of the temporary in the second step
471 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
472 // 13.3.1.6 in all cases, only standard conversion sequences and
473 // ellipsis conversion sequences are allowed.
474 if (SuppressUserConversions &&
475 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
476 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000477 } else {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000478 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000479 if (UserDefResult == OR_Ambiguous) {
480 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
481 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian574de2c2009-10-12 17:51:19 +0000482 if (Cand->Viable)
483 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000484 }
485 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000486
487 return ICS;
488}
489
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000490/// \brief Determine whether the conversion from FromType to ToType is a valid
491/// conversion that strips "noreturn" off the nested function type.
492static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
493 QualType ToType, QualType &ResultTy) {
494 if (Context.hasSameUnqualifiedType(FromType, ToType))
495 return false;
496
497 // Strip the noreturn off the type we're converting from; noreturn can
498 // safely be removed.
499 FromType = Context.getNoReturnType(FromType, false);
500 if (!Context.hasSameUnqualifiedType(FromType, ToType))
501 return false;
502
503 ResultTy = FromType;
504 return true;
505}
506
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000507/// IsStandardConversion - Determines whether there is a standard
508/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
509/// expression From to the type ToType. Standard conversion sequences
510/// only consider non-class types; for conversions that involve class
511/// types, use TryImplicitConversion. If a conversion exists, SCS will
512/// contain the standard conversion sequence required to perform this
513/// conversion and this routine will return true. Otherwise, this
514/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000515bool
516Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000517 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000518 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000519 QualType FromType = From->getType();
520
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000521 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000522 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000523 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000524 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000525 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000526 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000527
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000528 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000529 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000530 if (FromType->isRecordType() || ToType->isRecordType()) {
531 if (getLangOptions().CPlusPlus)
532 return false;
533
Mike Stump11289f42009-09-09 15:08:12 +0000534 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000535 }
536
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000537 // The first conversion can be an lvalue-to-rvalue conversion,
538 // array-to-pointer conversion, or function-to-pointer conversion
539 // (C++ 4p1).
540
Mike Stump11289f42009-09-09 15:08:12 +0000541 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542 // An lvalue (3.10) of a non-function, non-array type T can be
543 // converted to an rvalue.
544 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000545 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000546 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000547 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000548 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000549
550 // If T is a non-class type, the type of the rvalue is the
551 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000552 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
553 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000554 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000555 } else if (FromType->isArrayType()) {
556 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000557 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000558
559 // An lvalue or rvalue of type "array of N T" or "array of unknown
560 // bound of T" can be converted to an rvalue of type "pointer to
561 // T" (C++ 4.2p1).
562 FromType = Context.getArrayDecayedType(FromType);
563
564 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
565 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000566 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000567
568 // For the purpose of ranking in overload resolution
569 // (13.3.3.1.1), this conversion is considered an
570 // array-to-pointer conversion followed by a qualification
571 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000572 SCS.Second = ICK_Identity;
573 SCS.Third = ICK_Qualification;
574 SCS.ToTypePtr = ToType.getAsOpaquePtr();
575 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000576 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000577 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
578 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000579 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000580
581 // An lvalue of function type T can be converted to an rvalue of
582 // type "pointer to T." The result is a pointer to the
583 // function. (C++ 4.3p1).
584 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000585 } else if (FunctionDecl *Fn
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000586 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000587 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000588 SCS.First = ICK_Function_To_Pointer;
589
590 // We were able to resolve the address of the overloaded function,
591 // so we can convert to the type of that function.
592 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000593 if (ToType->isLValueReferenceType())
594 FromType = Context.getLValueReferenceType(FromType);
595 else if (ToType->isRValueReferenceType())
596 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000597 else if (ToType->isMemberPointerType()) {
598 // Resolve address only succeeds if both sides are member pointers,
599 // but it doesn't have to be the same class. See DR 247.
600 // Note that this means that the type of &Derived::fn can be
601 // Ret (Base::*)(Args) if the fn overload actually found is from the
602 // base class, even if it was brought into the derived class via a
603 // using declaration. The standard isn't clear on this issue at all.
604 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
605 FromType = Context.getMemberPointerType(FromType,
606 Context.getTypeDeclType(M->getParent()).getTypePtr());
607 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000608 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000609 } else {
610 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000611 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000612 }
613
614 // The second conversion can be an integral promotion, floating
615 // point promotion, integral conversion, floating point conversion,
616 // floating-integral conversion, pointer conversion,
617 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000618 // For overloading in C, this can also be a "compatible-type"
619 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000620 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000621 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000622 // The unqualified versions of the types are the same: there's no
623 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000624 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000625 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000626 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000627 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000628 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000629 } else if (IsFloatingPointPromotion(FromType, ToType)) {
630 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000631 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000632 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000633 } else if (IsComplexPromotion(FromType, ToType)) {
634 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000635 SCS.Second = ICK_Complex_Promotion;
636 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000637 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000638 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000639 // Integral conversions (C++ 4.7).
640 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000641 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000642 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000643 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
644 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000645 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000646 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000647 } else if (FromType->isComplexType() && ToType->isComplexType()) {
648 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000649 SCS.Second = ICK_Complex_Conversion;
650 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000651 } else if ((FromType->isFloatingType() &&
652 ToType->isIntegralType() && (!ToType->isBooleanType() &&
653 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000654 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000655 ToType->isFloatingType())) {
656 // Floating-integral conversions (C++ 4.9).
657 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000658 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000659 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000660 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
661 (ToType->isComplexType() && FromType->isArithmeticType())) {
662 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000663 SCS.Second = ICK_Complex_Real;
664 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000665 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
666 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000667 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000668 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000669 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000670 } else if (IsMemberPointerConversion(From, FromType, ToType,
671 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000672 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000673 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000674 } else if (ToType->isBooleanType() &&
675 (FromType->isArithmeticType() ||
676 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000677 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000678 FromType->isBlockPointerType() ||
679 FromType->isMemberPointerType() ||
680 FromType->isNullPtrType())) {
681 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000682 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000683 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000684 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000685 Context.typesAreCompatible(ToType, FromType)) {
686 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000687 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000688 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
689 // Treat a conversion that strips "noreturn" as an identity conversion.
690 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000691 } else {
692 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000693 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000694 }
695
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000696 QualType CanonFrom;
697 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000698 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000699 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000700 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000701 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000702 CanonFrom = Context.getCanonicalType(FromType);
703 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000704 } else {
705 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000706 SCS.Third = ICK_Identity;
707
Mike Stump11289f42009-09-09 15:08:12 +0000708 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000709 // [...] Any difference in top-level cv-qualification is
710 // subsumed by the initialization itself and does not constitute
711 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000712 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000713 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000714 if (CanonFrom.getLocalUnqualifiedType()
715 == CanonTo.getLocalUnqualifiedType() &&
716 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000717 FromType = ToType;
718 CanonFrom = CanonTo;
719 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000720 }
721
722 // If we have not converted the argument type to the parameter type,
723 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000724 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000725 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000726
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000727 SCS.ToTypePtr = FromType.getAsOpaquePtr();
728 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000729}
730
731/// IsIntegralPromotion - Determines whether the conversion from the
732/// expression From (whose potentially-adjusted type is FromType) to
733/// ToType is an integral promotion (C++ 4.5). If so, returns true and
734/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000735bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000736 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000737 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000738 if (!To) {
739 return false;
740 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000741
742 // An rvalue of type char, signed char, unsigned char, short int, or
743 // unsigned short int can be converted to an rvalue of type int if
744 // int can represent all the values of the source type; otherwise,
745 // the source rvalue can be converted to an rvalue of type unsigned
746 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000747 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000748 if (// We can promote any signed, promotable integer type to an int
749 (FromType->isSignedIntegerType() ||
750 // We can promote any unsigned integer type whose size is
751 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000752 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000753 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000754 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000755 }
756
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000757 return To->getKind() == BuiltinType::UInt;
758 }
759
760 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
761 // can be converted to an rvalue of the first of the following types
762 // that can represent all the values of its underlying type: int,
763 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000764
765 // We pre-calculate the promotion type for enum types.
766 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
767 if (ToType->isIntegerType())
768 return Context.hasSameUnqualifiedType(ToType,
769 FromEnumType->getDecl()->getPromotionType());
770
771 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000772 // Determine whether the type we're converting from is signed or
773 // unsigned.
774 bool FromIsSigned;
775 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000776
777 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
778 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000779
780 // The types we'll try to promote to, in the appropriate
781 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000782 QualType PromoteTypes[6] = {
783 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000784 Context.LongTy, Context.UnsignedLongTy ,
785 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000786 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000787 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000788 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
789 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000790 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000791 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
792 // We found the type that we can promote to. If this is the
793 // type we wanted, we have a promotion. Otherwise, no
794 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000795 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000796 }
797 }
798 }
799
800 // An rvalue for an integral bit-field (9.6) can be converted to an
801 // rvalue of type int if int can represent all the values of the
802 // bit-field; otherwise, it can be converted to unsigned int if
803 // unsigned int can represent all the values of the bit-field. If
804 // the bit-field is larger yet, no integral promotion applies to
805 // it. If the bit-field has an enumerated type, it is treated as any
806 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000807 // FIXME: We should delay checking of bit-fields until we actually perform the
808 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000809 using llvm::APSInt;
810 if (From)
811 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000812 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000813 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
814 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
815 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
816 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000817
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000818 // Are we promoting to an int from a bitfield that fits in an int?
819 if (BitWidth < ToSize ||
820 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
821 return To->getKind() == BuiltinType::Int;
822 }
Mike Stump11289f42009-09-09 15:08:12 +0000823
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000824 // Are we promoting to an unsigned int from an unsigned bitfield
825 // that fits into an unsigned int?
826 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
827 return To->getKind() == BuiltinType::UInt;
828 }
Mike Stump11289f42009-09-09 15:08:12 +0000829
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000830 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000831 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000832 }
Mike Stump11289f42009-09-09 15:08:12 +0000833
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000834 // An rvalue of type bool can be converted to an rvalue of type int,
835 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000836 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000837 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000838 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000839
840 return false;
841}
842
843/// IsFloatingPointPromotion - Determines whether the conversion from
844/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
845/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000846bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000847 /// An rvalue of type float can be converted to an rvalue of type
848 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000849 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
850 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000851 if (FromBuiltin->getKind() == BuiltinType::Float &&
852 ToBuiltin->getKind() == BuiltinType::Double)
853 return true;
854
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000855 // C99 6.3.1.5p1:
856 // When a float is promoted to double or long double, or a
857 // double is promoted to long double [...].
858 if (!getLangOptions().CPlusPlus &&
859 (FromBuiltin->getKind() == BuiltinType::Float ||
860 FromBuiltin->getKind() == BuiltinType::Double) &&
861 (ToBuiltin->getKind() == BuiltinType::LongDouble))
862 return true;
863 }
864
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000865 return false;
866}
867
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000868/// \brief Determine if a conversion is a complex promotion.
869///
870/// A complex promotion is defined as a complex -> complex conversion
871/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000872/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000873bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000874 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000875 if (!FromComplex)
876 return false;
877
John McCall9dd450b2009-09-21 23:43:11 +0000878 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000879 if (!ToComplex)
880 return false;
881
882 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000883 ToComplex->getElementType()) ||
884 IsIntegralPromotion(0, FromComplex->getElementType(),
885 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000886}
887
Douglas Gregor237f96c2008-11-26 23:31:11 +0000888/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
889/// the pointer type FromPtr to a pointer to type ToPointee, with the
890/// same type qualifiers as FromPtr has on its pointee type. ToType,
891/// if non-empty, will be a pointer to ToType that may or may not have
892/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000893static QualType
894BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000895 QualType ToPointee, QualType ToType,
896 ASTContext &Context) {
897 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
898 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000899 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000900
901 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000902 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000903 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000904 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000905 return ToType;
906
907 // Build a pointer to ToPointee. It has the right qualifiers
908 // already.
909 return Context.getPointerType(ToPointee);
910 }
911
912 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000913 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000914 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
915 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000916}
917
Fariborz Jahanian01cbe442009-12-16 23:13:33 +0000918/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
919/// the FromType, which is an objective-c pointer, to ToType, which may or may
920/// not have the right set of qualifiers.
921static QualType
922BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
923 QualType ToType,
924 ASTContext &Context) {
925 QualType CanonFromType = Context.getCanonicalType(FromType);
926 QualType CanonToType = Context.getCanonicalType(ToType);
927 Qualifiers Quals = CanonFromType.getQualifiers();
928
929 // Exact qualifier match -> return the pointer type we're converting to.
930 if (CanonToType.getLocalQualifiers() == Quals)
931 return ToType;
932
933 // Just build a canonical type that has the right qualifiers.
934 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
935}
936
Mike Stump11289f42009-09-09 15:08:12 +0000937static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000938 bool InOverloadResolution,
939 ASTContext &Context) {
940 // Handle value-dependent integral null pointer constants correctly.
941 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
942 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
943 Expr->getType()->isIntegralType())
944 return !InOverloadResolution;
945
Douglas Gregor56751b52009-09-25 04:25:58 +0000946 return Expr->isNullPointerConstant(Context,
947 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
948 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000949}
Mike Stump11289f42009-09-09 15:08:12 +0000950
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000951/// IsPointerConversion - Determines whether the conversion of the
952/// expression From, which has the (possibly adjusted) type FromType,
953/// can be converted to the type ToType via a pointer conversion (C++
954/// 4.10). If so, returns true and places the converted type (that
955/// might differ from ToType in its cv-qualifiers at some level) into
956/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000957///
Douglas Gregora29dc052008-11-27 01:19:21 +0000958/// This routine also supports conversions to and from block pointers
959/// and conversions with Objective-C's 'id', 'id<protocols...>', and
960/// pointers to interfaces. FIXME: Once we've determined the
961/// appropriate overloading rules for Objective-C, we may want to
962/// split the Objective-C checks into a different routine; however,
963/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000964/// conversions, so for now they live here. IncompatibleObjC will be
965/// set if the conversion is an allowed Objective-C conversion that
966/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000967bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000968 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000969 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000970 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000971 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000972 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
973 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000974
Mike Stump11289f42009-09-09 15:08:12 +0000975 // Conversion from a null pointer constant to any Objective-C pointer type.
976 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000977 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000978 ConvertedType = ToType;
979 return true;
980 }
981
Douglas Gregor231d1c62008-11-27 00:15:41 +0000982 // Blocks: Block pointers can be converted to void*.
983 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000984 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000985 ConvertedType = ToType;
986 return true;
987 }
988 // Blocks: A null pointer constant can be converted to a block
989 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000990 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000991 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000992 ConvertedType = ToType;
993 return true;
994 }
995
Sebastian Redl576fd422009-05-10 18:38:11 +0000996 // If the left-hand-side is nullptr_t, the right side can be a null
997 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000998 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000999 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001000 ConvertedType = ToType;
1001 return true;
1002 }
1003
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001004 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001005 if (!ToTypePtr)
1006 return false;
1007
1008 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001009 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001010 ConvertedType = ToType;
1011 return true;
1012 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001013
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001014 // Beyond this point, both types need to be pointers
1015 // , including objective-c pointers.
1016 QualType ToPointeeType = ToTypePtr->getPointeeType();
1017 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1018 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1019 ToType, Context);
1020 return true;
1021
1022 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001023 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001024 if (!FromTypePtr)
1025 return false;
1026
1027 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001028
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001029 // An rvalue of type "pointer to cv T," where T is an object type,
1030 // can be converted to an rvalue of type "pointer to cv void" (C++
1031 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001032 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001033 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001034 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001035 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001036 return true;
1037 }
1038
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001039 // When we're overloading in C, we allow a special kind of pointer
1040 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001041 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001042 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001043 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001044 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001045 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001046 return true;
1047 }
1048
Douglas Gregor5c407d92008-10-23 00:40:37 +00001049 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001050 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001051 // An rvalue of type "pointer to cv D," where D is a class type,
1052 // can be converted to an rvalue of type "pointer to cv B," where
1053 // B is a base class (clause 10) of D. If B is an inaccessible
1054 // (clause 11) or ambiguous (10.2) base class of D, a program that
1055 // necessitates this conversion is ill-formed. The result of the
1056 // conversion is a pointer to the base class sub-object of the
1057 // derived class object. The null pointer value is converted to
1058 // the null pointer value of the destination type.
1059 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001060 // Note that we do not check for ambiguity or inaccessibility
1061 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001062 if (getLangOptions().CPlusPlus &&
1063 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001064 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001065 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001066 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001067 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001068 ToType, Context);
1069 return true;
1070 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001071
Douglas Gregora119f102008-12-19 19:13:09 +00001072 return false;
1073}
1074
1075/// isObjCPointerConversion - Determines whether this is an
1076/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1077/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001078bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001079 QualType& ConvertedType,
1080 bool &IncompatibleObjC) {
1081 if (!getLangOptions().ObjC1)
1082 return false;
1083
Steve Naroff7cae42b2009-07-10 23:34:53 +00001084 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001085 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001086 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001087 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001088
Steve Naroff7cae42b2009-07-10 23:34:53 +00001089 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001090 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001091 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001092 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001093 ConvertedType = ToType;
1094 return true;
1095 }
1096 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001097 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001098 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001099 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001100 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001101 ConvertedType = ToType;
1102 return true;
1103 }
1104 // Objective C++: We're able to convert from a pointer to an
1105 // interface to a pointer to a different interface.
1106 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1107 ConvertedType = ToType;
1108 return true;
1109 }
1110
1111 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1112 // Okay: this is some kind of implicit downcast of Objective-C
1113 // interfaces, which is permitted. However, we're going to
1114 // complain about it.
1115 IncompatibleObjC = true;
1116 ConvertedType = FromType;
1117 return true;
1118 }
Mike Stump11289f42009-09-09 15:08:12 +00001119 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001120 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001121 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001122 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001123 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001124 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001125 ToPointeeType = ToBlockPtr->getPointeeType();
1126 else
Douglas Gregora119f102008-12-19 19:13:09 +00001127 return false;
1128
Douglas Gregor033f56d2008-12-23 00:53:59 +00001129 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001130 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001131 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001132 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001133 FromPointeeType = FromBlockPtr->getPointeeType();
1134 else
Douglas Gregora119f102008-12-19 19:13:09 +00001135 return false;
1136
Douglas Gregora119f102008-12-19 19:13:09 +00001137 // If we have pointers to pointers, recursively check whether this
1138 // is an Objective-C conversion.
1139 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1140 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1141 IncompatibleObjC)) {
1142 // We always complain about this conversion.
1143 IncompatibleObjC = true;
1144 ConvertedType = ToType;
1145 return true;
1146 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001147 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001148 // differences in the argument and result types are in Objective-C
1149 // pointer conversions. If so, we permit the conversion (but
1150 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001151 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001152 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001153 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001154 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001155 if (FromFunctionType && ToFunctionType) {
1156 // If the function types are exactly the same, this isn't an
1157 // Objective-C pointer conversion.
1158 if (Context.getCanonicalType(FromPointeeType)
1159 == Context.getCanonicalType(ToPointeeType))
1160 return false;
1161
1162 // Perform the quick checks that will tell us whether these
1163 // function types are obviously different.
1164 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1165 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1166 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1167 return false;
1168
1169 bool HasObjCConversion = false;
1170 if (Context.getCanonicalType(FromFunctionType->getResultType())
1171 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1172 // Okay, the types match exactly. Nothing to do.
1173 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1174 ToFunctionType->getResultType(),
1175 ConvertedType, IncompatibleObjC)) {
1176 // Okay, we have an Objective-C pointer conversion.
1177 HasObjCConversion = true;
1178 } else {
1179 // Function types are too different. Abort.
1180 return false;
1181 }
Mike Stump11289f42009-09-09 15:08:12 +00001182
Douglas Gregora119f102008-12-19 19:13:09 +00001183 // Check argument types.
1184 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1185 ArgIdx != NumArgs; ++ArgIdx) {
1186 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1187 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1188 if (Context.getCanonicalType(FromArgType)
1189 == Context.getCanonicalType(ToArgType)) {
1190 // Okay, the types match exactly. Nothing to do.
1191 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1192 ConvertedType, IncompatibleObjC)) {
1193 // Okay, we have an Objective-C pointer conversion.
1194 HasObjCConversion = true;
1195 } else {
1196 // Argument types are too different. Abort.
1197 return false;
1198 }
1199 }
1200
1201 if (HasObjCConversion) {
1202 // We had an Objective-C conversion. Allow this pointer
1203 // conversion, but complain about it.
1204 ConvertedType = ToType;
1205 IncompatibleObjC = true;
1206 return true;
1207 }
1208 }
1209
Sebastian Redl72b597d2009-01-25 19:43:20 +00001210 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001211}
1212
Douglas Gregor39c16d42008-10-24 04:54:22 +00001213/// CheckPointerConversion - Check the pointer conversion from the
1214/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001215/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001216/// conversions for which IsPointerConversion has already returned
1217/// true. It returns true and produces a diagnostic if there was an
1218/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001219bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001220 CastExpr::CastKind &Kind,
1221 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001222 QualType FromType = From->getType();
1223
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001224 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1225 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001226 QualType FromPointeeType = FromPtrType->getPointeeType(),
1227 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001228
Douglas Gregor39c16d42008-10-24 04:54:22 +00001229 if (FromPointeeType->isRecordType() &&
1230 ToPointeeType->isRecordType()) {
1231 // We must have a derived-to-base conversion. Check an
1232 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001233 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1234 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001235 From->getSourceRange(),
1236 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001237 return true;
1238
1239 // The conversion was successful.
1240 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001241 }
1242 }
Mike Stump11289f42009-09-09 15:08:12 +00001243 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001244 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001245 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001246 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001247 // Objective-C++ conversions are always okay.
1248 // FIXME: We should have a different class of conversions for the
1249 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001250 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001251 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001252
Steve Naroff7cae42b2009-07-10 23:34:53 +00001253 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001254 return false;
1255}
1256
Sebastian Redl72b597d2009-01-25 19:43:20 +00001257/// IsMemberPointerConversion - Determines whether the conversion of the
1258/// expression From, which has the (possibly adjusted) type FromType, can be
1259/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1260/// If so, returns true and places the converted type (that might differ from
1261/// ToType in its cv-qualifiers at some level) into ConvertedType.
1262bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001263 QualType ToType,
1264 bool InOverloadResolution,
1265 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001266 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001267 if (!ToTypePtr)
1268 return false;
1269
1270 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001271 if (From->isNullPointerConstant(Context,
1272 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1273 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001274 ConvertedType = ToType;
1275 return true;
1276 }
1277
1278 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001279 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001280 if (!FromTypePtr)
1281 return false;
1282
1283 // A pointer to member of B can be converted to a pointer to member of D,
1284 // where D is derived from B (C++ 4.11p2).
1285 QualType FromClass(FromTypePtr->getClass(), 0);
1286 QualType ToClass(ToTypePtr->getClass(), 0);
1287 // FIXME: What happens when these are dependent? Is this function even called?
1288
1289 if (IsDerivedFrom(ToClass, FromClass)) {
1290 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1291 ToClass.getTypePtr());
1292 return true;
1293 }
1294
1295 return false;
1296}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001297
Sebastian Redl72b597d2009-01-25 19:43:20 +00001298/// CheckMemberPointerConversion - Check the member pointer conversion from the
1299/// expression From to the type ToType. This routine checks for ambiguous or
1300/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1301/// for which IsMemberPointerConversion has already returned true. It returns
1302/// true and produces a diagnostic if there was an error, or returns false
1303/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001304bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001305 CastExpr::CastKind &Kind,
1306 bool IgnoreBaseAccess) {
1307 (void)IgnoreBaseAccess;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001308 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001309 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001310 if (!FromPtrType) {
1311 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001312 assert(From->isNullPointerConstant(Context,
1313 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001314 "Expr must be null pointer constant!");
1315 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001316 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001317 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001318
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001319 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001320 assert(ToPtrType && "No member pointer cast has a target type "
1321 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001322
Sebastian Redled8f2002009-01-28 18:33:18 +00001323 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1324 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001325
Sebastian Redled8f2002009-01-28 18:33:18 +00001326 // FIXME: What about dependent types?
1327 assert(FromClass->isRecordType() && "Pointer into non-class.");
1328 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001329
Douglas Gregor36d1b142009-10-06 17:59:45 +00001330 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1331 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001332 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1333 assert(DerivationOkay &&
1334 "Should not have been called if derivation isn't OK.");
1335 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001336
Sebastian Redled8f2002009-01-28 18:33:18 +00001337 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1338 getUnqualifiedType())) {
1339 // Derivation is ambiguous. Redo the check to find the exact paths.
1340 Paths.clear();
1341 Paths.setRecordingPaths(true);
1342 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1343 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1344 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001345
Sebastian Redled8f2002009-01-28 18:33:18 +00001346 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1347 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1348 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1349 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001350 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001351
Douglas Gregor89ee6822009-02-28 01:32:25 +00001352 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001353 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1354 << FromClass << ToClass << QualType(VBase, 0)
1355 << From->getSourceRange();
1356 return true;
1357 }
1358
Anders Carlssond7923c62009-08-22 23:33:40 +00001359 // Must be a base to derived member conversion.
1360 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001361 return false;
1362}
1363
Douglas Gregor9a657932008-10-21 23:43:52 +00001364/// IsQualificationConversion - Determines whether the conversion from
1365/// an rvalue of type FromType to ToType is a qualification conversion
1366/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001367bool
1368Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001369 FromType = Context.getCanonicalType(FromType);
1370 ToType = Context.getCanonicalType(ToType);
1371
1372 // If FromType and ToType are the same type, this is not a
1373 // qualification conversion.
1374 if (FromType == ToType)
1375 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001376
Douglas Gregor9a657932008-10-21 23:43:52 +00001377 // (C++ 4.4p4):
1378 // A conversion can add cv-qualifiers at levels other than the first
1379 // in multi-level pointers, subject to the following rules: [...]
1380 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001381 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001382 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001383 // Within each iteration of the loop, we check the qualifiers to
1384 // determine if this still looks like a qualification
1385 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001386 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001387 // until there are no more pointers or pointers-to-members left to
1388 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001389 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001390
1391 // -- for every j > 0, if const is in cv 1,j then const is in cv
1392 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001393 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001394 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001395
Douglas Gregor9a657932008-10-21 23:43:52 +00001396 // -- if the cv 1,j and cv 2,j are different, then const is in
1397 // every cv for 0 < k < j.
1398 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001399 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001400 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001401
Douglas Gregor9a657932008-10-21 23:43:52 +00001402 // Keep track of whether all prior cv-qualifiers in the "to" type
1403 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001404 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001405 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001406 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001407
1408 // We are left with FromType and ToType being the pointee types
1409 // after unwrapping the original FromType and ToType the same number
1410 // of types. If we unwrapped any pointers, and if FromType and
1411 // ToType have the same unqualified type (since we checked
1412 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001413 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001414}
1415
Douglas Gregor576e98c2009-01-30 23:27:23 +00001416/// Determines whether there is a user-defined conversion sequence
1417/// (C++ [over.ics.user]) that converts expression From to the type
1418/// ToType. If such a conversion exists, User will contain the
1419/// user-defined conversion sequence that performs such a conversion
1420/// and this routine will return true. Otherwise, this routine returns
1421/// false and User is unspecified.
1422///
1423/// \param AllowConversionFunctions true if the conversion should
1424/// consider conversion functions at all. If false, only constructors
1425/// will be considered.
1426///
1427/// \param AllowExplicit true if the conversion should consider C++0x
1428/// "explicit" conversion functions as well as non-explicit conversion
1429/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001430///
1431/// \param ForceRValue true if the expression should be treated as an rvalue
1432/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001433/// \param UserCast true if looking for user defined conversion for a static
1434/// cast.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001435OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1436 UserDefinedConversionSequence& User,
1437 OverloadCandidateSet& CandidateSet,
1438 bool AllowConversionFunctions,
1439 bool AllowExplicit,
1440 bool ForceRValue,
1441 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001442 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001443 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1444 // We're not going to find any constructors.
1445 } else if (CXXRecordDecl *ToRecordDecl
1446 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001447 // C++ [over.match.ctor]p1:
1448 // When objects of class type are direct-initialized (8.5), or
1449 // copy-initialized from an expression of the same or a
1450 // derived class type (8.5), overload resolution selects the
1451 // constructor. [...] For copy-initialization, the candidate
1452 // functions are all the converting constructors (12.3.1) of
1453 // that class. The argument list is the expression-list within
1454 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001455 bool SuppressUserConversions = !UserCast;
1456 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1457 IsDerivedFrom(From->getType(), ToType)) {
1458 SuppressUserConversions = false;
1459 AllowConversionFunctions = false;
1460 }
1461
Mike Stump11289f42009-09-09 15:08:12 +00001462 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001463 = Context.DeclarationNames.getCXXConstructorName(
1464 Context.getCanonicalType(ToType).getUnqualifiedType());
1465 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001466 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001467 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001468 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001469 // Find the constructor (which may be a template).
1470 CXXConstructorDecl *Constructor = 0;
1471 FunctionTemplateDecl *ConstructorTmpl
1472 = dyn_cast<FunctionTemplateDecl>(*Con);
1473 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001474 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001475 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1476 else
1477 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001478
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001479 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001480 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001481 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00001482 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1483 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001484 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001485 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001486 // Allow one user-defined conversion when user specifies a
1487 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001488 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001489 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001490 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001491 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001492 }
1493 }
1494
Douglas Gregor576e98c2009-01-30 23:27:23 +00001495 if (!AllowConversionFunctions) {
1496 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001497 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1498 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001499 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001500 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001501 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001502 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001503 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001504 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1505 // Add all of the conversion functions as candidates.
John McCalld14a8642009-11-21 08:51:07 +00001506 const UnresolvedSet *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001507 = FromRecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00001508 for (UnresolvedSet::iterator I = Conversions->begin(),
1509 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00001510 NamedDecl *D = *I;
1511 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1512 if (isa<UsingShadowDecl>(D))
1513 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1514
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001515 CXXConversionDecl *Conv;
1516 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001517 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001518 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1519 else
John McCalld14a8642009-11-21 08:51:07 +00001520 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001521
1522 if (AllowExplicit || !Conv->isExplicit()) {
1523 if (ConvTemplate)
John McCall6e9f8f62009-12-03 04:06:58 +00001524 AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1525 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001526 else
John McCall6e9f8f62009-12-03 04:06:58 +00001527 AddConversionCandidate(Conv, ActingContext, From, ToType,
1528 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001529 }
1530 }
1531 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001532 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001533
1534 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001535 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001536 case OR_Success:
1537 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001538 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001539 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1540 // C++ [over.ics.user]p1:
1541 // If the user-defined conversion is specified by a
1542 // constructor (12.3.1), the initial standard conversion
1543 // sequence converts the source type to the type required by
1544 // the argument of the constructor.
1545 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001546 QualType ThisType = Constructor->getThisType(Context);
Fariborz Jahanian55824512009-11-06 00:23:08 +00001547 if (Best->Conversions[0].ConversionKind ==
1548 ImplicitConversionSequence::EllipsisConversion)
1549 User.EllipsisConversion = true;
1550 else {
1551 User.Before = Best->Conversions[0].Standard;
1552 User.EllipsisConversion = false;
1553 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001554 User.ConversionFunction = Constructor;
1555 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001556 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001557 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001558 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001559 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001560 } else if (CXXConversionDecl *Conversion
1561 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1562 // C++ [over.ics.user]p1:
1563 //
1564 // [...] If the user-defined conversion is specified by a
1565 // conversion function (12.3.2), the initial standard
1566 // conversion sequence converts the source type to the
1567 // implicit object parameter of the conversion function.
1568 User.Before = Best->Conversions[0].Standard;
1569 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001570 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001571
1572 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001573 // The second standard conversion sequence converts the
1574 // result of the user-defined conversion to the target type
1575 // for the sequence. Since an implicit conversion sequence
1576 // is an initialization, the special rules for
1577 // initialization by user-defined conversion apply when
1578 // selecting the best user-defined conversion for a
1579 // user-defined conversion sequence (see 13.3.3 and
1580 // 13.3.3.1).
1581 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001582 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001583 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001584 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001585 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001586 }
Mike Stump11289f42009-09-09 15:08:12 +00001587
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001588 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001589 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001590 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001591 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001592 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001593
1594 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001595 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001596 }
1597
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001598 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001599}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001600
1601bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001602Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001603 ImplicitConversionSequence ICS;
1604 OverloadCandidateSet CandidateSet;
1605 OverloadingResult OvResult =
1606 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1607 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001608 if (OvResult == OR_Ambiguous)
1609 Diag(From->getSourceRange().getBegin(),
1610 diag::err_typecheck_ambiguous_condition)
1611 << From->getType() << ToType << From->getSourceRange();
1612 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1613 Diag(From->getSourceRange().getBegin(),
1614 diag::err_typecheck_nonviable_condition)
1615 << From->getType() << ToType << From->getSourceRange();
1616 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001617 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00001618 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001619 return true;
1620}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001621
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001622/// CompareImplicitConversionSequences - Compare two implicit
1623/// conversion sequences to determine whether one is better than the
1624/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001625ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001626Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1627 const ImplicitConversionSequence& ICS2)
1628{
1629 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1630 // conversion sequences (as defined in 13.3.3.1)
1631 // -- a standard conversion sequence (13.3.3.1.1) is a better
1632 // conversion sequence than a user-defined conversion sequence or
1633 // an ellipsis conversion sequence, and
1634 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1635 // conversion sequence than an ellipsis conversion sequence
1636 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001637 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001638 if (ICS1.ConversionKind < ICS2.ConversionKind)
1639 return ImplicitConversionSequence::Better;
1640 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1641 return ImplicitConversionSequence::Worse;
1642
1643 // Two implicit conversion sequences of the same form are
1644 // indistinguishable conversion sequences unless one of the
1645 // following rules apply: (C++ 13.3.3.2p3):
1646 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1647 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001648 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001649 ImplicitConversionSequence::UserDefinedConversion) {
1650 // User-defined conversion sequence U1 is a better conversion
1651 // sequence than another user-defined conversion sequence U2 if
1652 // they contain the same user-defined conversion function or
1653 // constructor and if the second standard conversion sequence of
1654 // U1 is better than the second standard conversion sequence of
1655 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001656 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001657 ICS2.UserDefined.ConversionFunction)
1658 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1659 ICS2.UserDefined.After);
1660 }
1661
1662 return ImplicitConversionSequence::Indistinguishable;
1663}
1664
1665/// CompareStandardConversionSequences - Compare two standard
1666/// conversion sequences to determine whether one is better than the
1667/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001668ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001669Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1670 const StandardConversionSequence& SCS2)
1671{
1672 // Standard conversion sequence S1 is a better conversion sequence
1673 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1674
1675 // -- S1 is a proper subsequence of S2 (comparing the conversion
1676 // sequences in the canonical form defined by 13.3.3.1.1,
1677 // excluding any Lvalue Transformation; the identity conversion
1678 // sequence is considered to be a subsequence of any
1679 // non-identity conversion sequence) or, if not that,
1680 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1681 // Neither is a proper subsequence of the other. Do nothing.
1682 ;
1683 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1684 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001685 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001686 SCS1.Third == ICK_Identity))
1687 // SCS1 is a proper subsequence of SCS2.
1688 return ImplicitConversionSequence::Better;
1689 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1690 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001691 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001692 SCS2.Third == ICK_Identity))
1693 // SCS2 is a proper subsequence of SCS1.
1694 return ImplicitConversionSequence::Worse;
1695
1696 // -- the rank of S1 is better than the rank of S2 (by the rules
1697 // defined below), or, if not that,
1698 ImplicitConversionRank Rank1 = SCS1.getRank();
1699 ImplicitConversionRank Rank2 = SCS2.getRank();
1700 if (Rank1 < Rank2)
1701 return ImplicitConversionSequence::Better;
1702 else if (Rank2 < Rank1)
1703 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001704
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001705 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1706 // are indistinguishable unless one of the following rules
1707 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001708
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001709 // A conversion that is not a conversion of a pointer, or
1710 // pointer to member, to bool is better than another conversion
1711 // that is such a conversion.
1712 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1713 return SCS2.isPointerConversionToBool()
1714 ? ImplicitConversionSequence::Better
1715 : ImplicitConversionSequence::Worse;
1716
Douglas Gregor5c407d92008-10-23 00:40:37 +00001717 // C++ [over.ics.rank]p4b2:
1718 //
1719 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001720 // conversion of B* to A* is better than conversion of B* to
1721 // void*, and conversion of A* to void* is better than conversion
1722 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001723 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001724 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001725 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001726 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001727 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1728 // Exactly one of the conversion sequences is a conversion to
1729 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001730 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1731 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001732 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1733 // Neither conversion sequence converts to a void pointer; compare
1734 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001735 if (ImplicitConversionSequence::CompareKind DerivedCK
1736 = CompareDerivedToBaseConversions(SCS1, SCS2))
1737 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001738 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1739 // Both conversion sequences are conversions to void
1740 // pointers. Compare the source types to determine if there's an
1741 // inheritance relationship in their sources.
1742 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1743 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1744
1745 // Adjust the types we're converting from via the array-to-pointer
1746 // conversion, if we need to.
1747 if (SCS1.First == ICK_Array_To_Pointer)
1748 FromType1 = Context.getArrayDecayedType(FromType1);
1749 if (SCS2.First == ICK_Array_To_Pointer)
1750 FromType2 = Context.getArrayDecayedType(FromType2);
1751
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001752 QualType FromPointee1
1753 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1754 QualType FromPointee2
1755 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001756
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001757 if (IsDerivedFrom(FromPointee2, FromPointee1))
1758 return ImplicitConversionSequence::Better;
1759 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1760 return ImplicitConversionSequence::Worse;
1761
1762 // Objective-C++: If one interface is more specific than the
1763 // other, it is the better one.
1764 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1765 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1766 if (FromIface1 && FromIface1) {
1767 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1768 return ImplicitConversionSequence::Better;
1769 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1770 return ImplicitConversionSequence::Worse;
1771 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001772 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001773
1774 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1775 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001776 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001777 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001778 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001779
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001780 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001781 // C++0x [over.ics.rank]p3b4:
1782 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1783 // implicit object parameter of a non-static member function declared
1784 // without a ref-qualifier, and S1 binds an rvalue reference to an
1785 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001786 // FIXME: We don't know if we're dealing with the implicit object parameter,
1787 // or if the member function in this case has a ref qualifier.
1788 // (Of course, we don't have ref qualifiers yet.)
1789 if (SCS1.RRefBinding != SCS2.RRefBinding)
1790 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1791 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001792
1793 // C++ [over.ics.rank]p3b4:
1794 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1795 // which the references refer are the same type except for
1796 // top-level cv-qualifiers, and the type to which the reference
1797 // initialized by S2 refers is more cv-qualified than the type
1798 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001799 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1800 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001801 T1 = Context.getCanonicalType(T1);
1802 T2 = Context.getCanonicalType(T2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001803 if (Context.hasSameUnqualifiedType(T1, T2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001804 if (T2.isMoreQualifiedThan(T1))
1805 return ImplicitConversionSequence::Better;
1806 else if (T1.isMoreQualifiedThan(T2))
1807 return ImplicitConversionSequence::Worse;
1808 }
1809 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001810
1811 return ImplicitConversionSequence::Indistinguishable;
1812}
1813
1814/// CompareQualificationConversions - Compares two standard conversion
1815/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001816/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1817ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001818Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001819 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001820 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001821 // -- S1 and S2 differ only in their qualification conversion and
1822 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1823 // cv-qualification signature of type T1 is a proper subset of
1824 // the cv-qualification signature of type T2, and S1 is not the
1825 // deprecated string literal array-to-pointer conversion (4.2).
1826 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1827 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1828 return ImplicitConversionSequence::Indistinguishable;
1829
1830 // FIXME: the example in the standard doesn't use a qualification
1831 // conversion (!)
1832 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1833 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1834 T1 = Context.getCanonicalType(T1);
1835 T2 = Context.getCanonicalType(T2);
1836
1837 // If the types are the same, we won't learn anything by unwrapped
1838 // them.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001839 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001840 return ImplicitConversionSequence::Indistinguishable;
1841
Mike Stump11289f42009-09-09 15:08:12 +00001842 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001843 = ImplicitConversionSequence::Indistinguishable;
1844 while (UnwrapSimilarPointerTypes(T1, T2)) {
1845 // Within each iteration of the loop, we check the qualifiers to
1846 // determine if this still looks like a qualification
1847 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001848 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001849 // until there are no more pointers or pointers-to-members left
1850 // to unwrap. This essentially mimics what
1851 // IsQualificationConversion does, but here we're checking for a
1852 // strict subset of qualifiers.
1853 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1854 // The qualifiers are the same, so this doesn't tell us anything
1855 // about how the sequences rank.
1856 ;
1857 else if (T2.isMoreQualifiedThan(T1)) {
1858 // T1 has fewer qualifiers, so it could be the better sequence.
1859 if (Result == ImplicitConversionSequence::Worse)
1860 // Neither has qualifiers that are a subset of the other's
1861 // qualifiers.
1862 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001863
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001864 Result = ImplicitConversionSequence::Better;
1865 } else if (T1.isMoreQualifiedThan(T2)) {
1866 // T2 has fewer qualifiers, so it could be the better sequence.
1867 if (Result == ImplicitConversionSequence::Better)
1868 // Neither has qualifiers that are a subset of the other's
1869 // qualifiers.
1870 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001871
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001872 Result = ImplicitConversionSequence::Worse;
1873 } else {
1874 // Qualifiers are disjoint.
1875 return ImplicitConversionSequence::Indistinguishable;
1876 }
1877
1878 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001879 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001880 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001881 }
1882
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001883 // Check that the winning standard conversion sequence isn't using
1884 // the deprecated string literal array to pointer conversion.
1885 switch (Result) {
1886 case ImplicitConversionSequence::Better:
1887 if (SCS1.Deprecated)
1888 Result = ImplicitConversionSequence::Indistinguishable;
1889 break;
1890
1891 case ImplicitConversionSequence::Indistinguishable:
1892 break;
1893
1894 case ImplicitConversionSequence::Worse:
1895 if (SCS2.Deprecated)
1896 Result = ImplicitConversionSequence::Indistinguishable;
1897 break;
1898 }
1899
1900 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001901}
1902
Douglas Gregor5c407d92008-10-23 00:40:37 +00001903/// CompareDerivedToBaseConversions - Compares two standard conversion
1904/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001905/// various kinds of derived-to-base conversions (C++
1906/// [over.ics.rank]p4b3). As part of these checks, we also look at
1907/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001908ImplicitConversionSequence::CompareKind
1909Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1910 const StandardConversionSequence& SCS2) {
1911 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1912 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1913 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1914 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1915
1916 // Adjust the types we're converting from via the array-to-pointer
1917 // conversion, if we need to.
1918 if (SCS1.First == ICK_Array_To_Pointer)
1919 FromType1 = Context.getArrayDecayedType(FromType1);
1920 if (SCS2.First == ICK_Array_To_Pointer)
1921 FromType2 = Context.getArrayDecayedType(FromType2);
1922
1923 // Canonicalize all of the types.
1924 FromType1 = Context.getCanonicalType(FromType1);
1925 ToType1 = Context.getCanonicalType(ToType1);
1926 FromType2 = Context.getCanonicalType(FromType2);
1927 ToType2 = Context.getCanonicalType(ToType2);
1928
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001929 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001930 //
1931 // If class B is derived directly or indirectly from class A and
1932 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001933 //
1934 // For Objective-C, we let A, B, and C also be Objective-C
1935 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001936
1937 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001938 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001939 SCS2.Second == ICK_Pointer_Conversion &&
1940 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1941 FromType1->isPointerType() && FromType2->isPointerType() &&
1942 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001943 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001944 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001945 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001946 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001947 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001948 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001949 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001950 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001951
John McCall9dd450b2009-09-21 23:43:11 +00001952 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1953 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1954 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1955 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001956
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001957 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001958 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1959 if (IsDerivedFrom(ToPointee1, ToPointee2))
1960 return ImplicitConversionSequence::Better;
1961 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1962 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001963
1964 if (ToIface1 && ToIface2) {
1965 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1966 return ImplicitConversionSequence::Better;
1967 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1968 return ImplicitConversionSequence::Worse;
1969 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001970 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001971
1972 // -- conversion of B* to A* is better than conversion of C* to A*,
1973 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1974 if (IsDerivedFrom(FromPointee2, FromPointee1))
1975 return ImplicitConversionSequence::Better;
1976 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1977 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001978
Douglas Gregor237f96c2008-11-26 23:31:11 +00001979 if (FromIface1 && FromIface2) {
1980 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1981 return ImplicitConversionSequence::Better;
1982 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1983 return ImplicitConversionSequence::Worse;
1984 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001985 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001986 }
1987
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001988 // Compare based on reference bindings.
1989 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1990 SCS1.Second == ICK_Derived_To_Base) {
1991 // -- binding of an expression of type C to a reference of type
1992 // B& is better than binding an expression of type C to a
1993 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001994 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1995 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001996 if (IsDerivedFrom(ToType1, ToType2))
1997 return ImplicitConversionSequence::Better;
1998 else if (IsDerivedFrom(ToType2, ToType1))
1999 return ImplicitConversionSequence::Worse;
2000 }
2001
Douglas Gregor2fe98832008-11-03 19:09:14 +00002002 // -- binding of an expression of type B to a reference of type
2003 // A& is better than binding an expression of type C to a
2004 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002005 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2006 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002007 if (IsDerivedFrom(FromType2, FromType1))
2008 return ImplicitConversionSequence::Better;
2009 else if (IsDerivedFrom(FromType1, FromType2))
2010 return ImplicitConversionSequence::Worse;
2011 }
2012 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002013
2014 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002015 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2016 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2017 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2018 const MemberPointerType * FromMemPointer1 =
2019 FromType1->getAs<MemberPointerType>();
2020 const MemberPointerType * ToMemPointer1 =
2021 ToType1->getAs<MemberPointerType>();
2022 const MemberPointerType * FromMemPointer2 =
2023 FromType2->getAs<MemberPointerType>();
2024 const MemberPointerType * ToMemPointer2 =
2025 ToType2->getAs<MemberPointerType>();
2026 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2027 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2028 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2029 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2030 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2031 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2032 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2033 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002034 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002035 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2036 if (IsDerivedFrom(ToPointee1, ToPointee2))
2037 return ImplicitConversionSequence::Worse;
2038 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2039 return ImplicitConversionSequence::Better;
2040 }
2041 // conversion of B::* to C::* is better than conversion of A::* to C::*
2042 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2043 if (IsDerivedFrom(FromPointee1, FromPointee2))
2044 return ImplicitConversionSequence::Better;
2045 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2046 return ImplicitConversionSequence::Worse;
2047 }
2048 }
2049
Douglas Gregor2fe98832008-11-03 19:09:14 +00002050 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2051 SCS1.Second == ICK_Derived_To_Base) {
2052 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002053 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2054 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002055 if (IsDerivedFrom(ToType1, ToType2))
2056 return ImplicitConversionSequence::Better;
2057 else if (IsDerivedFrom(ToType2, ToType1))
2058 return ImplicitConversionSequence::Worse;
2059 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002060
Douglas Gregor2fe98832008-11-03 19:09:14 +00002061 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002062 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2063 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002064 if (IsDerivedFrom(FromType2, FromType1))
2065 return ImplicitConversionSequence::Better;
2066 else if (IsDerivedFrom(FromType1, FromType2))
2067 return ImplicitConversionSequence::Worse;
2068 }
2069 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002070
Douglas Gregor5c407d92008-10-23 00:40:37 +00002071 return ImplicitConversionSequence::Indistinguishable;
2072}
2073
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002074/// TryCopyInitialization - Try to copy-initialize a value of type
2075/// ToType from the expression From. Return the implicit conversion
2076/// sequence required to pass this argument, which may be a bad
2077/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002078/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002079/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2080/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002081ImplicitConversionSequence
2082Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002083 bool SuppressUserConversions, bool ForceRValue,
2084 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002085 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002086 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00002087 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002088 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002089 SuppressUserConversions,
2090 /*AllowExplicit=*/false,
2091 ForceRValue,
2092 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002093 return ICS;
2094 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002095 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002096 SuppressUserConversions,
2097 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002098 ForceRValue,
2099 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002100 }
2101}
2102
Sebastian Redl42e92c42009-04-12 17:16:29 +00002103/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2104/// the expression @p From. Returns true (and emits a diagnostic) if there was
2105/// an error, returns false if the initialization succeeded. Elidable should
2106/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2107/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002108bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002109 AssignmentAction Action, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002110 if (!getLangOptions().CPlusPlus) {
2111 // In C, argument passing is the same as performing an assignment.
2112 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002113
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002114 AssignConvertType ConvTy =
2115 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002116 if (ConvTy != Compatible &&
2117 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2118 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002119
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002120 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002121 FromType, From, Action);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002122 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002123
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002124 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002125 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002126 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002127 /*SuppressUserConversions=*/false,
2128 /*AllowExplicit=*/false,
2129 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002130
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002131 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002132 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002133 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002134 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002135 return Diag(From->getSourceRange().getBegin(),
2136 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002137 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002138 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002139}
2140
Douglas Gregor436424c2008-11-18 23:14:02 +00002141/// TryObjectArgumentInitialization - Try to initialize the object
2142/// parameter of the given member function (@c Method) from the
2143/// expression @p From.
2144ImplicitConversionSequence
John McCall6e9f8f62009-12-03 04:06:58 +00002145Sema::TryObjectArgumentInitialization(QualType FromType,
2146 CXXMethodDecl *Method,
2147 CXXRecordDecl *ActingContext) {
2148 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002149 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2150 // const volatile object.
2151 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2152 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2153 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002154
2155 // Set up the conversion sequence as a "bad" conversion, to allow us
2156 // to exit early.
2157 ImplicitConversionSequence ICS;
2158 ICS.Standard.setAsIdentityConversion();
2159 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2160
2161 // We need to have an object of class type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002162 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002163 FromType = PT->getPointeeType();
2164
2165 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002166
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002167 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002168 // where X is the class of which the function is a member
2169 // (C++ [over.match.funcs]p4). However, when finding an implicit
2170 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002171 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002172 // (C++ [over.match.funcs]p5). We perform a simplified version of
2173 // reference binding here, that allows class rvalues to bind to
2174 // non-constant references.
2175
2176 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2177 // with the implicit object parameter (C++ [over.match.funcs]p5).
2178 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002179 if (ImplicitParamType.getCVRQualifiers()
2180 != FromTypeCanon.getLocalCVRQualifiers() &&
Douglas Gregor01df9462009-11-05 00:07:36 +00002181 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor436424c2008-11-18 23:14:02 +00002182 return ICS;
2183
2184 // Check that we have either the same type or a derived type. It
2185 // affects the conversion rank.
2186 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002187 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002188 ICS.Standard.Second = ICK_Identity;
2189 else if (IsDerivedFrom(FromType, ClassType))
2190 ICS.Standard.Second = ICK_Derived_To_Base;
2191 else
2192 return ICS;
2193
2194 // Success. Mark this as a reference binding.
2195 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2196 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2197 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2198 ICS.Standard.ReferenceBinding = true;
2199 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002200 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002201 return ICS;
2202}
2203
2204/// PerformObjectArgumentInitialization - Perform initialization of
2205/// the implicit object parameter for the given Method with the given
2206/// expression.
2207bool
2208Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002209 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002210 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002211 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002212
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002213 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002214 FromRecordType = PT->getPointeeType();
2215 DestType = Method->getThisType(Context);
2216 } else {
2217 FromRecordType = From->getType();
2218 DestType = ImplicitParamRecordType;
2219 }
2220
John McCall6e9f8f62009-12-03 04:06:58 +00002221 // Note that we always use the true parent context when performing
2222 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002223 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002224 = TryObjectArgumentInitialization(From->getType(), Method,
2225 Method->getParent());
Douglas Gregor436424c2008-11-18 23:14:02 +00002226 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2227 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002228 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002229 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002230
Douglas Gregor436424c2008-11-18 23:14:02 +00002231 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002232 CheckDerivedToBaseConversion(FromRecordType,
2233 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002234 From->getSourceRange().getBegin(),
2235 From->getSourceRange()))
2236 return true;
2237
Mike Stump11289f42009-09-09 15:08:12 +00002238 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002239 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002240 return false;
2241}
2242
Douglas Gregor5fb53972009-01-14 15:45:31 +00002243/// TryContextuallyConvertToBool - Attempt to contextually convert the
2244/// expression From to bool (C++0x [conv]p3).
2245ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002246 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002247 // FIXME: Are these flags correct?
2248 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002249 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002250 /*ForceRValue=*/false,
2251 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002252}
2253
2254/// PerformContextuallyConvertToBool - Perform a contextual conversion
2255/// of the expression From to bool (C++0x [conv]p3).
2256bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2257 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002258 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting))
Douglas Gregor5fb53972009-01-14 15:45:31 +00002259 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002260
Fariborz Jahanian76197412009-11-18 18:26:29 +00002261 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002262 return Diag(From->getSourceRange().getBegin(),
2263 diag::err_typecheck_bool_condition)
2264 << From->getType() << From->getSourceRange();
2265 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002266}
2267
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002268/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002269/// candidate functions, using the given function call arguments. If
2270/// @p SuppressUserConversions, then don't allow user-defined
2271/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002272/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2273/// hacky way to implement the overloading rules for elidable copy
2274/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002275///
2276/// \para PartialOverloading true if we are performing "partial" overloading
2277/// based on an incomplete set of function arguments. This feature is used by
2278/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002279void
2280Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002281 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002282 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002283 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002284 bool ForceRValue,
2285 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002286 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002287 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002288 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002289 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002290 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002291 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002292 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002293
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002294 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002295 if (!isa<CXXConstructorDecl>(Method)) {
2296 // If we get here, it's because we're calling a member function
2297 // that is named without a member access expression (e.g.,
2298 // "this->f") that was either written explicitly or created
2299 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002300 // function, e.g., X::f(). We use an empty type for the implied
2301 // object argument (C++ [over.call.func]p3), and the acting context
2302 // is irrelevant.
2303 AddMethodCandidate(Method, Method->getParent(),
2304 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002305 SuppressUserConversions, ForceRValue);
2306 return;
2307 }
2308 // We treat a constructor like a non-member function, since its object
2309 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002310 }
2311
Douglas Gregorff7028a2009-11-13 23:59:09 +00002312 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002313 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002314
Douglas Gregor27381f32009-11-23 12:27:39 +00002315 // Overload resolution is always an unevaluated context.
2316 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2317
Douglas Gregorffe14e32009-11-14 01:20:54 +00002318 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2319 // C++ [class.copy]p3:
2320 // A member function template is never instantiated to perform the copy
2321 // of a class object to an object of its class type.
2322 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2323 if (NumArgs == 1 &&
2324 Constructor->isCopyConstructorLikeSpecialization() &&
2325 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2326 return;
2327 }
2328
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002329 // Add this candidate
2330 CandidateSet.push_back(OverloadCandidate());
2331 OverloadCandidate& Candidate = CandidateSet.back();
2332 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002333 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002334 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002335 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002336
2337 unsigned NumArgsInProto = Proto->getNumArgs();
2338
2339 // (C++ 13.3.2p2): A candidate function having fewer than m
2340 // parameters is viable only if it has an ellipsis in its parameter
2341 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002342 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2343 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002344 Candidate.Viable = false;
2345 return;
2346 }
2347
2348 // (C++ 13.3.2p2): A candidate function having more than m parameters
2349 // is viable only if the (m+1)st parameter has a default argument
2350 // (8.3.6). For the purposes of overload resolution, the
2351 // parameter list is truncated on the right, so that there are
2352 // exactly m parameters.
2353 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002354 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002355 // Not enough arguments.
2356 Candidate.Viable = false;
2357 return;
2358 }
2359
2360 // Determine the implicit conversion sequences for each of the
2361 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002362 Candidate.Conversions.resize(NumArgs);
2363 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2364 if (ArgIdx < NumArgsInProto) {
2365 // (C++ 13.3.2p3): for F to be a viable function, there shall
2366 // exist for each argument an implicit conversion sequence
2367 // (13.3.3.1) that converts that argument to the corresponding
2368 // parameter of F.
2369 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002370 Candidate.Conversions[ArgIdx]
2371 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002372 SuppressUserConversions, ForceRValue,
2373 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002374 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002375 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002376 // 13.3.3.1-p10 If several different sequences of conversions exist that
2377 // each convert the argument to the parameter type, the implicit conversion
2378 // sequence associated with the parameter is defined to be the unique conversion
2379 // sequence designated the ambiguous conversion sequence. For the purpose of
2380 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2381 // conversion sequence is treated as a user-defined sequence that is
2382 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002383 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002384 Candidate.Conversions[ArgIdx].ConversionKind =
2385 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002386 // Set the conversion function to one of them. As due to ambiguity,
2387 // they carry the same weight and is needed for overload resolution
2388 // later.
2389 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2390 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2391 }
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002392 else {
2393 Candidate.Viable = false;
2394 break;
2395 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002396 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002397 } else {
2398 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2399 // argument for which there is no corresponding parameter is
2400 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002401 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002402 = ImplicitConversionSequence::EllipsisConversion;
2403 }
2404 }
2405}
2406
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002407/// \brief Add all of the function declarations in the given function set to
2408/// the overload canddiate set.
2409void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2410 Expr **Args, unsigned NumArgs,
2411 OverloadCandidateSet& CandidateSet,
2412 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002413 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002414 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002415 F != FEnd; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002416 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002417 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2418 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2419 AddMethodCandidate(cast<CXXMethodDecl>(FD),
John McCall6e9f8f62009-12-03 04:06:58 +00002420 cast<CXXMethodDecl>(FD)->getParent(),
2421 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002422 CandidateSet, SuppressUserConversions);
2423 else
2424 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2425 SuppressUserConversions);
2426 } else {
2427 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2428 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2429 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2430 AddMethodTemplateCandidate(FunTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002431 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002432 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002433 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002434 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002435 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002436 else
2437 AddTemplateOverloadCandidate(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002438 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002439 Args, NumArgs, CandidateSet,
2440 SuppressUserConversions);
2441 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002442 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002443}
2444
John McCallf0f1cf02009-11-17 07:50:12 +00002445/// AddMethodCandidate - Adds a named decl (which is some kind of
2446/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002447void Sema::AddMethodCandidate(NamedDecl *Decl,
2448 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002449 Expr **Args, unsigned NumArgs,
2450 OverloadCandidateSet& CandidateSet,
2451 bool SuppressUserConversions, bool ForceRValue) {
2452
2453 // FIXME: use this
John McCall6e9f8f62009-12-03 04:06:58 +00002454 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002455
2456 if (isa<UsingShadowDecl>(Decl))
2457 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2458
2459 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2460 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2461 "Expected a member function template");
John McCall6e9f8f62009-12-03 04:06:58 +00002462 AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2463 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002464 CandidateSet,
2465 SuppressUserConversions,
2466 ForceRValue);
2467 } else {
John McCall6e9f8f62009-12-03 04:06:58 +00002468 AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2469 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002470 CandidateSet, SuppressUserConversions, ForceRValue);
2471 }
2472}
2473
Douglas Gregor436424c2008-11-18 23:14:02 +00002474/// AddMethodCandidate - Adds the given C++ member function to the set
2475/// of candidate functions, using the given function call arguments
2476/// and the object argument (@c Object). For example, in a call
2477/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2478/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2479/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002480/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2481/// a slightly hacky way to implement the overloading rules for elidable copy
2482/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002483void
John McCall6e9f8f62009-12-03 04:06:58 +00002484Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2485 QualType ObjectType, Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002486 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002487 bool SuppressUserConversions, bool ForceRValue) {
2488 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002489 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002490 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002491 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002492 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002493 assert(!isa<CXXConstructorDecl>(Method) &&
2494 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002495
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002496 if (!CandidateSet.isNewCandidate(Method))
2497 return;
2498
Douglas Gregor27381f32009-11-23 12:27:39 +00002499 // Overload resolution is always an unevaluated context.
2500 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2501
Douglas Gregor436424c2008-11-18 23:14:02 +00002502 // Add this candidate
2503 CandidateSet.push_back(OverloadCandidate());
2504 OverloadCandidate& Candidate = CandidateSet.back();
2505 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002506 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002507 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002508
2509 unsigned NumArgsInProto = Proto->getNumArgs();
2510
2511 // (C++ 13.3.2p2): A candidate function having fewer than m
2512 // parameters is viable only if it has an ellipsis in its parameter
2513 // list (8.3.5).
2514 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2515 Candidate.Viable = false;
2516 return;
2517 }
2518
2519 // (C++ 13.3.2p2): A candidate function having more than m parameters
2520 // is viable only if the (m+1)st parameter has a default argument
2521 // (8.3.6). For the purposes of overload resolution, the
2522 // parameter list is truncated on the right, so that there are
2523 // exactly m parameters.
2524 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2525 if (NumArgs < MinRequiredArgs) {
2526 // Not enough arguments.
2527 Candidate.Viable = false;
2528 return;
2529 }
2530
2531 Candidate.Viable = true;
2532 Candidate.Conversions.resize(NumArgs + 1);
2533
John McCall6e9f8f62009-12-03 04:06:58 +00002534 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002535 // The implicit object argument is ignored.
2536 Candidate.IgnoreObjectArgument = true;
2537 else {
2538 // Determine the implicit conversion sequence for the object
2539 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002540 Candidate.Conversions[0]
2541 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
Mike Stump11289f42009-09-09 15:08:12 +00002542 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002543 == ImplicitConversionSequence::BadConversion) {
2544 Candidate.Viable = false;
2545 return;
2546 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002547 }
2548
2549 // Determine the implicit conversion sequences for each of the
2550 // arguments.
2551 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2552 if (ArgIdx < NumArgsInProto) {
2553 // (C++ 13.3.2p3): for F to be a viable function, there shall
2554 // exist for each argument an implicit conversion sequence
2555 // (13.3.3.1) that converts that argument to the corresponding
2556 // parameter of F.
2557 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002558 Candidate.Conversions[ArgIdx + 1]
2559 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002560 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002561 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002562 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002563 == ImplicitConversionSequence::BadConversion) {
2564 Candidate.Viable = false;
2565 break;
2566 }
2567 } else {
2568 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2569 // argument for which there is no corresponding parameter is
2570 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002571 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002572 = ImplicitConversionSequence::EllipsisConversion;
2573 }
2574 }
2575}
2576
Douglas Gregor97628d62009-08-21 00:16:32 +00002577/// \brief Add a C++ member function template as a candidate to the candidate
2578/// set, using template argument deduction to produce an appropriate member
2579/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002580void
Douglas Gregor97628d62009-08-21 00:16:32 +00002581Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002582 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002583 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002584 QualType ObjectType,
2585 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002586 OverloadCandidateSet& CandidateSet,
2587 bool SuppressUserConversions,
2588 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002589 if (!CandidateSet.isNewCandidate(MethodTmpl))
2590 return;
2591
Douglas Gregor97628d62009-08-21 00:16:32 +00002592 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002593 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002594 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002595 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002596 // candidate functions in the usual way.113) A given name can refer to one
2597 // or more function templates and also to a set of overloaded non-template
2598 // functions. In such a case, the candidate functions generated from each
2599 // function template are combined with the set of non-template candidate
2600 // functions.
2601 TemplateDeductionInfo Info(Context);
2602 FunctionDecl *Specialization = 0;
2603 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002604 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002605 Args, NumArgs, Specialization, Info)) {
2606 // FIXME: Record what happened with template argument deduction, so
2607 // that we can give the user a beautiful diagnostic.
2608 (void)Result;
2609 return;
2610 }
Mike Stump11289f42009-09-09 15:08:12 +00002611
Douglas Gregor97628d62009-08-21 00:16:32 +00002612 // Add the function template specialization produced by template argument
2613 // deduction as a candidate.
2614 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002615 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002616 "Specialization is not a member function?");
John McCall6e9f8f62009-12-03 04:06:58 +00002617 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2618 ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002619 CandidateSet, SuppressUserConversions, ForceRValue);
2620}
2621
Douglas Gregor05155d82009-08-21 23:19:43 +00002622/// \brief Add a C++ function template specialization as a candidate
2623/// in the candidate set, using template argument deduction to produce
2624/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002625void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002626Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002627 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002628 Expr **Args, unsigned NumArgs,
2629 OverloadCandidateSet& CandidateSet,
2630 bool SuppressUserConversions,
2631 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002632 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2633 return;
2634
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002635 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002636 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002637 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002638 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002639 // candidate functions in the usual way.113) A given name can refer to one
2640 // or more function templates and also to a set of overloaded non-template
2641 // functions. In such a case, the candidate functions generated from each
2642 // function template are combined with the set of non-template candidate
2643 // functions.
2644 TemplateDeductionInfo Info(Context);
2645 FunctionDecl *Specialization = 0;
2646 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002647 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002648 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002649 // FIXME: Record what happened with template argument deduction, so
2650 // that we can give the user a beautiful diagnostic.
John McCalld681c392009-12-16 08:11:27 +00002651 (void) Result;
2652
2653 CandidateSet.push_back(OverloadCandidate());
2654 OverloadCandidate &Candidate = CandidateSet.back();
2655 Candidate.Function = FunctionTemplate->getTemplatedDecl();
2656 Candidate.Viable = false;
2657 Candidate.IsSurrogate = false;
2658 Candidate.IgnoreObjectArgument = false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002659 return;
2660 }
Mike Stump11289f42009-09-09 15:08:12 +00002661
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002662 // Add the function template specialization produced by template argument
2663 // deduction as a candidate.
2664 assert(Specialization && "Missing function template specialization?");
2665 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2666 SuppressUserConversions, ForceRValue);
2667}
Mike Stump11289f42009-09-09 15:08:12 +00002668
Douglas Gregora1f013e2008-11-07 22:36:19 +00002669/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002670/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002671/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002672/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002673/// (which may or may not be the same type as the type that the
2674/// conversion function produces).
2675void
2676Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002677 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002678 Expr *From, QualType ToType,
2679 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002680 assert(!Conversion->getDescribedFunctionTemplate() &&
2681 "Conversion function templates use AddTemplateConversionCandidate");
2682
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002683 if (!CandidateSet.isNewCandidate(Conversion))
2684 return;
2685
Douglas Gregor27381f32009-11-23 12:27:39 +00002686 // Overload resolution is always an unevaluated context.
2687 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2688
Douglas Gregora1f013e2008-11-07 22:36:19 +00002689 // Add this candidate
2690 CandidateSet.push_back(OverloadCandidate());
2691 OverloadCandidate& Candidate = CandidateSet.back();
2692 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002693 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002694 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002695 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002696 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002697 = Conversion->getConversionType().getAsOpaquePtr();
2698 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2699
Douglas Gregor436424c2008-11-18 23:14:02 +00002700 // Determine the implicit conversion sequence for the implicit
2701 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002702 Candidate.Viable = true;
2703 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002704 Candidate.Conversions[0]
2705 = TryObjectArgumentInitialization(From->getType(), Conversion,
2706 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002707 // Conversion functions to a different type in the base class is visible in
2708 // the derived class. So, a derived to base conversion should not participate
2709 // in overload resolution.
2710 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2711 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002712 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002713 == ImplicitConversionSequence::BadConversion) {
2714 Candidate.Viable = false;
2715 return;
2716 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002717
2718 // We won't go through a user-define type conversion function to convert a
2719 // derived to base as such conversions are given Conversion Rank. They only
2720 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2721 QualType FromCanon
2722 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2723 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2724 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2725 Candidate.Viable = false;
2726 return;
2727 }
2728
Douglas Gregora1f013e2008-11-07 22:36:19 +00002729
2730 // To determine what the conversion from the result of calling the
2731 // conversion function to the type we're eventually trying to
2732 // convert to (ToType), we need to synthesize a call to the
2733 // conversion function and attempt copy initialization from it. This
2734 // makes sure that we get the right semantics with respect to
2735 // lvalues/rvalues and the type. Fortunately, we can allocate this
2736 // call on the stack and we don't need its arguments to be
2737 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002738 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002739 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002740 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002741 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002742 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002743
2744 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002745 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2746 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002747 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002748 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002749 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002750 ImplicitConversionSequence ICS =
2751 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002752 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002753 /*ForceRValue=*/false,
2754 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002755
Douglas Gregora1f013e2008-11-07 22:36:19 +00002756 switch (ICS.ConversionKind) {
2757 case ImplicitConversionSequence::StandardConversion:
2758 Candidate.FinalConversion = ICS.Standard;
2759 break;
2760
2761 case ImplicitConversionSequence::BadConversion:
2762 Candidate.Viable = false;
2763 break;
2764
2765 default:
Mike Stump11289f42009-09-09 15:08:12 +00002766 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002767 "Can only end up with a standard conversion sequence or failure");
2768 }
2769}
2770
Douglas Gregor05155d82009-08-21 23:19:43 +00002771/// \brief Adds a conversion function template specialization
2772/// candidate to the overload set, using template argument deduction
2773/// to deduce the template arguments of the conversion function
2774/// template from the type that we are converting to (C++
2775/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002776void
Douglas Gregor05155d82009-08-21 23:19:43 +00002777Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6e9f8f62009-12-03 04:06:58 +00002778 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002779 Expr *From, QualType ToType,
2780 OverloadCandidateSet &CandidateSet) {
2781 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2782 "Only conversion function templates permitted here");
2783
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002784 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2785 return;
2786
Douglas Gregor05155d82009-08-21 23:19:43 +00002787 TemplateDeductionInfo Info(Context);
2788 CXXConversionDecl *Specialization = 0;
2789 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002790 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002791 Specialization, Info)) {
2792 // FIXME: Record what happened with template argument deduction, so
2793 // that we can give the user a beautiful diagnostic.
2794 (void)Result;
2795 return;
2796 }
Mike Stump11289f42009-09-09 15:08:12 +00002797
Douglas Gregor05155d82009-08-21 23:19:43 +00002798 // Add the conversion function template specialization produced by
2799 // template argument deduction as a candidate.
2800 assert(Specialization && "Missing function template specialization?");
John McCall6e9f8f62009-12-03 04:06:58 +00002801 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002802}
2803
Douglas Gregorab7897a2008-11-19 22:57:39 +00002804/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2805/// converts the given @c Object to a function pointer via the
2806/// conversion function @c Conversion, and then attempts to call it
2807/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2808/// the type of function that we'll eventually be calling.
2809void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002810 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002811 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002812 QualType ObjectType,
2813 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002814 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002815 if (!CandidateSet.isNewCandidate(Conversion))
2816 return;
2817
Douglas Gregor27381f32009-11-23 12:27:39 +00002818 // Overload resolution is always an unevaluated context.
2819 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2820
Douglas Gregorab7897a2008-11-19 22:57:39 +00002821 CandidateSet.push_back(OverloadCandidate());
2822 OverloadCandidate& Candidate = CandidateSet.back();
2823 Candidate.Function = 0;
2824 Candidate.Surrogate = Conversion;
2825 Candidate.Viable = true;
2826 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002827 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002828 Candidate.Conversions.resize(NumArgs + 1);
2829
2830 // Determine the implicit conversion sequence for the implicit
2831 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002832 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002833 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
Douglas Gregorab7897a2008-11-19 22:57:39 +00002834 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2835 Candidate.Viable = false;
2836 return;
2837 }
2838
2839 // The first conversion is actually a user-defined conversion whose
2840 // first conversion is ObjectInit's standard conversion (which is
2841 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002842 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002843 = ImplicitConversionSequence::UserDefinedConversion;
2844 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002845 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002846 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002847 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002848 = Candidate.Conversions[0].UserDefined.Before;
2849 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2850
Mike Stump11289f42009-09-09 15:08:12 +00002851 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002852 unsigned NumArgsInProto = Proto->getNumArgs();
2853
2854 // (C++ 13.3.2p2): A candidate function having fewer than m
2855 // parameters is viable only if it has an ellipsis in its parameter
2856 // list (8.3.5).
2857 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2858 Candidate.Viable = false;
2859 return;
2860 }
2861
2862 // Function types don't have any default arguments, so just check if
2863 // we have enough arguments.
2864 if (NumArgs < NumArgsInProto) {
2865 // Not enough arguments.
2866 Candidate.Viable = false;
2867 return;
2868 }
2869
2870 // Determine the implicit conversion sequences for each of the
2871 // arguments.
2872 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2873 if (ArgIdx < NumArgsInProto) {
2874 // (C++ 13.3.2p3): for F to be a viable function, there shall
2875 // exist for each argument an implicit conversion sequence
2876 // (13.3.3.1) that converts that argument to the corresponding
2877 // parameter of F.
2878 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002879 Candidate.Conversions[ArgIdx + 1]
2880 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002881 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002882 /*ForceRValue=*/false,
2883 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002884 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002885 == ImplicitConversionSequence::BadConversion) {
2886 Candidate.Viable = false;
2887 break;
2888 }
2889 } else {
2890 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2891 // argument for which there is no corresponding parameter is
2892 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002893 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002894 = ImplicitConversionSequence::EllipsisConversion;
2895 }
2896 }
2897}
2898
Mike Stump87c57ac2009-05-16 07:39:55 +00002899// FIXME: This will eventually be removed, once we've migrated all of the
2900// operator overloading logic over to the scheme used by binary operators, which
2901// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002902void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002903 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002904 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002905 OverloadCandidateSet& CandidateSet,
2906 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002907 FunctionSet Functions;
2908
2909 QualType T1 = Args[0]->getType();
2910 QualType T2;
2911 if (NumArgs > 1)
2912 T2 = Args[1]->getType();
2913
2914 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002915 if (S)
2916 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002917 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002918 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2919 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002920 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002921}
2922
2923/// \brief Add overload candidates for overloaded operators that are
2924/// member functions.
2925///
2926/// Add the overloaded operator candidates that are member functions
2927/// for the operator Op that was used in an operator expression such
2928/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2929/// CandidateSet will store the added overload candidates. (C++
2930/// [over.match.oper]).
2931void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2932 SourceLocation OpLoc,
2933 Expr **Args, unsigned NumArgs,
2934 OverloadCandidateSet& CandidateSet,
2935 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002936 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2937
2938 // C++ [over.match.oper]p3:
2939 // For a unary operator @ with an operand of a type whose
2940 // cv-unqualified version is T1, and for a binary operator @ with
2941 // a left operand of a type whose cv-unqualified version is T1 and
2942 // a right operand of a type whose cv-unqualified version is T2,
2943 // three sets of candidate functions, designated member
2944 // candidates, non-member candidates and built-in candidates, are
2945 // constructed as follows:
2946 QualType T1 = Args[0]->getType();
2947 QualType T2;
2948 if (NumArgs > 1)
2949 T2 = Args[1]->getType();
2950
2951 // -- If T1 is a class type, the set of member candidates is the
2952 // result of the qualified lookup of T1::operator@
2953 // (13.3.1.1.1); otherwise, the set of member candidates is
2954 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002955 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002956 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002957 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002958 return;
Mike Stump11289f42009-09-09 15:08:12 +00002959
John McCall27b18f82009-11-17 02:14:36 +00002960 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2961 LookupQualifiedName(Operators, T1Rec->getDecl());
2962 Operators.suppressDiagnostics();
2963
Mike Stump11289f42009-09-09 15:08:12 +00002964 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002965 OperEnd = Operators.end();
2966 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00002967 ++Oper)
John McCall6e9f8f62009-12-03 04:06:58 +00002968 AddMethodCandidate(*Oper, Args[0]->getType(),
2969 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00002970 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002971 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002972}
2973
Douglas Gregora11693b2008-11-12 17:17:38 +00002974/// AddBuiltinCandidate - Add a candidate for a built-in
2975/// operator. ResultTy and ParamTys are the result and parameter types
2976/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002977/// arguments being passed to the candidate. IsAssignmentOperator
2978/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002979/// operator. NumContextualBoolArguments is the number of arguments
2980/// (at the beginning of the argument list) that will be contextually
2981/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002982void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002983 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002984 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002985 bool IsAssignmentOperator,
2986 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00002987 // Overload resolution is always an unevaluated context.
2988 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2989
Douglas Gregora11693b2008-11-12 17:17:38 +00002990 // Add this candidate
2991 CandidateSet.push_back(OverloadCandidate());
2992 OverloadCandidate& Candidate = CandidateSet.back();
2993 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002994 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002995 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002996 Candidate.BuiltinTypes.ResultTy = ResultTy;
2997 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2998 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2999
3000 // Determine the implicit conversion sequences for each of the
3001 // arguments.
3002 Candidate.Viable = true;
3003 Candidate.Conversions.resize(NumArgs);
3004 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003005 // C++ [over.match.oper]p4:
3006 // For the built-in assignment operators, conversions of the
3007 // left operand are restricted as follows:
3008 // -- no temporaries are introduced to hold the left operand, and
3009 // -- no user-defined conversions are applied to the left
3010 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003011 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003012 //
3013 // We block these conversions by turning off user-defined
3014 // conversions, since that is the only way that initialization of
3015 // a reference to a non-class type can occur from something that
3016 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003017 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003018 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003019 "Contextual conversion to bool requires bool type");
3020 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3021 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003022 Candidate.Conversions[ArgIdx]
3023 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003024 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003025 /*ForceRValue=*/false,
3026 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003027 }
Mike Stump11289f42009-09-09 15:08:12 +00003028 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00003029 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003030 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003031 break;
3032 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003033 }
3034}
3035
3036/// BuiltinCandidateTypeSet - A set of types that will be used for the
3037/// candidate operator functions for built-in operators (C++
3038/// [over.built]). The types are separated into pointer types and
3039/// enumeration types.
3040class BuiltinCandidateTypeSet {
3041 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003042 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003043
3044 /// PointerTypes - The set of pointer types that will be used in the
3045 /// built-in candidates.
3046 TypeSet PointerTypes;
3047
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003048 /// MemberPointerTypes - The set of member pointer types that will be
3049 /// used in the built-in candidates.
3050 TypeSet MemberPointerTypes;
3051
Douglas Gregora11693b2008-11-12 17:17:38 +00003052 /// EnumerationTypes - The set of enumeration types that will be
3053 /// used in the built-in candidates.
3054 TypeSet EnumerationTypes;
3055
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003056 /// Sema - The semantic analysis instance where we are building the
3057 /// candidate type set.
3058 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003059
Douglas Gregora11693b2008-11-12 17:17:38 +00003060 /// Context - The AST context in which we will build the type sets.
3061 ASTContext &Context;
3062
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003063 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3064 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003065 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003066
3067public:
3068 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003069 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003070
Mike Stump11289f42009-09-09 15:08:12 +00003071 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003072 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003073
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003074 void AddTypesConvertedFrom(QualType Ty,
3075 SourceLocation Loc,
3076 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003077 bool AllowExplicitConversions,
3078 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003079
3080 /// pointer_begin - First pointer type found;
3081 iterator pointer_begin() { return PointerTypes.begin(); }
3082
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003083 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003084 iterator pointer_end() { return PointerTypes.end(); }
3085
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003086 /// member_pointer_begin - First member pointer type found;
3087 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3088
3089 /// member_pointer_end - Past the last member pointer type found;
3090 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3091
Douglas Gregora11693b2008-11-12 17:17:38 +00003092 /// enumeration_begin - First enumeration type found;
3093 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3094
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003095 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003096 iterator enumeration_end() { return EnumerationTypes.end(); }
3097};
3098
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003099/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003100/// the set of pointer types along with any more-qualified variants of
3101/// that type. For example, if @p Ty is "int const *", this routine
3102/// will add "int const *", "int const volatile *", "int const
3103/// restrict *", and "int const volatile restrict *" to the set of
3104/// pointer types. Returns true if the add of @p Ty itself succeeded,
3105/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003106///
3107/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003108bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003109BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3110 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003111
Douglas Gregora11693b2008-11-12 17:17:38 +00003112 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003113 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003114 return false;
3115
John McCall8ccfcb52009-09-24 19:53:00 +00003116 const PointerType *PointerTy = Ty->getAs<PointerType>();
3117 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003118
John McCall8ccfcb52009-09-24 19:53:00 +00003119 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003120 // Don't add qualified variants of arrays. For one, they're not allowed
3121 // (the qualifier would sink to the element type), and for another, the
3122 // only overload situation where it matters is subscript or pointer +- int,
3123 // and those shouldn't have qualifier variants anyway.
3124 if (PointeeTy->isArrayType())
3125 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003126 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003127 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003128 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003129 bool hasVolatile = VisibleQuals.hasVolatile();
3130 bool hasRestrict = VisibleQuals.hasRestrict();
3131
John McCall8ccfcb52009-09-24 19:53:00 +00003132 // Iterate through all strict supersets of BaseCVR.
3133 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3134 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003135 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3136 // in the types.
3137 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3138 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003139 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3140 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003141 }
3142
3143 return true;
3144}
3145
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003146/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3147/// to the set of pointer types along with any more-qualified variants of
3148/// that type. For example, if @p Ty is "int const *", this routine
3149/// will add "int const *", "int const volatile *", "int const
3150/// restrict *", and "int const volatile restrict *" to the set of
3151/// pointer types. Returns true if the add of @p Ty itself succeeded,
3152/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003153///
3154/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003155bool
3156BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3157 QualType Ty) {
3158 // Insert this type.
3159 if (!MemberPointerTypes.insert(Ty))
3160 return false;
3161
John McCall8ccfcb52009-09-24 19:53:00 +00003162 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3163 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003164
John McCall8ccfcb52009-09-24 19:53:00 +00003165 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003166 // Don't add qualified variants of arrays. For one, they're not allowed
3167 // (the qualifier would sink to the element type), and for another, the
3168 // only overload situation where it matters is subscript or pointer +- int,
3169 // and those shouldn't have qualifier variants anyway.
3170 if (PointeeTy->isArrayType())
3171 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003172 const Type *ClassTy = PointerTy->getClass();
3173
3174 // Iterate through all strict supersets of the pointee type's CVR
3175 // qualifiers.
3176 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3177 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3178 if ((CVR | BaseCVR) != CVR) continue;
3179
3180 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3181 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003182 }
3183
3184 return true;
3185}
3186
Douglas Gregora11693b2008-11-12 17:17:38 +00003187/// AddTypesConvertedFrom - Add each of the types to which the type @p
3188/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003189/// primarily interested in pointer types and enumeration types. We also
3190/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003191/// AllowUserConversions is true if we should look at the conversion
3192/// functions of a class type, and AllowExplicitConversions if we
3193/// should also include the explicit conversion functions of a class
3194/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003195void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003196BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003197 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003198 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003199 bool AllowExplicitConversions,
3200 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003201 // Only deal with canonical types.
3202 Ty = Context.getCanonicalType(Ty);
3203
3204 // Look through reference types; they aren't part of the type of an
3205 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003206 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003207 Ty = RefTy->getPointeeType();
3208
3209 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003210 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003211
Sebastian Redl65ae2002009-11-05 16:36:20 +00003212 // If we're dealing with an array type, decay to the pointer.
3213 if (Ty->isArrayType())
3214 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3215
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003216 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003217 QualType PointeeTy = PointerTy->getPointeeType();
3218
3219 // Insert our type, and its more-qualified variants, into the set
3220 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003221 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003222 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003223 } else if (Ty->isMemberPointerType()) {
3224 // Member pointers are far easier, since the pointee can't be converted.
3225 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3226 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003227 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003228 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003229 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003230 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003231 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003232 // No conversion functions in incomplete types.
3233 return;
3234 }
Mike Stump11289f42009-09-09 15:08:12 +00003235
Douglas Gregora11693b2008-11-12 17:17:38 +00003236 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003237 const UnresolvedSet *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003238 = ClassDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00003239 for (UnresolvedSet::iterator I = Conversions->begin(),
3240 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003241
Mike Stump11289f42009-09-09 15:08:12 +00003242 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003243 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003244 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003245 continue;
3246
John McCalld14a8642009-11-21 08:51:07 +00003247 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003248 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003249 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003250 VisibleQuals);
3251 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003252 }
3253 }
3254 }
3255}
3256
Douglas Gregor84605ae2009-08-24 13:43:27 +00003257/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3258/// the volatile- and non-volatile-qualified assignment operators for the
3259/// given type to the candidate set.
3260static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3261 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003262 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003263 unsigned NumArgs,
3264 OverloadCandidateSet &CandidateSet) {
3265 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003266
Douglas Gregor84605ae2009-08-24 13:43:27 +00003267 // T& operator=(T&, T)
3268 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3269 ParamTypes[1] = T;
3270 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3271 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003272
Douglas Gregor84605ae2009-08-24 13:43:27 +00003273 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3274 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003275 ParamTypes[0]
3276 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003277 ParamTypes[1] = T;
3278 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003279 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003280 }
3281}
Mike Stump11289f42009-09-09 15:08:12 +00003282
Sebastian Redl1054fae2009-10-25 17:03:50 +00003283/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3284/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003285static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3286 Qualifiers VRQuals;
3287 const RecordType *TyRec;
3288 if (const MemberPointerType *RHSMPType =
3289 ArgExpr->getType()->getAs<MemberPointerType>())
3290 TyRec = cast<RecordType>(RHSMPType->getClass());
3291 else
3292 TyRec = ArgExpr->getType()->getAs<RecordType>();
3293 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003294 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003295 VRQuals.addVolatile();
3296 VRQuals.addRestrict();
3297 return VRQuals;
3298 }
3299
3300 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003301 const UnresolvedSet *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003302 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003303
John McCalld14a8642009-11-21 08:51:07 +00003304 for (UnresolvedSet::iterator I = Conversions->begin(),
3305 E = Conversions->end(); I != E; ++I) {
3306 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003307 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3308 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3309 CanTy = ResTypeRef->getPointeeType();
3310 // Need to go down the pointer/mempointer chain and add qualifiers
3311 // as see them.
3312 bool done = false;
3313 while (!done) {
3314 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3315 CanTy = ResTypePtr->getPointeeType();
3316 else if (const MemberPointerType *ResTypeMPtr =
3317 CanTy->getAs<MemberPointerType>())
3318 CanTy = ResTypeMPtr->getPointeeType();
3319 else
3320 done = true;
3321 if (CanTy.isVolatileQualified())
3322 VRQuals.addVolatile();
3323 if (CanTy.isRestrictQualified())
3324 VRQuals.addRestrict();
3325 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3326 return VRQuals;
3327 }
3328 }
3329 }
3330 return VRQuals;
3331}
3332
Douglas Gregord08452f2008-11-19 15:42:04 +00003333/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3334/// operator overloads to the candidate set (C++ [over.built]), based
3335/// on the operator @p Op and the arguments given. For example, if the
3336/// operator is a binary '+', this routine might add "int
3337/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003338void
Mike Stump11289f42009-09-09 15:08:12 +00003339Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003340 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003341 Expr **Args, unsigned NumArgs,
3342 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003343 // The set of "promoted arithmetic types", which are the arithmetic
3344 // types are that preserved by promotion (C++ [over.built]p2). Note
3345 // that the first few of these types are the promoted integral
3346 // types; these types need to be first.
3347 // FIXME: What about complex?
3348 const unsigned FirstIntegralType = 0;
3349 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003350 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003351 LastPromotedIntegralType = 13;
3352 const unsigned FirstPromotedArithmeticType = 7,
3353 LastPromotedArithmeticType = 16;
3354 const unsigned NumArithmeticTypes = 16;
3355 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003356 Context.BoolTy, Context.CharTy, Context.WCharTy,
3357// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003358 Context.SignedCharTy, Context.ShortTy,
3359 Context.UnsignedCharTy, Context.UnsignedShortTy,
3360 Context.IntTy, Context.LongTy, Context.LongLongTy,
3361 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3362 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3363 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003364 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3365 "Invalid first promoted integral type");
3366 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3367 == Context.UnsignedLongLongTy &&
3368 "Invalid last promoted integral type");
3369 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3370 "Invalid first promoted arithmetic type");
3371 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3372 == Context.LongDoubleTy &&
3373 "Invalid last promoted arithmetic type");
3374
Douglas Gregora11693b2008-11-12 17:17:38 +00003375 // Find all of the types that the arguments can convert to, but only
3376 // if the operator we're looking at has built-in operator candidates
3377 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003378 Qualifiers VisibleTypeConversionsQuals;
3379 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003380 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3381 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3382
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003383 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003384 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3385 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003386 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003387 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003388 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003389 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003390 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003391 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003392 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003393 true,
3394 (Op == OO_Exclaim ||
3395 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003396 Op == OO_PipePipe),
3397 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003398 }
3399
3400 bool isComparison = false;
3401 switch (Op) {
3402 case OO_None:
3403 case NUM_OVERLOADED_OPERATORS:
3404 assert(false && "Expected an overloaded operator");
3405 break;
3406
Douglas Gregord08452f2008-11-19 15:42:04 +00003407 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003408 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003409 goto UnaryStar;
3410 else
3411 goto BinaryStar;
3412 break;
3413
3414 case OO_Plus: // '+' is either unary or binary
3415 if (NumArgs == 1)
3416 goto UnaryPlus;
3417 else
3418 goto BinaryPlus;
3419 break;
3420
3421 case OO_Minus: // '-' is either unary or binary
3422 if (NumArgs == 1)
3423 goto UnaryMinus;
3424 else
3425 goto BinaryMinus;
3426 break;
3427
3428 case OO_Amp: // '&' is either unary or binary
3429 if (NumArgs == 1)
3430 goto UnaryAmp;
3431 else
3432 goto BinaryAmp;
3433
3434 case OO_PlusPlus:
3435 case OO_MinusMinus:
3436 // C++ [over.built]p3:
3437 //
3438 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3439 // is either volatile or empty, there exist candidate operator
3440 // functions of the form
3441 //
3442 // VQ T& operator++(VQ T&);
3443 // T operator++(VQ T&, int);
3444 //
3445 // C++ [over.built]p4:
3446 //
3447 // For every pair (T, VQ), where T is an arithmetic type other
3448 // than bool, and VQ is either volatile or empty, there exist
3449 // candidate operator functions of the form
3450 //
3451 // VQ T& operator--(VQ T&);
3452 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003453 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003454 Arith < NumArithmeticTypes; ++Arith) {
3455 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003456 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003457 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003458
3459 // Non-volatile version.
3460 if (NumArgs == 1)
3461 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3462 else
3463 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003464 // heuristic to reduce number of builtin candidates in the set.
3465 // Add volatile version only if there are conversions to a volatile type.
3466 if (VisibleTypeConversionsQuals.hasVolatile()) {
3467 // Volatile version
3468 ParamTypes[0]
3469 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3470 if (NumArgs == 1)
3471 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3472 else
3473 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3474 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003475 }
3476
3477 // C++ [over.built]p5:
3478 //
3479 // For every pair (T, VQ), where T is a cv-qualified or
3480 // cv-unqualified object type, and VQ is either volatile or
3481 // empty, there exist candidate operator functions of the form
3482 //
3483 // T*VQ& operator++(T*VQ&);
3484 // T*VQ& operator--(T*VQ&);
3485 // T* operator++(T*VQ&, int);
3486 // T* operator--(T*VQ&, int);
3487 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3488 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3489 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003490 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003491 continue;
3492
Mike Stump11289f42009-09-09 15:08:12 +00003493 QualType ParamTypes[2] = {
3494 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003495 };
Mike Stump11289f42009-09-09 15:08:12 +00003496
Douglas Gregord08452f2008-11-19 15:42:04 +00003497 // Without volatile
3498 if (NumArgs == 1)
3499 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3500 else
3501 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3502
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003503 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3504 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003505 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003506 ParamTypes[0]
3507 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003508 if (NumArgs == 1)
3509 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3510 else
3511 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3512 }
3513 }
3514 break;
3515
3516 UnaryStar:
3517 // C++ [over.built]p6:
3518 // For every cv-qualified or cv-unqualified object type T, there
3519 // exist candidate operator functions of the form
3520 //
3521 // T& operator*(T*);
3522 //
3523 // C++ [over.built]p7:
3524 // For every function type T, there exist candidate operator
3525 // functions of the form
3526 // T& operator*(T*);
3527 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3528 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3529 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003530 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003531 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003532 &ParamTy, Args, 1, CandidateSet);
3533 }
3534 break;
3535
3536 UnaryPlus:
3537 // C++ [over.built]p8:
3538 // For every type T, there exist candidate operator functions of
3539 // the form
3540 //
3541 // T* operator+(T*);
3542 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3543 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3544 QualType ParamTy = *Ptr;
3545 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3546 }
Mike Stump11289f42009-09-09 15:08:12 +00003547
Douglas Gregord08452f2008-11-19 15:42:04 +00003548 // Fall through
3549
3550 UnaryMinus:
3551 // C++ [over.built]p9:
3552 // For every promoted arithmetic type T, there exist candidate
3553 // operator functions of the form
3554 //
3555 // T operator+(T);
3556 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003557 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003558 Arith < LastPromotedArithmeticType; ++Arith) {
3559 QualType ArithTy = ArithmeticTypes[Arith];
3560 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3561 }
3562 break;
3563
3564 case OO_Tilde:
3565 // C++ [over.built]p10:
3566 // For every promoted integral type T, there exist candidate
3567 // operator functions of the form
3568 //
3569 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003570 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003571 Int < LastPromotedIntegralType; ++Int) {
3572 QualType IntTy = ArithmeticTypes[Int];
3573 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3574 }
3575 break;
3576
Douglas Gregora11693b2008-11-12 17:17:38 +00003577 case OO_New:
3578 case OO_Delete:
3579 case OO_Array_New:
3580 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003581 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003582 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003583 break;
3584
3585 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003586 UnaryAmp:
3587 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003588 // C++ [over.match.oper]p3:
3589 // -- For the operator ',', the unary operator '&', or the
3590 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003591 break;
3592
Douglas Gregor84605ae2009-08-24 13:43:27 +00003593 case OO_EqualEqual:
3594 case OO_ExclaimEqual:
3595 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003596 // For every pointer to member type T, there exist candidate operator
3597 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003598 //
3599 // bool operator==(T,T);
3600 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003601 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003602 MemPtr = CandidateTypes.member_pointer_begin(),
3603 MemPtrEnd = CandidateTypes.member_pointer_end();
3604 MemPtr != MemPtrEnd;
3605 ++MemPtr) {
3606 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3607 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3608 }
Mike Stump11289f42009-09-09 15:08:12 +00003609
Douglas Gregor84605ae2009-08-24 13:43:27 +00003610 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003611
Douglas Gregora11693b2008-11-12 17:17:38 +00003612 case OO_Less:
3613 case OO_Greater:
3614 case OO_LessEqual:
3615 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003616 // C++ [over.built]p15:
3617 //
3618 // For every pointer or enumeration type T, there exist
3619 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003620 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003621 // bool operator<(T, T);
3622 // bool operator>(T, T);
3623 // bool operator<=(T, T);
3624 // bool operator>=(T, T);
3625 // bool operator==(T, T);
3626 // bool operator!=(T, T);
3627 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3628 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3629 QualType ParamTypes[2] = { *Ptr, *Ptr };
3630 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3631 }
Mike Stump11289f42009-09-09 15:08:12 +00003632 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003633 = CandidateTypes.enumeration_begin();
3634 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3635 QualType ParamTypes[2] = { *Enum, *Enum };
3636 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3637 }
3638
3639 // Fall through.
3640 isComparison = true;
3641
Douglas Gregord08452f2008-11-19 15:42:04 +00003642 BinaryPlus:
3643 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003644 if (!isComparison) {
3645 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3646
3647 // C++ [over.built]p13:
3648 //
3649 // For every cv-qualified or cv-unqualified object type T
3650 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003651 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003652 // T* operator+(T*, ptrdiff_t);
3653 // T& operator[](T*, ptrdiff_t); [BELOW]
3654 // T* operator-(T*, ptrdiff_t);
3655 // T* operator+(ptrdiff_t, T*);
3656 // T& operator[](ptrdiff_t, T*); [BELOW]
3657 //
3658 // C++ [over.built]p14:
3659 //
3660 // For every T, where T is a pointer to object type, there
3661 // exist candidate operator functions of the form
3662 //
3663 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003664 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003665 = CandidateTypes.pointer_begin();
3666 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3667 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3668
3669 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3670 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3671
3672 if (Op == OO_Plus) {
3673 // T* operator+(ptrdiff_t, T*);
3674 ParamTypes[0] = ParamTypes[1];
3675 ParamTypes[1] = *Ptr;
3676 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3677 } else {
3678 // ptrdiff_t operator-(T, T);
3679 ParamTypes[1] = *Ptr;
3680 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3681 Args, 2, CandidateSet);
3682 }
3683 }
3684 }
3685 // Fall through
3686
Douglas Gregora11693b2008-11-12 17:17:38 +00003687 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003688 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003689 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003690 // C++ [over.built]p12:
3691 //
3692 // For every pair of promoted arithmetic types L and R, there
3693 // exist candidate operator functions of the form
3694 //
3695 // LR operator*(L, R);
3696 // LR operator/(L, R);
3697 // LR operator+(L, R);
3698 // LR operator-(L, R);
3699 // bool operator<(L, R);
3700 // bool operator>(L, R);
3701 // bool operator<=(L, R);
3702 // bool operator>=(L, R);
3703 // bool operator==(L, R);
3704 // bool operator!=(L, R);
3705 //
3706 // where LR is the result of the usual arithmetic conversions
3707 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003708 //
3709 // C++ [over.built]p24:
3710 //
3711 // For every pair of promoted arithmetic types L and R, there exist
3712 // candidate operator functions of the form
3713 //
3714 // LR operator?(bool, L, R);
3715 //
3716 // where LR is the result of the usual arithmetic conversions
3717 // between types L and R.
3718 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003719 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003720 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003721 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003722 Right < LastPromotedArithmeticType; ++Right) {
3723 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003724 QualType Result
3725 = isComparison
3726 ? Context.BoolTy
3727 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003728 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3729 }
3730 }
3731 break;
3732
3733 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003734 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003735 case OO_Caret:
3736 case OO_Pipe:
3737 case OO_LessLess:
3738 case OO_GreaterGreater:
3739 // C++ [over.built]p17:
3740 //
3741 // For every pair of promoted integral types L and R, there
3742 // exist candidate operator functions of the form
3743 //
3744 // LR operator%(L, R);
3745 // LR operator&(L, R);
3746 // LR operator^(L, R);
3747 // LR operator|(L, R);
3748 // L operator<<(L, R);
3749 // L operator>>(L, R);
3750 //
3751 // where LR is the result of the usual arithmetic conversions
3752 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003753 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003754 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003755 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003756 Right < LastPromotedIntegralType; ++Right) {
3757 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3758 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3759 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003760 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003761 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3762 }
3763 }
3764 break;
3765
3766 case OO_Equal:
3767 // C++ [over.built]p20:
3768 //
3769 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003770 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003771 // empty, there exist candidate operator functions of the form
3772 //
3773 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003774 for (BuiltinCandidateTypeSet::iterator
3775 Enum = CandidateTypes.enumeration_begin(),
3776 EnumEnd = CandidateTypes.enumeration_end();
3777 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003778 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003779 CandidateSet);
3780 for (BuiltinCandidateTypeSet::iterator
3781 MemPtr = CandidateTypes.member_pointer_begin(),
3782 MemPtrEnd = CandidateTypes.member_pointer_end();
3783 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003784 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003785 CandidateSet);
3786 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003787
3788 case OO_PlusEqual:
3789 case OO_MinusEqual:
3790 // C++ [over.built]p19:
3791 //
3792 // For every pair (T, VQ), where T is any type and VQ is either
3793 // volatile or empty, there exist candidate operator functions
3794 // of the form
3795 //
3796 // T*VQ& operator=(T*VQ&, T*);
3797 //
3798 // C++ [over.built]p21:
3799 //
3800 // For every pair (T, VQ), where T is a cv-qualified or
3801 // cv-unqualified object type and VQ is either volatile or
3802 // empty, there exist candidate operator functions of the form
3803 //
3804 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3805 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3806 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3807 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3808 QualType ParamTypes[2];
3809 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3810
3811 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003812 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003813 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3814 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003815
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003816 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3817 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003818 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003819 ParamTypes[0]
3820 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003821 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3822 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003823 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003824 }
3825 // Fall through.
3826
3827 case OO_StarEqual:
3828 case OO_SlashEqual:
3829 // C++ [over.built]p18:
3830 //
3831 // For every triple (L, VQ, R), where L is an arithmetic type,
3832 // VQ is either volatile or empty, and R is a promoted
3833 // arithmetic type, there exist candidate operator functions of
3834 // the form
3835 //
3836 // VQ L& operator=(VQ L&, R);
3837 // VQ L& operator*=(VQ L&, R);
3838 // VQ L& operator/=(VQ L&, R);
3839 // VQ L& operator+=(VQ L&, R);
3840 // VQ L& operator-=(VQ L&, R);
3841 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003842 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003843 Right < LastPromotedArithmeticType; ++Right) {
3844 QualType ParamTypes[2];
3845 ParamTypes[1] = ArithmeticTypes[Right];
3846
3847 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003848 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003849 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3850 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003851
3852 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003853 if (VisibleTypeConversionsQuals.hasVolatile()) {
3854 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3855 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3856 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3857 /*IsAssigmentOperator=*/Op == OO_Equal);
3858 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003859 }
3860 }
3861 break;
3862
3863 case OO_PercentEqual:
3864 case OO_LessLessEqual:
3865 case OO_GreaterGreaterEqual:
3866 case OO_AmpEqual:
3867 case OO_CaretEqual:
3868 case OO_PipeEqual:
3869 // C++ [over.built]p22:
3870 //
3871 // For every triple (L, VQ, R), where L is an integral type, VQ
3872 // is either volatile or empty, and R is a promoted integral
3873 // type, there exist candidate operator functions of the form
3874 //
3875 // VQ L& operator%=(VQ L&, R);
3876 // VQ L& operator<<=(VQ L&, R);
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 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003882 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003883 Right < LastPromotedIntegralType; ++Right) {
3884 QualType ParamTypes[2];
3885 ParamTypes[1] = ArithmeticTypes[Right];
3886
3887 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003888 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003889 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003890 if (VisibleTypeConversionsQuals.hasVolatile()) {
3891 // Add this built-in operator as a candidate (VQ is 'volatile').
3892 ParamTypes[0] = ArithmeticTypes[Left];
3893 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3894 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3895 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3896 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003897 }
3898 }
3899 break;
3900
Douglas Gregord08452f2008-11-19 15:42:04 +00003901 case OO_Exclaim: {
3902 // C++ [over.operator]p23:
3903 //
3904 // There also exist candidate operator functions of the form
3905 //
Mike Stump11289f42009-09-09 15:08:12 +00003906 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003907 // bool operator&&(bool, bool); [BELOW]
3908 // bool operator||(bool, bool); [BELOW]
3909 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003910 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3911 /*IsAssignmentOperator=*/false,
3912 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003913 break;
3914 }
3915
Douglas Gregora11693b2008-11-12 17:17:38 +00003916 case OO_AmpAmp:
3917 case OO_PipePipe: {
3918 // C++ [over.operator]p23:
3919 //
3920 // There also exist candidate operator functions of the form
3921 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003922 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003923 // bool operator&&(bool, bool);
3924 // bool operator||(bool, bool);
3925 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003926 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3927 /*IsAssignmentOperator=*/false,
3928 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003929 break;
3930 }
3931
3932 case OO_Subscript:
3933 // C++ [over.built]p13:
3934 //
3935 // For every cv-qualified or cv-unqualified object type T there
3936 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003937 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003938 // T* operator+(T*, ptrdiff_t); [ABOVE]
3939 // T& operator[](T*, ptrdiff_t);
3940 // T* operator-(T*, ptrdiff_t); [ABOVE]
3941 // T* operator+(ptrdiff_t, T*); [ABOVE]
3942 // T& operator[](ptrdiff_t, T*);
3943 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3944 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3945 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003946 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003947 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003948
3949 // T& operator[](T*, ptrdiff_t)
3950 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3951
3952 // T& operator[](ptrdiff_t, T*);
3953 ParamTypes[0] = ParamTypes[1];
3954 ParamTypes[1] = *Ptr;
3955 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3956 }
3957 break;
3958
3959 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003960 // C++ [over.built]p11:
3961 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3962 // C1 is the same type as C2 or is a derived class of C2, T is an object
3963 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3964 // there exist candidate operator functions of the form
3965 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3966 // where CV12 is the union of CV1 and CV2.
3967 {
3968 for (BuiltinCandidateTypeSet::iterator Ptr =
3969 CandidateTypes.pointer_begin();
3970 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3971 QualType C1Ty = (*Ptr);
3972 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003973 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003974 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003975 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003976 if (!isa<RecordType>(C1))
3977 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003978 // heuristic to reduce number of builtin candidates in the set.
3979 // Add volatile/restrict version only if there are conversions to a
3980 // volatile/restrict type.
3981 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3982 continue;
3983 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3984 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003985 }
3986 for (BuiltinCandidateTypeSet::iterator
3987 MemPtr = CandidateTypes.member_pointer_begin(),
3988 MemPtrEnd = CandidateTypes.member_pointer_end();
3989 MemPtr != MemPtrEnd; ++MemPtr) {
3990 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3991 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00003992 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003993 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3994 break;
3995 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3996 // build CV12 T&
3997 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003998 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3999 T.isVolatileQualified())
4000 continue;
4001 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4002 T.isRestrictQualified())
4003 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004004 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004005 QualType ResultTy = Context.getLValueReferenceType(T);
4006 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4007 }
4008 }
4009 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004010 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004011
4012 case OO_Conditional:
4013 // Note that we don't consider the first argument, since it has been
4014 // contextually converted to bool long ago. The candidates below are
4015 // therefore added as binary.
4016 //
4017 // C++ [over.built]p24:
4018 // For every type T, where T is a pointer or pointer-to-member type,
4019 // there exist candidate operator functions of the form
4020 //
4021 // T operator?(bool, T, T);
4022 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004023 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4024 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4025 QualType ParamTypes[2] = { *Ptr, *Ptr };
4026 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4027 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004028 for (BuiltinCandidateTypeSet::iterator Ptr =
4029 CandidateTypes.member_pointer_begin(),
4030 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4031 QualType ParamTypes[2] = { *Ptr, *Ptr };
4032 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4033 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004034 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004035 }
4036}
4037
Douglas Gregore254f902009-02-04 00:32:51 +00004038/// \brief Add function candidates found via argument-dependent lookup
4039/// to the set of overloading candidates.
4040///
4041/// This routine performs argument-dependent name lookup based on the
4042/// given function name (which may also be an operator name) and adds
4043/// all of the overload candidates found by ADL to the overload
4044/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004045void
Douglas Gregore254f902009-02-04 00:32:51 +00004046Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4047 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004048 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004049 OverloadCandidateSet& CandidateSet,
4050 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004051 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00004052
Douglas Gregorcabea402009-09-22 15:41:20 +00004053 // FIXME: Should we be trafficking in canonical function decls throughout?
4054
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004055 // Record all of the function candidates that we've already
4056 // added to the overload set, so that we don't add those same
4057 // candidates a second time.
4058 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4059 CandEnd = CandidateSet.end();
4060 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004061 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004062 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004063 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4064 Functions.insert(FunTmpl);
4065 }
Douglas Gregore254f902009-02-04 00:32:51 +00004066
Douglas Gregorcabea402009-09-22 15:41:20 +00004067 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00004068 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00004069
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004070 // Erase all of the candidates we already knew about.
4071 // FIXME: This is suboptimal. Is there a better way?
4072 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4073 CandEnd = CandidateSet.end();
4074 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004075 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004076 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004077 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4078 Functions.erase(FunTmpl);
4079 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004080
4081 // For each of the ADL candidates we found, add it to the overload
4082 // set.
4083 for (FunctionSet::iterator Func = Functions.begin(),
4084 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00004085 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004086 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCall6b51f282009-11-23 01:53:49 +00004087 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004088 continue;
4089
4090 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4091 false, false, PartialOverloading);
4092 } else
Mike Stump11289f42009-09-09 15:08:12 +00004093 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00004094 ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004095 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004096 }
Douglas Gregore254f902009-02-04 00:32:51 +00004097}
4098
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004099/// isBetterOverloadCandidate - Determines whether the first overload
4100/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004101bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004102Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00004103 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004104 // Define viable functions to be better candidates than non-viable
4105 // functions.
4106 if (!Cand2.Viable)
4107 return Cand1.Viable;
4108 else if (!Cand1.Viable)
4109 return false;
4110
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004111 // C++ [over.match.best]p1:
4112 //
4113 // -- if F is a static member function, ICS1(F) is defined such
4114 // that ICS1(F) is neither better nor worse than ICS1(G) for
4115 // any function G, and, symmetrically, ICS1(G) is neither
4116 // better nor worse than ICS1(F).
4117 unsigned StartArg = 0;
4118 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4119 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004120
Douglas Gregord3cb3562009-07-07 23:38:56 +00004121 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004122 // A viable function F1 is defined to be a better function than another
4123 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004124 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004125 unsigned NumArgs = Cand1.Conversions.size();
4126 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4127 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004128 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004129 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4130 Cand2.Conversions[ArgIdx])) {
4131 case ImplicitConversionSequence::Better:
4132 // Cand1 has a better conversion sequence.
4133 HasBetterConversion = true;
4134 break;
4135
4136 case ImplicitConversionSequence::Worse:
4137 // Cand1 can't be better than Cand2.
4138 return false;
4139
4140 case ImplicitConversionSequence::Indistinguishable:
4141 // Do nothing.
4142 break;
4143 }
4144 }
4145
Mike Stump11289f42009-09-09 15:08:12 +00004146 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004147 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004148 if (HasBetterConversion)
4149 return true;
4150
Mike Stump11289f42009-09-09 15:08:12 +00004151 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004152 // specialization, or, if not that,
4153 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4154 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4155 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004156
4157 // -- F1 and F2 are function template specializations, and the function
4158 // template for F1 is more specialized than the template for F2
4159 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004160 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004161 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4162 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004163 if (FunctionTemplateDecl *BetterTemplate
4164 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4165 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004166 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4167 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004168 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004169
Douglas Gregora1f013e2008-11-07 22:36:19 +00004170 // -- the context is an initialization by user-defined conversion
4171 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4172 // from the return type of F1 to the destination type (i.e.,
4173 // the type of the entity being initialized) is a better
4174 // conversion sequence than the standard conversion sequence
4175 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004176 if (Cand1.Function && Cand2.Function &&
4177 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004178 isa<CXXConversionDecl>(Cand2.Function)) {
4179 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4180 Cand2.FinalConversion)) {
4181 case ImplicitConversionSequence::Better:
4182 // Cand1 has a better conversion sequence.
4183 return true;
4184
4185 case ImplicitConversionSequence::Worse:
4186 // Cand1 can't be better than Cand2.
4187 return false;
4188
4189 case ImplicitConversionSequence::Indistinguishable:
4190 // Do nothing
4191 break;
4192 }
4193 }
4194
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004195 return false;
4196}
4197
Mike Stump11289f42009-09-09 15:08:12 +00004198/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004199/// within an overload candidate set.
4200///
4201/// \param CandidateSet the set of candidate functions.
4202///
4203/// \param Loc the location of the function name (or operator symbol) for
4204/// which overload resolution occurs.
4205///
Mike Stump11289f42009-09-09 15:08:12 +00004206/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004207/// function, Best points to the candidate function found.
4208///
4209/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004210OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4211 SourceLocation Loc,
4212 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004213 // Find the best viable function.
4214 Best = CandidateSet.end();
4215 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4216 Cand != CandidateSet.end(); ++Cand) {
4217 if (Cand->Viable) {
4218 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4219 Best = Cand;
4220 }
4221 }
4222
4223 // If we didn't find any viable functions, abort.
4224 if (Best == CandidateSet.end())
4225 return OR_No_Viable_Function;
4226
4227 // Make sure that this function is better than every other viable
4228 // function. If not, we have an ambiguity.
4229 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4230 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004231 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004232 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004233 !isBetterOverloadCandidate(*Best, *Cand)) {
4234 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004235 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004236 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004237 }
Mike Stump11289f42009-09-09 15:08:12 +00004238
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004239 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004240 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004241 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004242 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004243 return OR_Deleted;
4244
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004245 // C++ [basic.def.odr]p2:
4246 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004247 // when referred to from a potentially-evaluated expression. [Note: this
4248 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004249 // (clause 13), user-defined conversions (12.3.2), allocation function for
4250 // placement new (5.3.4), as well as non-default initialization (8.5).
4251 if (Best->Function)
4252 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004253 return OR_Success;
4254}
4255
4256/// PrintOverloadCandidates - When overload resolution fails, prints
4257/// diagnostic messages containing the candidates in the candidate
4258/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00004259void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004260Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004261 bool OnlyViable,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004262 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004263 SourceLocation OpLoc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004264 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4265 LastCand = CandidateSet.end();
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004266 bool Reported = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004267 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004268 if (Cand->Viable || !OnlyViable) {
4269 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004270 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004271 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004272 // Deleted or "unavailable" function.
4273 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4274 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00004275 } else if (FunctionTemplateDecl *FunTmpl
4276 = Cand->Function->getPrimaryTemplate()) {
4277 // Function template specialization
4278 // FIXME: Give a better reason!
4279 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4280 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4281 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00004282 } else {
4283 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00004284 bool errReported = false;
4285 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4286 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4287 const ImplicitConversionSequence &Conversion =
4288 Cand->Conversions[i];
4289 if ((Conversion.ConversionKind !=
4290 ImplicitConversionSequence::BadConversion) ||
4291 Conversion.ConversionFunctionSet.size() == 0)
4292 continue;
4293 Diag(Cand->Function->getLocation(),
4294 diag::err_ovl_candidate_not_viable) << (i+1);
4295 errReported = true;
4296 for (int j = Conversion.ConversionFunctionSet.size()-1;
4297 j >= 0; j--) {
4298 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4299 Diag(Func->getLocation(), diag::err_ovl_candidate);
4300 }
4301 }
4302 }
4303 if (!errReported)
4304 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004305 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004306 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004307 // Desugar the type of the surrogate down to a function type,
4308 // retaining as many typedefs as possible while still showing
4309 // the function type (and, therefore, its parameter types).
4310 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004311 bool isLValueReference = false;
4312 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004313 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004314 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004315 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004316 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004317 isLValueReference = true;
4318 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004319 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004320 FnType = FnTypeRef->getPointeeType();
4321 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004322 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004323 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004324 FnType = FnTypePtr->getPointeeType();
4325 isPointer = true;
4326 }
4327 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00004328 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004329 // Reconstruct the pointer/reference as appropriate.
4330 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004331 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4332 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004333
Douglas Gregorab7897a2008-11-19 22:57:39 +00004334 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004335 << FnType;
Douglas Gregor66950a32009-09-30 21:46:01 +00004336 } else if (OnlyViable) {
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004337 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanian0fe5e032009-10-09 17:09:58 +00004338 "builtin-binary-operator-not-binary");
Fariborz Jahanian956127d2009-10-16 23:25:02 +00004339 std::string TypeStr("operator");
4340 TypeStr += Opc;
4341 TypeStr += "(";
4342 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4343 if (Cand->Conversions.size() == 1) {
4344 TypeStr += ")";
4345 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4346 }
4347 else {
4348 TypeStr += ", ";
4349 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4350 TypeStr += ")";
4351 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4352 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004353 }
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004354 else if (!Cand->Viable && !Reported) {
4355 // Non-viability might be due to ambiguous user-defined conversions,
4356 // needed for built-in operators. Report them as well, but only once
4357 // as we have typically many built-in candidates.
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004358 unsigned NoOperands = Cand->Conversions.size();
4359 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004360 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4361 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4362 ICS.ConversionFunctionSet.empty())
4363 continue;
4364 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4365 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4366 QualType FromTy =
4367 QualType(
4368 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4369 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4370 << FromTy << Func->getConversionType();
4371 }
4372 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4373 FunctionDecl *Func =
4374 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4375 Diag(Func->getLocation(),diag::err_ovl_candidate);
4376 }
4377 }
4378 Reported = true;
4379 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004380 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004381 }
4382}
4383
Douglas Gregorcd695e52008-11-10 20:40:00 +00004384/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4385/// an overloaded function (C++ [over.over]), where @p From is an
4386/// expression with overloaded function type and @p ToType is the type
4387/// we're trying to resolve to. For example:
4388///
4389/// @code
4390/// int f(double);
4391/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004392///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004393/// int (*pfd)(double) = f; // selects f(double)
4394/// @endcode
4395///
4396/// This routine returns the resulting FunctionDecl if it could be
4397/// resolved, and NULL otherwise. When @p Complain is true, this
4398/// routine will emit diagnostics if there is an error.
4399FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004400Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004401 bool Complain) {
4402 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004403 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004404 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004405 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004406 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004407 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004408 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004409 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004410 FunctionType = MemTypePtr->getPointeeType();
4411 IsMember = true;
4412 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004413
4414 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004415 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004416 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004417 return 0;
4418
4419 // Find the actual overloaded function declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004420
Douglas Gregorcd695e52008-11-10 20:40:00 +00004421 // C++ [over.over]p1:
4422 // [...] [Note: any redundant set of parentheses surrounding the
4423 // overloaded function name is ignored (5.1). ]
4424 Expr *OvlExpr = From->IgnoreParens();
4425
4426 // C++ [over.over]p1:
4427 // [...] The overloaded function name can be preceded by the &
4428 // operator.
4429 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4430 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4431 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4432 }
4433
Anders Carlssonb68b0282009-10-20 22:53:47 +00004434 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004435 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCalld14a8642009-11-21 08:51:07 +00004436
4437 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004438
John McCall10eae182009-11-30 22:42:35 +00004439 // Look into the overloaded expression.
John McCalle66edc12009-11-24 19:00:30 +00004440 if (UnresolvedLookupExpr *UL
John McCalld14a8642009-11-21 08:51:07 +00004441 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4442 Fns.append(UL->decls_begin(), UL->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00004443 if (UL->hasExplicitTemplateArgs()) {
4444 HasExplicitTemplateArgs = true;
4445 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4446 }
John McCall10eae182009-11-30 22:42:35 +00004447 } else if (UnresolvedMemberExpr *ME
4448 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4449 Fns.append(ME->decls_begin(), ME->decls_end());
4450 if (ME->hasExplicitTemplateArgs()) {
4451 HasExplicitTemplateArgs = true;
John McCall6b51f282009-11-23 01:53:49 +00004452 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004453 }
Douglas Gregor9b146582009-07-08 20:55:45 +00004454 }
Mike Stump11289f42009-09-09 15:08:12 +00004455
John McCalld14a8642009-11-21 08:51:07 +00004456 // If we didn't actually find anything, we're done.
4457 if (Fns.empty())
4458 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004459
Douglas Gregorcd695e52008-11-10 20:40:00 +00004460 // Look through all of the overloaded functions, searching for one
4461 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004462 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004463 bool FoundNonTemplateFunction = false;
John McCalld14a8642009-11-21 08:51:07 +00004464 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4465 E = Fns.end(); I != E; ++I) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004466 // C++ [over.over]p3:
4467 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004468 // targets of type "pointer-to-function" or "reference-to-function."
4469 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004470 // type "pointer-to-member-function."
4471 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004472
Mike Stump11289f42009-09-09 15:08:12 +00004473 if (FunctionTemplateDecl *FunctionTemplate
John McCalld14a8642009-11-21 08:51:07 +00004474 = dyn_cast<FunctionTemplateDecl>(*I)) {
Mike Stump11289f42009-09-09 15:08:12 +00004475 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004476 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004477 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004478 // static when converting to member pointer.
4479 if (Method->isStatic() == IsMember)
4480 continue;
4481 } else if (IsMember)
4482 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004483
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004484 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004485 // If the name is a function template, template argument deduction is
4486 // done (14.8.2.2), and if the argument deduction succeeds, the
4487 // resulting template argument list is used to generate a single
4488 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004489 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004490 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004491 FunctionDecl *Specialization = 0;
4492 TemplateDeductionInfo Info(Context);
4493 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004494 = DeduceTemplateArguments(FunctionTemplate,
4495 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor9b146582009-07-08 20:55:45 +00004496 FunctionType, Specialization, Info)) {
4497 // FIXME: make a note of the failed deduction for diagnostics.
4498 (void)Result;
4499 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004500 // FIXME: If the match isn't exact, shouldn't we just drop this as
4501 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004502 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004503 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004504 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004505 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004506 }
John McCalld14a8642009-11-21 08:51:07 +00004507
4508 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00004509 }
Mike Stump11289f42009-09-09 15:08:12 +00004510
John McCalld14a8642009-11-21 08:51:07 +00004511 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004512 // Skip non-static functions when converting to pointer, and static
4513 // when converting to member pointer.
4514 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004515 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004516
4517 // If we have explicit template arguments, skip non-templates.
4518 if (HasExplicitTemplateArgs)
4519 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004520 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004521 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004522
John McCalld14a8642009-11-21 08:51:07 +00004523 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*I)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00004524 QualType ResultTy;
4525 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4526 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4527 ResultTy)) {
John McCalld14a8642009-11-21 08:51:07 +00004528 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004529 FoundNonTemplateFunction = true;
4530 }
Mike Stump11289f42009-09-09 15:08:12 +00004531 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004532 }
4533
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004534 // If there were 0 or 1 matches, we're done.
4535 if (Matches.empty())
4536 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004537 else if (Matches.size() == 1) {
4538 FunctionDecl *Result = *Matches.begin();
4539 MarkDeclarationReferenced(From->getLocStart(), Result);
4540 return Result;
4541 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004542
4543 // C++ [over.over]p4:
4544 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004545 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004546 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004547 // [...] and any given function template specialization F1 is
4548 // eliminated if the set contains a second function template
4549 // specialization whose function template is more specialized
4550 // than the function template of F1 according to the partial
4551 // ordering rules of 14.5.5.2.
4552
4553 // The algorithm specified above is quadratic. We instead use a
4554 // two-pass algorithm (similar to the one used to identify the
4555 // best viable function in an overload set) that identifies the
4556 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004557 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004558 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004559 FunctionDecl *Result =
4560 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4561 TPOC_Other, From->getLocStart(),
4562 PDiag(),
4563 PDiag(diag::err_addr_ovl_ambiguous)
4564 << TemplateMatches[0]->getDeclName(),
4565 PDiag(diag::err_ovl_template_candidate));
4566 MarkDeclarationReferenced(From->getLocStart(), Result);
4567 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004568 }
Mike Stump11289f42009-09-09 15:08:12 +00004569
Douglas Gregorfae1d712009-09-26 03:56:17 +00004570 // [...] any function template specializations in the set are
4571 // eliminated if the set also contains a non-template function, [...]
4572 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4573 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4574 if ((*M)->getPrimaryTemplate() == 0)
4575 RemainingMatches.push_back(*M);
4576
Mike Stump11289f42009-09-09 15:08:12 +00004577 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004578 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004579 if (RemainingMatches.size() == 1) {
4580 FunctionDecl *Result = RemainingMatches.front();
4581 MarkDeclarationReferenced(From->getLocStart(), Result);
4582 return Result;
4583 }
Mike Stump11289f42009-09-09 15:08:12 +00004584
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004585 // FIXME: We should probably return the same thing that BestViableFunction
4586 // returns (even if we issue the diagnostics here).
4587 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4588 << RemainingMatches[0]->getDeclName();
4589 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4590 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004591 return 0;
4592}
4593
Douglas Gregorcabea402009-09-22 15:41:20 +00004594/// \brief Add a single candidate to the overload set.
4595static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00004596 NamedDecl *Callee,
John McCall6b51f282009-11-23 01:53:49 +00004597 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004598 Expr **Args, unsigned NumArgs,
4599 OverloadCandidateSet &CandidateSet,
4600 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004601 if (isa<UsingShadowDecl>(Callee))
4602 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4603
Douglas Gregorcabea402009-09-22 15:41:20 +00004604 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004605 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorcabea402009-09-22 15:41:20 +00004606 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4607 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004608 return;
John McCalld14a8642009-11-21 08:51:07 +00004609 }
4610
4611 if (FunctionTemplateDecl *FuncTemplate
4612 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004613 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004614 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00004615 return;
4616 }
4617
4618 assert(false && "unhandled case in overloaded call candidate");
4619
4620 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00004621}
4622
4623/// \brief Add the overload candidates named by callee and/or found by argument
4624/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00004625void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00004626 Expr **Args, unsigned NumArgs,
4627 OverloadCandidateSet &CandidateSet,
4628 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004629
4630#ifndef NDEBUG
4631 // Verify that ArgumentDependentLookup is consistent with the rules
4632 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00004633 //
Douglas Gregorcabea402009-09-22 15:41:20 +00004634 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4635 // and let Y be the lookup set produced by argument dependent
4636 // lookup (defined as follows). If X contains
4637 //
4638 // -- a declaration of a class member, or
4639 //
4640 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00004641 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00004642 //
4643 // -- a declaration that is neither a function or a function
4644 // template
4645 //
4646 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00004647
John McCall57500772009-12-16 12:17:52 +00004648 if (ULE->requiresADL()) {
4649 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
4650 E = ULE->decls_end(); I != E; ++I) {
4651 assert(!(*I)->getDeclContext()->isRecord());
4652 assert(isa<UsingShadowDecl>(*I) ||
4653 !(*I)->getDeclContext()->isFunctionOrMethod());
4654 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00004655 }
4656 }
4657#endif
4658
John McCall57500772009-12-16 12:17:52 +00004659 // It would be nice to avoid this copy.
4660 TemplateArgumentListInfo TABuffer;
4661 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
4662 if (ULE->hasExplicitTemplateArgs()) {
4663 ULE->copyTemplateArgumentsInto(TABuffer);
4664 ExplicitTemplateArgs = &TABuffer;
4665 }
4666
4667 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
4668 E = ULE->decls_end(); I != E; ++I)
John McCall6b51f282009-11-23 01:53:49 +00004669 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004670 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00004671 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00004672
John McCall57500772009-12-16 12:17:52 +00004673 if (ULE->requiresADL())
4674 AddArgumentDependentLookupCandidates(ULE->getName(), Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004675 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004676 CandidateSet,
4677 PartialOverloading);
4678}
John McCalld681c392009-12-16 08:11:27 +00004679
John McCall57500772009-12-16 12:17:52 +00004680static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
4681 Expr **Args, unsigned NumArgs) {
4682 Fn->Destroy(SemaRef.Context);
4683 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4684 Args[Arg]->Destroy(SemaRef.Context);
4685 return SemaRef.ExprError();
4686}
4687
John McCalld681c392009-12-16 08:11:27 +00004688/// Attempts to recover from a call where no functions were found.
4689///
4690/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00004691static Sema::OwningExprResult
4692BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
4693 UnresolvedLookupExpr *ULE,
4694 SourceLocation LParenLoc,
4695 Expr **Args, unsigned NumArgs,
4696 SourceLocation *CommaLocs,
4697 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00004698
4699 CXXScopeSpec SS;
4700 if (ULE->getQualifier()) {
4701 SS.setScopeRep(ULE->getQualifier());
4702 SS.setRange(ULE->getQualifierRange());
4703 }
4704
John McCall57500772009-12-16 12:17:52 +00004705 TemplateArgumentListInfo TABuffer;
4706 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
4707 if (ULE->hasExplicitTemplateArgs()) {
4708 ULE->copyTemplateArgumentsInto(TABuffer);
4709 ExplicitTemplateArgs = &TABuffer;
4710 }
4711
John McCalld681c392009-12-16 08:11:27 +00004712 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
4713 Sema::LookupOrdinaryName);
4714 if (SemaRef.DiagnoseEmptyLookup(SS, R))
John McCall57500772009-12-16 12:17:52 +00004715 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00004716
John McCall57500772009-12-16 12:17:52 +00004717 assert(!R.empty() && "lookup results empty despite recovery");
4718
4719 // Build an implicit member call if appropriate. Just drop the
4720 // casts and such from the call, we don't really care.
4721 Sema::OwningExprResult NewFn = SemaRef.ExprError();
4722 if ((*R.begin())->isCXXClassMember())
4723 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
4724 else if (ExplicitTemplateArgs)
4725 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
4726 else
4727 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
4728
4729 if (NewFn.isInvalid())
4730 return Destroy(SemaRef, Fn, Args, NumArgs);
4731
4732 Fn->Destroy(SemaRef.Context);
4733
4734 // This shouldn't cause an infinite loop because we're giving it
4735 // an expression with non-empty lookup results, which should never
4736 // end up here.
4737 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
4738 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
4739 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00004740}
Douglas Gregorcabea402009-09-22 15:41:20 +00004741
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004742/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004743/// (which eventually refers to the declaration Func) and the call
4744/// arguments Args/NumArgs, attempt to resolve the function call down
4745/// to a specific function. If overload resolution succeeds, returns
4746/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004747/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004748/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00004749Sema::OwningExprResult
4750Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
4751 SourceLocation LParenLoc,
4752 Expr **Args, unsigned NumArgs,
4753 SourceLocation *CommaLocs,
4754 SourceLocation RParenLoc) {
4755#ifndef NDEBUG
4756 if (ULE->requiresADL()) {
4757 // To do ADL, we must have found an unqualified name.
4758 assert(!ULE->getQualifier() && "qualified name with ADL");
4759
4760 // We don't perform ADL for implicit declarations of builtins.
4761 // Verify that this was correctly set up.
4762 FunctionDecl *F;
4763 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
4764 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
4765 F->getBuiltinID() && F->isImplicit())
4766 assert(0 && "performing ADL for builtin");
4767
4768 // We don't perform ADL in C.
4769 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
4770 }
4771#endif
4772
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004773 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004774
John McCall57500772009-12-16 12:17:52 +00004775 // Add the functions denoted by the callee to the set of candidate
4776 // functions, including those from argument-dependent lookup.
4777 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00004778
4779 // If we found nothing, try to recover.
4780 // AddRecoveryCallCandidates diagnoses the error itself, so we just
4781 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00004782 if (CandidateSet.empty())
4783 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
4784 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00004785
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004786 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004787 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00004788 case OR_Success: {
4789 FunctionDecl *FDecl = Best->Function;
4790 Fn = FixOverloadedFunctionReference(Fn, FDecl);
4791 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
4792 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004793
4794 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004795 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004796 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00004797 << ULE->getName() << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004798 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4799 break;
4800
4801 case OR_Ambiguous:
4802 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00004803 << ULE->getName() << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004804 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4805 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004806
4807 case OR_Deleted:
4808 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4809 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00004810 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00004811 << Fn->getSourceRange();
4812 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4813 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004814 }
4815
4816 // Overload resolution failed. Destroy all of the subexpressions and
4817 // return NULL.
4818 Fn->Destroy(Context);
4819 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4820 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00004821 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004822}
4823
John McCall283b9012009-11-22 00:44:51 +00004824static bool IsOverloaded(const Sema::FunctionSet &Functions) {
4825 return Functions.size() > 1 ||
4826 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
4827}
4828
Douglas Gregor084d8552009-03-13 23:49:33 +00004829/// \brief Create a unary operation that may resolve to an overloaded
4830/// operator.
4831///
4832/// \param OpLoc The location of the operator itself (e.g., '*').
4833///
4834/// \param OpcIn The UnaryOperator::Opcode that describes this
4835/// operator.
4836///
4837/// \param Functions The set of non-member functions that will be
4838/// considered by overload resolution. The caller needs to build this
4839/// set based on the context using, e.g.,
4840/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4841/// set should not contain any member functions; those will be added
4842/// by CreateOverloadedUnaryOp().
4843///
4844/// \param input The input argument.
4845Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4846 unsigned OpcIn,
4847 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004848 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004849 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4850 Expr *Input = (Expr *)input.get();
4851
4852 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4853 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4854 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4855
4856 Expr *Args[2] = { Input, 0 };
4857 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004858
Douglas Gregor084d8552009-03-13 23:49:33 +00004859 // For post-increment and post-decrement, add the implicit '0' as
4860 // the second argument, so that we know this is a post-increment or
4861 // post-decrement.
4862 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4863 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004864 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004865 SourceLocation());
4866 NumArgs = 2;
4867 }
4868
4869 if (Input->isTypeDependent()) {
John McCalld14a8642009-11-21 08:51:07 +00004870 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00004871 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4872 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00004873 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump11289f42009-09-09 15:08:12 +00004874 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004875 FuncEnd = Functions.end();
4876 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00004877 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00004878
Douglas Gregor084d8552009-03-13 23:49:33 +00004879 input.release();
4880 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4881 &Args[0], NumArgs,
4882 Context.DependentTy,
4883 OpLoc));
4884 }
4885
4886 // Build an empty overload set.
4887 OverloadCandidateSet CandidateSet;
4888
4889 // Add the candidates from the given function set.
4890 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4891
4892 // Add operator candidates that are member functions.
4893 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4894
4895 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004896 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00004897
4898 // Perform overload resolution.
4899 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004900 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004901 case OR_Success: {
4902 // We found a built-in operator or an overloaded operator.
4903 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004904
Douglas Gregor084d8552009-03-13 23:49:33 +00004905 if (FnDecl) {
4906 // We matched an overloaded operator. Build a call to that
4907 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004908
Douglas Gregor084d8552009-03-13 23:49:33 +00004909 // Convert the arguments.
4910 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4911 if (PerformObjectArgumentInitialization(Input, Method))
4912 return ExprError();
4913 } else {
4914 // Convert the arguments.
4915 if (PerformCopyInitialization(Input,
4916 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004917 AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00004918 return ExprError();
4919 }
4920
4921 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004922 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004923
Douglas Gregor084d8552009-03-13 23:49:33 +00004924 // Build the actual expression node.
4925 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4926 SourceLocation());
4927 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004928
Douglas Gregor084d8552009-03-13 23:49:33 +00004929 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00004930 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004931 ExprOwningPtr<CallExpr> TheCall(this,
4932 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00004933 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004934
4935 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4936 FnDecl))
4937 return ExprError();
4938
4939 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00004940 } else {
4941 // We matched a built-in operator. Convert the arguments, then
4942 // break out so that we will build the appropriate built-in
4943 // operator node.
4944 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004945 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00004946 return ExprError();
4947
4948 break;
4949 }
4950 }
4951
4952 case OR_No_Viable_Function:
4953 // No viable function; fall through to handling this as a
4954 // built-in operator, which will produce an error message for us.
4955 break;
4956
4957 case OR_Ambiguous:
4958 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4959 << UnaryOperator::getOpcodeStr(Opc)
4960 << Input->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004961 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4962 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00004963 return ExprError();
4964
4965 case OR_Deleted:
4966 Diag(OpLoc, diag::err_ovl_deleted_oper)
4967 << Best->Function->isDeleted()
4968 << UnaryOperator::getOpcodeStr(Opc)
4969 << Input->getSourceRange();
4970 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4971 return ExprError();
4972 }
4973
4974 // Either we found no viable overloaded operator or we matched a
4975 // built-in operator. In either case, fall through to trying to
4976 // build a built-in operation.
4977 input.release();
4978 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4979}
4980
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004981/// \brief Create a binary operation that may resolve to an overloaded
4982/// operator.
4983///
4984/// \param OpLoc The location of the operator itself (e.g., '+').
4985///
4986/// \param OpcIn The BinaryOperator::Opcode that describes this
4987/// operator.
4988///
4989/// \param Functions The set of non-member functions that will be
4990/// considered by overload resolution. The caller needs to build this
4991/// set based on the context using, e.g.,
4992/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4993/// set should not contain any member functions; those will be added
4994/// by CreateOverloadedBinOp().
4995///
4996/// \param LHS Left-hand argument.
4997/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004998Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004999Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005000 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005001 FunctionSet &Functions,
5002 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005003 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005004 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005005
5006 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5007 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5008 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5009
5010 // If either side is type-dependent, create an appropriate dependent
5011 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005012 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005013 if (Functions.empty()) {
5014 // If there are no functions to store, just build a dependent
5015 // BinaryOperator or CompoundAssignment.
5016 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5017 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5018 Context.DependentTy, OpLoc));
5019
5020 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5021 Context.DependentTy,
5022 Context.DependentTy,
5023 Context.DependentTy,
5024 OpLoc));
5025 }
5026
John McCalld14a8642009-11-21 08:51:07 +00005027 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005028 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5029 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00005030 /* ADL */ true, IsOverloaded(Functions));
John McCalld14a8642009-11-21 08:51:07 +00005031
Mike Stump11289f42009-09-09 15:08:12 +00005032 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005033 FuncEnd = Functions.end();
5034 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00005035 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00005036
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005037 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00005038 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005039 Context.DependentTy,
5040 OpLoc));
5041 }
5042
5043 // If this is the .* operator, which is not overloadable, just
5044 // create a built-in binary operator.
5045 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00005046 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005047
Sebastian Redl6a96bf72009-11-18 23:10:33 +00005048 // If this is the assignment operator, we only perform overload resolution
5049 // if the left-hand side is a class or enumeration type. This is actually
5050 // a hack. The standard requires that we do overload resolution between the
5051 // various built-in candidates, but as DR507 points out, this can lead to
5052 // problems. So we do it this way, which pretty much follows what GCC does.
5053 // Note that we go the traditional code path for compound assignment forms.
5054 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00005055 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005056
Douglas Gregor084d8552009-03-13 23:49:33 +00005057 // Build an empty overload set.
5058 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005059
5060 // Add the candidates from the given function set.
5061 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
5062
5063 // Add operator candidates that are member functions.
5064 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5065
5066 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005067 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005068
5069 // Perform overload resolution.
5070 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005071 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005072 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005073 // We found a built-in operator or an overloaded operator.
5074 FunctionDecl *FnDecl = Best->Function;
5075
5076 if (FnDecl) {
5077 // We matched an overloaded operator. Build a call to that
5078 // operator.
5079
5080 // Convert the arguments.
5081 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00005082 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5083 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005084 AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005085 return ExprError();
5086 } else {
5087 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00005088 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005089 AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00005090 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005091 AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005092 return ExprError();
5093 }
5094
5095 // Determine the result type
5096 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00005097 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005098 ResultTy = ResultTy.getNonReferenceType();
5099
5100 // Build the actual expression node.
5101 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00005102 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005103 UsualUnaryConversions(FnExpr);
5104
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005105 ExprOwningPtr<CXXOperatorCallExpr>
5106 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5107 Args, 2, ResultTy,
5108 OpLoc));
5109
5110 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5111 FnDecl))
5112 return ExprError();
5113
5114 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005115 } else {
5116 // We matched a built-in operator. Convert the arguments, then
5117 // break out so that we will build the appropriate built-in
5118 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00005119 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005120 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00005121 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005122 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005123 return ExprError();
5124
5125 break;
5126 }
5127 }
5128
Douglas Gregor66950a32009-09-30 21:46:01 +00005129 case OR_No_Viable_Function: {
5130 // C++ [over.match.oper]p9:
5131 // If the operator is the operator , [...] and there are no
5132 // viable functions, then the operator is assumed to be the
5133 // built-in operator and interpreted according to clause 5.
5134 if (Opc == BinaryOperator::Comma)
5135 break;
5136
Sebastian Redl027de2a2009-05-21 11:50:50 +00005137 // For class as left operand for assignment or compound assigment operator
5138 // do not fall through to handling in built-in, but report that no overloaded
5139 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005140 OwningExprResult Result = ExprError();
5141 if (Args[0]->getType()->isRecordType() &&
5142 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005143 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5144 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005145 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005146 } else {
5147 // No viable function; try to create a built-in operation, which will
5148 // produce an error. Then, show the non-viable candidates.
5149 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005150 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005151 assert(Result.isInvalid() &&
5152 "C++ binary operator overloading is missing candidates!");
5153 if (Result.isInvalid())
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005154 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5155 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005156 return move(Result);
5157 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005158
5159 case OR_Ambiguous:
5160 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5161 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005162 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005163 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5164 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005165 return ExprError();
5166
5167 case OR_Deleted:
5168 Diag(OpLoc, diag::err_ovl_deleted_oper)
5169 << Best->Function->isDeleted()
5170 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005171 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005172 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5173 return ExprError();
5174 }
5175
Douglas Gregor66950a32009-09-30 21:46:01 +00005176 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005177 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005178}
5179
Sebastian Redladba46e2009-10-29 20:17:01 +00005180Action::OwningExprResult
5181Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5182 SourceLocation RLoc,
5183 ExprArg Base, ExprArg Idx) {
5184 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5185 static_cast<Expr*>(Idx.get()) };
5186 DeclarationName OpName =
5187 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5188
5189 // If either side is type-dependent, create an appropriate dependent
5190 // expression.
5191 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5192
John McCalld14a8642009-11-21 08:51:07 +00005193 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005194 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5195 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005196 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005197 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005198
5199 Base.release();
5200 Idx.release();
5201 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5202 Args, 2,
5203 Context.DependentTy,
5204 RLoc));
5205 }
5206
5207 // Build an empty overload set.
5208 OverloadCandidateSet CandidateSet;
5209
5210 // Subscript can only be overloaded as a member function.
5211
5212 // Add operator candidates that are member functions.
5213 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5214
5215 // Add builtin operator candidates.
5216 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5217
5218 // Perform overload resolution.
5219 OverloadCandidateSet::iterator Best;
5220 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5221 case OR_Success: {
5222 // We found a built-in operator or an overloaded operator.
5223 FunctionDecl *FnDecl = Best->Function;
5224
5225 if (FnDecl) {
5226 // We matched an overloaded operator. Build a call to that
5227 // operator.
5228
5229 // Convert the arguments.
5230 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5231 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5232 PerformCopyInitialization(Args[1],
5233 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005234 AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005235 return ExprError();
5236
5237 // Determine the result type
5238 QualType ResultTy
5239 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5240 ResultTy = ResultTy.getNonReferenceType();
5241
5242 // Build the actual expression node.
5243 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5244 LLoc);
5245 UsualUnaryConversions(FnExpr);
5246
5247 Base.release();
5248 Idx.release();
5249 ExprOwningPtr<CXXOperatorCallExpr>
5250 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5251 FnExpr, Args, 2,
5252 ResultTy, RLoc));
5253
5254 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5255 FnDecl))
5256 return ExprError();
5257
5258 return MaybeBindToTemporary(TheCall.release());
5259 } else {
5260 // We matched a built-in operator. Convert the arguments, then
5261 // break out so that we will build the appropriate built-in
5262 // operator node.
5263 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005264 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00005265 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005266 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005267 return ExprError();
5268
5269 break;
5270 }
5271 }
5272
5273 case OR_No_Viable_Function: {
5274 // No viable function; try to create a built-in operation, which will
5275 // produce an error. Then, show the non-viable candidates.
5276 OwningExprResult Result =
5277 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5278 assert(Result.isInvalid() &&
5279 "C++ subscript operator overloading is missing candidates!");
5280 if (Result.isInvalid())
5281 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5282 "[]", LLoc);
5283 return move(Result);
5284 }
5285
5286 case OR_Ambiguous:
5287 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5288 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5289 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5290 "[]", LLoc);
5291 return ExprError();
5292
5293 case OR_Deleted:
5294 Diag(LLoc, diag::err_ovl_deleted_oper)
5295 << Best->Function->isDeleted() << "[]"
5296 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5297 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5298 return ExprError();
5299 }
5300
5301 // We matched a built-in operator; build it.
5302 Base.release();
5303 Idx.release();
5304 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5305 Owned(Args[1]), RLoc);
5306}
5307
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005308/// BuildCallToMemberFunction - Build a call to a member
5309/// function. MemExpr is the expression that refers to the member
5310/// function (and includes the object parameter), Args/NumArgs are the
5311/// arguments to the function call (not including the object
5312/// parameter). The caller needs to validate that the member
5313/// expression refers to a member function or an overloaded member
5314/// function.
John McCall2d74de92009-12-01 22:10:20 +00005315Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005316Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5317 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005318 unsigned NumArgs, SourceLocation *CommaLocs,
5319 SourceLocation RParenLoc) {
5320 // Dig out the member expression. This holds both the object
5321 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00005322 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5323
John McCall10eae182009-11-30 22:42:35 +00005324 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005325 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00005326 if (isa<MemberExpr>(NakedMemExpr)) {
5327 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00005328 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5329 } else {
5330 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCall2d74de92009-12-01 22:10:20 +00005331
John McCall6e9f8f62009-12-03 04:06:58 +00005332 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00005333
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005334 // Add overload candidates
5335 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00005336
John McCall2d74de92009-12-01 22:10:20 +00005337 // FIXME: avoid copy.
5338 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5339 if (UnresExpr->hasExplicitTemplateArgs()) {
5340 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5341 TemplateArgs = &TemplateArgsBuffer;
5342 }
5343
John McCall10eae182009-11-30 22:42:35 +00005344 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5345 E = UnresExpr->decls_end(); I != E; ++I) {
5346
John McCall6e9f8f62009-12-03 04:06:58 +00005347 NamedDecl *Func = *I;
5348 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5349 if (isa<UsingShadowDecl>(Func))
5350 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5351
John McCall10eae182009-11-30 22:42:35 +00005352 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00005353 // If explicit template arguments were provided, we can't call a
5354 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00005355 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00005356 continue;
5357
John McCall6e9f8f62009-12-03 04:06:58 +00005358 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5359 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005360 } else {
John McCall10eae182009-11-30 22:42:35 +00005361 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall6e9f8f62009-12-03 04:06:58 +00005362 ActingDC, TemplateArgs,
5363 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005364 CandidateSet,
5365 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005366 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005367 }
Mike Stump11289f42009-09-09 15:08:12 +00005368
John McCall10eae182009-11-30 22:42:35 +00005369 DeclarationName DeclName = UnresExpr->getMemberName();
5370
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005371 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00005372 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005373 case OR_Success:
5374 Method = cast<CXXMethodDecl>(Best->Function);
5375 break;
5376
5377 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00005378 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005379 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005380 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005381 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5382 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005383 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005384
5385 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00005386 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005387 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005388 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5389 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005390 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005391
5392 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00005393 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00005394 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005395 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005396 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5397 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005398 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005399 }
5400
Douglas Gregor51c538b2009-11-20 19:42:02 +00005401 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00005402
John McCall2d74de92009-12-01 22:10:20 +00005403 // If overload resolution picked a static member, build a
5404 // non-member call based on that function.
5405 if (Method->isStatic()) {
5406 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5407 Args, NumArgs, RParenLoc);
5408 }
5409
John McCall10eae182009-11-30 22:42:35 +00005410 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005411 }
5412
5413 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005414 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00005415 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005416 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005417 Method->getResultType().getNonReferenceType(),
5418 RParenLoc));
5419
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005420 // Check for a valid return type.
5421 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5422 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00005423 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005424
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005425 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00005426 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00005427 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005428 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCall2d74de92009-12-01 22:10:20 +00005429 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005430 MemExpr->setBase(ObjectArg);
5431
5432 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005433 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005434 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005435 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00005436 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005437
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005438 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00005439 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00005440
John McCall2d74de92009-12-01 22:10:20 +00005441 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005442}
5443
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005444/// BuildCallToObjectOfClassType - Build a call to an object of class
5445/// type (C++ [over.call.object]), which can end up invoking an
5446/// overloaded function call operator (@c operator()) or performing a
5447/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005448Sema::ExprResult
5449Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005450 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005451 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005452 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005453 SourceLocation RParenLoc) {
5454 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005455 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005456
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005457 // C++ [over.call.object]p1:
5458 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005459 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005460 // candidate functions includes at least the function call
5461 // operators of T. The function call operators of T are obtained by
5462 // ordinary lookup of the name operator() in the context of
5463 // (E).operator().
5464 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005465 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005466
5467 if (RequireCompleteType(LParenLoc, Object->getType(),
5468 PartialDiagnostic(diag::err_incomplete_object_call)
5469 << Object->getSourceRange()))
5470 return true;
5471
John McCall27b18f82009-11-17 02:14:36 +00005472 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5473 LookupQualifiedName(R, Record->getDecl());
5474 R.suppressDiagnostics();
5475
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005476 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00005477 Oper != OperEnd; ++Oper) {
John McCall6e9f8f62009-12-03 04:06:58 +00005478 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005479 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005480 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005481
Douglas Gregorab7897a2008-11-19 22:57:39 +00005482 // C++ [over.call.object]p2:
5483 // In addition, for each conversion function declared in T of the
5484 // form
5485 //
5486 // operator conversion-type-id () cv-qualifier;
5487 //
5488 // where cv-qualifier is the same cv-qualification as, or a
5489 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005490 // denotes the type "pointer to function of (P1,...,Pn) returning
5491 // R", or the type "reference to pointer to function of
5492 // (P1,...,Pn) returning R", or the type "reference to function
5493 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005494 // is also considered as a candidate function. Similarly,
5495 // surrogate call functions are added to the set of candidate
5496 // functions for each conversion function declared in an
5497 // accessible base class provided the function is not hidden
5498 // within T by another intervening declaration.
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005499 // FIXME: Look in base classes for more conversion operators!
John McCalld14a8642009-11-21 08:51:07 +00005500 const UnresolvedSet *Conversions
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005501 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00005502 for (UnresolvedSet::iterator I = Conversions->begin(),
5503 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00005504 NamedDecl *D = *I;
5505 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5506 if (isa<UsingShadowDecl>(D))
5507 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5508
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005509 // Skip over templated conversion functions; they aren't
5510 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00005511 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005512 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005513
John McCall6e9f8f62009-12-03 04:06:58 +00005514 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00005515
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005516 // Strip the reference type (if any) and then the pointer type (if
5517 // any) to get down to what might be a function type.
5518 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5519 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5520 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005521
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005522 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall6e9f8f62009-12-03 04:06:58 +00005523 AddSurrogateCandidate(Conv, ActingContext, Proto,
5524 Object->getType(), Args, NumArgs,
5525 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005526 }
Mike Stump11289f42009-09-09 15:08:12 +00005527
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005528 // Perform overload resolution.
5529 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005530 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005531 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005532 // Overload resolution succeeded; we'll build the appropriate call
5533 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005534 break;
5535
5536 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005537 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00005538 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00005539 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00005540 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005541 break;
5542
5543 case OR_Ambiguous:
5544 Diag(Object->getSourceRange().getBegin(),
5545 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005546 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005547 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5548 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005549
5550 case OR_Deleted:
5551 Diag(Object->getSourceRange().getBegin(),
5552 diag::err_ovl_deleted_object_call)
5553 << Best->Function->isDeleted()
5554 << Object->getType() << Object->getSourceRange();
5555 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5556 break;
Mike Stump11289f42009-09-09 15:08:12 +00005557 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005558
Douglas Gregorab7897a2008-11-19 22:57:39 +00005559 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005560 // We had an error; delete all of the subexpressions and return
5561 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005562 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005563 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005564 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005565 return true;
5566 }
5567
Douglas Gregorab7897a2008-11-19 22:57:39 +00005568 if (Best->Function == 0) {
5569 // Since there is no function declaration, this is one of the
5570 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00005571 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00005572 = cast<CXXConversionDecl>(
5573 Best->Conversions[0].UserDefined.ConversionFunction);
5574
5575 // We selected one of the surrogate functions that converts the
5576 // object parameter to a function pointer. Perform the conversion
5577 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005578
5579 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005580 // and then call it.
Eli Friedmana958a012009-12-09 04:52:43 +00005581 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005582
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005583 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005584 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5585 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005586 }
5587
5588 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5589 // that calls this method, using Object for the implicit object
5590 // parameter and passing along the remaining arguments.
5591 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00005592 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005593
5594 unsigned NumArgsInProto = Proto->getNumArgs();
5595 unsigned NumArgsToCheck = NumArgs;
5596
5597 // Build the full argument list for the method call (the
5598 // implicit object parameter is placed at the beginning of the
5599 // list).
5600 Expr **MethodArgs;
5601 if (NumArgs < NumArgsInProto) {
5602 NumArgsToCheck = NumArgsInProto;
5603 MethodArgs = new Expr*[NumArgsInProto + 1];
5604 } else {
5605 MethodArgs = new Expr*[NumArgs + 1];
5606 }
5607 MethodArgs[0] = Object;
5608 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5609 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00005610
5611 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00005612 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005613 UsualUnaryConversions(NewFn);
5614
5615 // Once we've built TheCall, all of the expressions are properly
5616 // owned.
5617 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005618 ExprOwningPtr<CXXOperatorCallExpr>
5619 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005620 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005621 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005622 delete [] MethodArgs;
5623
Anders Carlsson3d5829c2009-10-13 21:49:31 +00005624 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5625 Method))
5626 return true;
5627
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005628 // We may have default arguments. If so, we need to allocate more
5629 // slots in the call for them.
5630 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005631 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005632 else if (NumArgs > NumArgsInProto)
5633 NumArgsToCheck = NumArgsInProto;
5634
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005635 bool IsError = false;
5636
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005637 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005638 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005639 TheCall->setArg(0, Object);
5640
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005641
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005642 // Check the argument types.
5643 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005644 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005645 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005646 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00005647
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005648 // Pass the argument.
5649 QualType ProtoArgType = Proto->getArgType(i);
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005650 IsError |= PerformCopyInitialization(Arg, ProtoArgType, AA_Passing);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005651 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00005652 OwningExprResult DefArg
5653 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5654 if (DefArg.isInvalid()) {
5655 IsError = true;
5656 break;
5657 }
5658
5659 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005660 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005661
5662 TheCall->setArg(i + 1, Arg);
5663 }
5664
5665 // If this is a variadic call, handle args passed through "...".
5666 if (Proto->isVariadic()) {
5667 // Promote the arguments (C99 6.5.2.2p7).
5668 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5669 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005670 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005671 TheCall->setArg(i + 1, Arg);
5672 }
5673 }
5674
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005675 if (IsError) return true;
5676
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005677 if (CheckFunctionCall(Method, TheCall.get()))
5678 return true;
5679
Anders Carlsson1c83deb2009-08-16 03:53:54 +00005680 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005681}
5682
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005683/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00005684/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005685/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00005686Sema::OwningExprResult
5687Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5688 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005689 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00005690
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005691 // C++ [over.ref]p1:
5692 //
5693 // [...] An expression x->m is interpreted as (x.operator->())->m
5694 // for a class object x of type T if T::operator->() exists and if
5695 // the operator is selected as the best match function by the
5696 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005697 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5698 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005699 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00005700
Eli Friedman132e70b2009-11-18 01:28:03 +00005701 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5702 PDiag(diag::err_typecheck_incomplete_tag)
5703 << Base->getSourceRange()))
5704 return ExprError();
5705
John McCall27b18f82009-11-17 02:14:36 +00005706 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5707 LookupQualifiedName(R, BaseRecord->getDecl());
5708 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00005709
5710 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00005711 Oper != OperEnd; ++Oper) {
5712 NamedDecl *D = *Oper;
5713 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5714 if (isa<UsingShadowDecl>(D))
5715 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5716
5717 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
5718 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005719 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00005720 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005721
5722 // Perform overload resolution.
5723 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005724 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005725 case OR_Success:
5726 // Overload resolution succeeded; we'll build the call below.
5727 break;
5728
5729 case OR_No_Viable_Function:
5730 if (CandidateSet.empty())
5731 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00005732 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005733 else
5734 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00005735 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005736 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00005737 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005738
5739 case OR_Ambiguous:
5740 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005741 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005742 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005743 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005744
5745 case OR_Deleted:
5746 Diag(OpLoc, diag::err_ovl_deleted_oper)
5747 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005748 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005749 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005750 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005751 }
5752
5753 // Convert the object parameter.
5754 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005755 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005756 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005757
5758 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005759 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005760
5761 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005762 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5763 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005764 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005765
5766 QualType ResultTy = Method->getResultType().getNonReferenceType();
5767 ExprOwningPtr<CXXOperatorCallExpr>
5768 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5769 &Base, 1, ResultTy, OpLoc));
5770
5771 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5772 Method))
5773 return ExprError();
5774 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005775}
5776
Douglas Gregorcd695e52008-11-10 20:40:00 +00005777/// FixOverloadedFunctionReference - E is an expression that refers to
5778/// a C++ overloaded function (possibly with some parentheses and
5779/// perhaps a '&' around it). We have resolved the overloaded function
5780/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005781/// refer (possibly indirectly) to Fn. Returns the new expr.
5782Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005783 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00005784 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5785 if (SubExpr == PE->getSubExpr())
5786 return PE->Retain();
5787
5788 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
5789 }
5790
5791 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5792 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00005793 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00005794 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00005795 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00005796 if (SubExpr == ICE->getSubExpr())
5797 return ICE->Retain();
5798
5799 return new (Context) ImplicitCastExpr(ICE->getType(),
5800 ICE->getCastKind(),
5801 SubExpr,
5802 ICE->isLvalueCast());
5803 }
5804
5805 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005806 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005807 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005808 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5809 if (Method->isStatic()) {
5810 // Do nothing: static member functions aren't any different
5811 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00005812 } else {
John McCalle66edc12009-11-24 19:00:30 +00005813 // Fix the sub expression, which really has to be an
5814 // UnresolvedLookupExpr holding an overloaded member function
5815 // or template.
John McCalld14a8642009-11-21 08:51:07 +00005816 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5817 if (SubExpr == UnOp->getSubExpr())
5818 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00005819
John McCalld14a8642009-11-21 08:51:07 +00005820 assert(isa<DeclRefExpr>(SubExpr)
5821 && "fixed to something other than a decl ref");
5822 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
5823 && "fixed to a member ref with no nested name qualifier");
5824
5825 // We have taken the address of a pointer to member
5826 // function. Perform the computation here so that we get the
5827 // appropriate pointer to member type.
5828 QualType ClassType
5829 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5830 QualType MemPtrType
5831 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
5832
5833 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5834 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005835 }
5836 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00005837 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5838 if (SubExpr == UnOp->getSubExpr())
5839 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005840
Douglas Gregor51c538b2009-11-20 19:42:02 +00005841 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5842 Context.getPointerType(SubExpr->getType()),
5843 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00005844 }
John McCalld14a8642009-11-21 08:51:07 +00005845
5846 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00005847 // FIXME: avoid copy.
5848 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00005849 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00005850 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
5851 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00005852 }
5853
John McCalld14a8642009-11-21 08:51:07 +00005854 return DeclRefExpr::Create(Context,
5855 ULE->getQualifier(),
5856 ULE->getQualifierRange(),
5857 Fn,
5858 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00005859 Fn->getType(),
5860 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00005861 }
5862
John McCall10eae182009-11-30 22:42:35 +00005863 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00005864 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00005865 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5866 if (MemExpr->hasExplicitTemplateArgs()) {
5867 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5868 TemplateArgs = &TemplateArgsBuffer;
5869 }
John McCall6b51f282009-11-23 01:53:49 +00005870
John McCall2d74de92009-12-01 22:10:20 +00005871 Expr *Base;
5872
5873 // If we're filling in
5874 if (MemExpr->isImplicitAccess()) {
5875 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
5876 return DeclRefExpr::Create(Context,
5877 MemExpr->getQualifier(),
5878 MemExpr->getQualifierRange(),
5879 Fn,
5880 MemExpr->getMemberLoc(),
5881 Fn->getType(),
5882 TemplateArgs);
5883 } else
5884 Base = new (Context) CXXThisExpr(SourceLocation(),
5885 MemExpr->getBaseType());
5886 } else
5887 Base = MemExpr->getBase()->Retain();
5888
5889 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00005890 MemExpr->isArrow(),
5891 MemExpr->getQualifier(),
5892 MemExpr->getQualifierRange(),
5893 Fn,
John McCall6b51f282009-11-23 01:53:49 +00005894 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00005895 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00005896 Fn->getType());
5897 }
5898
Douglas Gregor51c538b2009-11-20 19:42:02 +00005899 assert(false && "Invalid reference to overloaded function");
5900 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00005901}
5902
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005903Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
5904 FunctionDecl *Fn) {
5905 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
5906}
5907
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005908} // end namespace clang