blob: d406dd47c7b946d8ffd65bf5285b08e4b1005ce4 [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"
Douglas Gregor39c16d42008-10-24 04:54:22 +000015#include "SemaInherit.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"
19#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000023#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000025#include "llvm/Support/Compiler.h"
26#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,
41 ICC_Qualification_Adjustment,
42 ICC_Promotion,
43 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000044 ICC_Promotion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000047 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000052 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000053 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000054 ICC_Conversion
55 };
56 return Category[(int)Kind];
57}
58
59/// GetConversionRank - Retrieve the implicit conversion rank
60/// corresponding to the given implicit conversion kind.
61ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
62 static const ImplicitConversionRank
63 Rank[(int)ICK_Num_Conversion_Kinds] = {
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Promotion,
70 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000071 ICR_Promotion,
72 ICR_Conversion,
73 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000074 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000079 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000080 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000081 ICR_Conversion
82 };
83 return Rank[(int)Kind];
84}
85
86/// GetImplicitConversionName - Return the name of this kind of
87/// implicit conversion.
88const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
89 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
90 "No conversion",
91 "Lvalue-to-rvalue",
92 "Array-to-pointer",
93 "Function-to-pointer",
94 "Qualification",
95 "Integral promotion",
96 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +000097 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000098 "Integral conversion",
99 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000102 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000103 "Pointer conversion",
104 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000105 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000106 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000107 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 };
109 return Name[Kind];
110}
111
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000112/// StandardConversionSequence - Set the standard conversion
113/// sequence to the identity conversion.
114void StandardConversionSequence::setAsIdentityConversion() {
115 First = ICK_Identity;
116 Second = ICK_Identity;
117 Third = ICK_Identity;
118 Deprecated = false;
119 ReferenceBinding = false;
120 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000121 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000122 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000123}
124
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000125/// getRank - Retrieve the rank of this standard conversion sequence
126/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
127/// implicit conversions.
128ImplicitConversionRank StandardConversionSequence::getRank() const {
129 ImplicitConversionRank Rank = ICR_Exact_Match;
130 if (GetConversionRank(First) > Rank)
131 Rank = GetConversionRank(First);
132 if (GetConversionRank(Second) > Rank)
133 Rank = GetConversionRank(Second);
134 if (GetConversionRank(Third) > Rank)
135 Rank = GetConversionRank(Third);
136 return Rank;
137}
138
139/// isPointerConversionToBool - Determines whether this conversion is
140/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000141/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000142/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000143bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000144 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
145 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
146
147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
151 if (ToType->isBooleanType() &&
Douglas Gregor033f56d2008-12-23 00:53:59 +0000152 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregor5c407d92008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000163bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregor5c407d92008-10-23 00:40:37 +0000166 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
175 if (Second == ICK_Pointer_Conversion)
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
185 bool PrintedSomething = false;
186 if (First != ICK_Identity) {
187 fprintf(stderr, "%s", GetImplicitConversionName(First));
188 PrintedSomething = true;
189 }
190
191 if (Second != ICK_Identity) {
192 if (PrintedSomething) {
193 fprintf(stderr, " -> ");
194 }
195 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor2fe98832008-11-03 19:09:14 +0000196
197 if (CopyConstructor) {
198 fprintf(stderr, " (by copy constructor)");
199 } else if (DirectBinding) {
200 fprintf(stderr, " (direct reference binding)");
201 } else if (ReferenceBinding) {
202 fprintf(stderr, " (reference binding)");
203 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000204 PrintedSomething = true;
205 }
206
207 if (Third != ICK_Identity) {
208 if (PrintedSomething) {
209 fprintf(stderr, " -> ");
210 }
211 fprintf(stderr, "%s", GetImplicitConversionName(Third));
212 PrintedSomething = true;
213 }
214
215 if (!PrintedSomething) {
216 fprintf(stderr, "No conversions required");
217 }
218}
219
220/// DebugPrint - Print this user-defined conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void UserDefinedConversionSequence::DebugPrint() const {
223 if (Before.First || Before.Second || Before.Third) {
224 Before.DebugPrint();
225 fprintf(stderr, " -> ");
226 }
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 if (After.First || After.Second || After.Third) {
229 fprintf(stderr, " -> ");
230 After.DebugPrint();
231 }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237 switch (ConversionKind) {
238 case StandardConversion:
239 fprintf(stderr, "Standard conversion: ");
240 Standard.DebugPrint();
241 break;
242 case UserDefinedConversion:
243 fprintf(stderr, "User-defined conversion: ");
244 UserDefined.DebugPrint();
245 break;
246 case EllipsisConversion:
247 fprintf(stderr, "Ellipsis conversion");
248 break;
249 case BadConversion:
250 fprintf(stderr, "Bad conversion");
251 break;
252 }
253
254 fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
Mike Stump11289f42009-09-09 15:08:12 +0000263// FunctionDecl that New cannot be overloaded with.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000264//
265// Example: Given the following input:
266//
267// void f(int, float); // #1
268// void f(int, int); // #2
269// int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000272// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000273//
274// When we process #2, Old is a FunctionDecl for #1. By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
Mike Stump11289f42009-09-09 15:08:12 +0000286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000288 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
289 // Is this new function an overload of every function in the
290 // overload set?
291 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
292 FuncEnd = Ovl->function_end();
293 for (; Func != FuncEnd; ++Func) {
294 if (!IsOverload(New, *Func, MatchedDecl)) {
295 MatchedDecl = Func;
296 return false;
297 }
298 }
299
300 // This function overloads every function in the overload set.
301 return true;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000302 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
303 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
304 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregor23061de2009-06-24 16:50:40 +0000305 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
Mike Stump11289f42009-09-09 15:08:12 +0000306 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
307
Douglas Gregor23061de2009-06-24 16:50:40 +0000308 // C++ [temp.fct]p2:
309 // A function template can be overloaded with other function templates
310 // and with normal (non-template) functions.
311 if ((OldTemplate == 0) != (NewTemplate == 0))
312 return true;
313
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000314 // Is the function New an overload of the function Old?
315 QualType OldQType = Context.getCanonicalType(Old->getType());
316 QualType NewQType = Context.getCanonicalType(New->getType());
317
318 // Compare the signatures (C++ 1.3.10) of the two functions to
319 // determine whether they are overloads. If we find any mismatch
320 // in the signature, they are overloads.
321
322 // If either of these functions is a K&R-style function (no
323 // prototype), then we consider them to have matching signatures.
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000324 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
325 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000326 return false;
327
Douglas Gregor23061de2009-06-24 16:50:40 +0000328 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
329 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000330
331 // The signature of a function includes the types of its
332 // parameters (C++ 1.3.10), which includes the presence or absence
333 // of the ellipsis; see C++ DR 357).
334 if (OldQType != NewQType &&
335 (OldType->getNumArgs() != NewType->getNumArgs() ||
336 OldType->isVariadic() != NewType->isVariadic() ||
337 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
338 NewType->arg_type_begin())))
339 return true;
340
Douglas Gregor23061de2009-06-24 16:50:40 +0000341 // C++ [temp.over.link]p4:
Mike Stump11289f42009-09-09 15:08:12 +0000342 // The signature of a function template consists of its function
Douglas Gregor23061de2009-06-24 16:50:40 +0000343 // signature, its return type and its template parameter list. The names
344 // of the template parameters are significant only for establishing the
Mike Stump11289f42009-09-09 15:08:12 +0000345 // relationship between the template parameters and the rest of the
Douglas Gregor23061de2009-06-24 16:50:40 +0000346 // signature.
347 //
348 // We check the return type and template parameter lists for function
349 // templates first; the remaining checks follow.
350 if (NewTemplate &&
Mike Stump11289f42009-09-09 15:08:12 +0000351 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
352 OldTemplate->getTemplateParameters(),
Douglas Gregor23061de2009-06-24 16:50:40 +0000353 false, false, SourceLocation()) ||
354 OldType->getResultType() != NewType->getResultType()))
355 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000356
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000357 // If the function is a class member, its signature includes the
358 // cv-qualifiers (if any) on the function itself.
359 //
360 // As part of this, also check whether one of the member functions
361 // is static, in which case they are not overloads (C++
362 // 13.1p2). While not part of the definition of the signature,
363 // this check is important to determine whether these functions
364 // can be overloaded.
365 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
366 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Mike Stump11289f42009-09-09 15:08:12 +0000367 if (OldMethod && NewMethod &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000368 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb81897c2008-11-21 15:36:28 +0000369 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000370 return true;
371
372 // The signatures match; this is not an overload.
373 return false;
374 } else {
375 // (C++ 13p1):
376 // Only function declarations can be overloaded; object and type
377 // declarations cannot be overloaded.
378 return false;
379 }
380}
381
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000382/// TryImplicitConversion - Attempt to perform an implicit conversion
383/// from the given expression (Expr) to the given type (ToType). This
384/// function returns an implicit conversion sequence that can be used
385/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000386///
387/// void f(float f);
388/// void g(int i) { f(i); }
389///
390/// this routine would produce an implicit conversion sequence to
391/// describe the initialization of f from i, which will be a standard
392/// conversion sequence containing an lvalue-to-rvalue conversion (C++
393/// 4.1) followed by a floating-integral conversion (C++ 4.9).
394//
395/// Note that this routine only determines how the conversion can be
396/// performed; it does not actually perform the conversion. As such,
397/// it will not produce any diagnostics if no conversion is available,
398/// but will instead return an implicit conversion sequence of kind
399/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000400///
401/// If @p SuppressUserConversions, then user-defined conversions are
402/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000403/// If @p AllowExplicit, then explicit user-defined conversions are
404/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000405/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
406/// no matter its actual lvalueness.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000407ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000408Sema::TryImplicitConversion(Expr* From, QualType ToType,
409 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000410 bool AllowExplicit, bool ForceRValue,
Mike Stump11289f42009-09-09 15:08:12 +0000411 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000412 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000413 OverloadCandidateSet Conversions;
Anders Carlsson228eea32009-08-28 15:33:32 +0000414 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000415 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000416 else if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +0000417 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000418 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000419 !SuppressUserConversions, AllowExplicit,
420 ForceRValue)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000421 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000422 // C++ [over.ics.user]p4:
423 // A conversion of an expression of class type to the same class
424 // type is given Exact Match rank, and a conversion of an
425 // expression of class type to a base class of that type is
426 // given Conversion rank, in spite of the fact that a copy
427 // constructor (i.e., a user-defined conversion function) is
428 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000429 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000430 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000431 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000432 = Context.getCanonicalType(From->getType().getUnqualifiedType());
433 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
434 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000435 // Turn this into a "standard" conversion sequence, so that it
436 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000437 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
438 ICS.Standard.setAsIdentityConversion();
439 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
440 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000441 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000442 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000443 ICS.Standard.Second = ICK_Derived_To_Base;
444 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000445 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000446
447 // C++ [over.best.ics]p4:
448 // However, when considering the argument of a user-defined
449 // conversion function that is a candidate by 13.3.1.3 when
450 // invoked for the copying of the temporary in the second step
451 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
452 // 13.3.1.6 in all cases, only standard conversion sequences and
453 // ellipsis conversion sequences are allowed.
454 if (SuppressUserConversions &&
455 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
456 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000457 } else
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000458 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000459
460 return ICS;
461}
462
463/// IsStandardConversion - Determines whether there is a standard
464/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
465/// expression From to the type ToType. Standard conversion sequences
466/// only consider non-class types; for conversions that involve class
467/// types, use TryImplicitConversion. If a conversion exists, SCS will
468/// contain the standard conversion sequence required to perform this
469/// conversion and this routine will return true. Otherwise, this
470/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000471bool
472Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000473 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000474 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000475 QualType FromType = From->getType();
476
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000477 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000478 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000479 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000480 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000481 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000482 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000483
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000484 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000485 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000486 if (FromType->isRecordType() || ToType->isRecordType()) {
487 if (getLangOptions().CPlusPlus)
488 return false;
489
Mike Stump11289f42009-09-09 15:08:12 +0000490 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000491 }
492
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493 // The first conversion can be an lvalue-to-rvalue conversion,
494 // array-to-pointer conversion, or function-to-pointer conversion
495 // (C++ 4p1).
496
Mike Stump11289f42009-09-09 15:08:12 +0000497 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498 // An lvalue (3.10) of a non-function, non-array type T can be
499 // converted to an rvalue.
500 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000501 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000502 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000503 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000504 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505
506 // If T is a non-class type, the type of the rvalue is the
507 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000508 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
509 // just strip the qualifiers because they don't matter.
510
511 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000512 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000513 } else if (FromType->isArrayType()) {
514 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000515 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516
517 // An lvalue or rvalue of type "array of N T" or "array of unknown
518 // bound of T" can be converted to an rvalue of type "pointer to
519 // T" (C++ 4.2p1).
520 FromType = Context.getArrayDecayedType(FromType);
521
522 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
523 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000524 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000525
526 // For the purpose of ranking in overload resolution
527 // (13.3.3.1.1), this conversion is considered an
528 // array-to-pointer conversion followed by a qualification
529 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000530 SCS.Second = ICK_Identity;
531 SCS.Third = ICK_Qualification;
532 SCS.ToTypePtr = ToType.getAsOpaquePtr();
533 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000534 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000535 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
536 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000537 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000538
539 // An lvalue of function type T can be converted to an rvalue of
540 // type "pointer to T." The result is a pointer to the
541 // function. (C++ 4.3p1).
542 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000543 } else if (FunctionDecl *Fn
Douglas Gregorcd695e52008-11-10 20:40:00 +0000544 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000545 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000546 SCS.First = ICK_Function_To_Pointer;
547
548 // We were able to resolve the address of the overloaded function,
549 // so we can convert to the type of that function.
550 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000551 if (ToType->isLValueReferenceType())
552 FromType = Context.getLValueReferenceType(FromType);
553 else if (ToType->isRValueReferenceType())
554 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000555 else if (ToType->isMemberPointerType()) {
556 // Resolve address only succeeds if both sides are member pointers,
557 // but it doesn't have to be the same class. See DR 247.
558 // Note that this means that the type of &Derived::fn can be
559 // Ret (Base::*)(Args) if the fn overload actually found is from the
560 // base class, even if it was brought into the derived class via a
561 // using declaration. The standard isn't clear on this issue at all.
562 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
563 FromType = Context.getMemberPointerType(FromType,
564 Context.getTypeDeclType(M->getParent()).getTypePtr());
565 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000566 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000567 } else {
568 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000569 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000570 }
571
572 // The second conversion can be an integral promotion, floating
573 // point promotion, integral conversion, floating point conversion,
574 // floating-integral conversion, pointer conversion,
575 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000576 // For overloading in C, this can also be a "compatible-type"
577 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000578 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000579 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000580 // The unqualified versions of the types are the same: there's no
581 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000582 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000583 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000584 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000585 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000586 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000587 } else if (IsFloatingPointPromotion(FromType, ToType)) {
588 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000589 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000590 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000591 } else if (IsComplexPromotion(FromType, ToType)) {
592 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000593 SCS.Second = ICK_Complex_Promotion;
594 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000595 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000596 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000597 // Integral conversions (C++ 4.7).
598 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000599 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000600 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000601 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
602 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000603 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000604 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000605 } else if (FromType->isComplexType() && ToType->isComplexType()) {
606 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000607 SCS.Second = ICK_Complex_Conversion;
608 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000609 } else if ((FromType->isFloatingType() &&
610 ToType->isIntegralType() && (!ToType->isBooleanType() &&
611 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000612 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000613 ToType->isFloatingType())) {
614 // Floating-integral conversions (C++ 4.9).
615 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000616 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000617 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000618 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
619 (ToType->isComplexType() && FromType->isArithmeticType())) {
620 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000621 SCS.Second = ICK_Complex_Real;
622 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000623 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
624 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000625 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000626 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000627 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stump12b8ce12009-08-04 21:02:39 +0000628 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
629 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000630 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000631 } else if (ToType->isBooleanType() &&
632 (FromType->isArithmeticType() ||
633 FromType->isEnumeralType() ||
634 FromType->isPointerType() ||
635 FromType->isBlockPointerType() ||
636 FromType->isMemberPointerType() ||
637 FromType->isNullPtrType())) {
638 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000639 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000640 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000641 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000642 Context.typesAreCompatible(ToType, FromType)) {
643 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000644 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000645 } else {
646 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000647 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000648 }
649
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000650 QualType CanonFrom;
651 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000652 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000653 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000654 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000655 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000656 CanonFrom = Context.getCanonicalType(FromType);
657 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000658 } else {
659 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000660 SCS.Third = ICK_Identity;
661
Mike Stump11289f42009-09-09 15:08:12 +0000662 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000663 // [...] Any difference in top-level cv-qualification is
664 // subsumed by the initialization itself and does not constitute
665 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000666 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000667 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000668 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000669 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
670 FromType = ToType;
671 CanonFrom = CanonTo;
672 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000673 }
674
675 // If we have not converted the argument type to the parameter type,
676 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000677 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000678 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000679
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000680 SCS.ToTypePtr = FromType.getAsOpaquePtr();
681 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000682}
683
684/// IsIntegralPromotion - Determines whether the conversion from the
685/// expression From (whose potentially-adjusted type is FromType) to
686/// ToType is an integral promotion (C++ 4.5). If so, returns true and
687/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000688bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000689 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlee547972008-11-04 15:59:10 +0000690 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000691 if (!To) {
692 return false;
693 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000694
695 // An rvalue of type char, signed char, unsigned char, short int, or
696 // unsigned short int can be converted to an rvalue of type int if
697 // int can represent all the values of the source type; otherwise,
698 // the source rvalue can be converted to an rvalue of type unsigned
699 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000700 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000701 if (// We can promote any signed, promotable integer type to an int
702 (FromType->isSignedIntegerType() ||
703 // We can promote any unsigned integer type whose size is
704 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000705 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000706 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000707 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000708 }
709
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000710 return To->getKind() == BuiltinType::UInt;
711 }
712
713 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
714 // can be converted to an rvalue of the first of the following types
715 // that can represent all the values of its underlying type: int,
716 // unsigned int, long, or unsigned long (C++ 4.5p2).
717 if ((FromType->isEnumeralType() || FromType->isWideCharType())
718 && ToType->isIntegerType()) {
719 // Determine whether the type we're converting from is signed or
720 // unsigned.
721 bool FromIsSigned;
722 uint64_t FromSize = Context.getTypeSize(FromType);
723 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
724 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
725 FromIsSigned = UnderlyingType->isSignedIntegerType();
726 } else {
727 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
728 FromIsSigned = true;
729 }
730
731 // The types we'll try to promote to, in the appropriate
732 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000733 QualType PromoteTypes[6] = {
734 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000735 Context.LongTy, Context.UnsignedLongTy ,
736 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000737 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000738 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000739 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
740 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000741 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000742 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
743 // We found the type that we can promote to. If this is the
744 // type we wanted, we have a promotion. Otherwise, no
745 // promotion.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000746 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000747 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
748 }
749 }
750 }
751
752 // An rvalue for an integral bit-field (9.6) can be converted to an
753 // rvalue of type int if int can represent all the values of the
754 // bit-field; otherwise, it can be converted to unsigned int if
755 // unsigned int can represent all the values of the bit-field. If
756 // the bit-field is larger yet, no integral promotion applies to
757 // it. If the bit-field has an enumerated type, it is treated as any
758 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000759 // FIXME: We should delay checking of bit-fields until we actually perform the
760 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000761 using llvm::APSInt;
762 if (From)
763 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000764 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000765 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
766 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
767 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
768 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000769
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000770 // Are we promoting to an int from a bitfield that fits in an int?
771 if (BitWidth < ToSize ||
772 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
773 return To->getKind() == BuiltinType::Int;
774 }
Mike Stump11289f42009-09-09 15:08:12 +0000775
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000776 // Are we promoting to an unsigned int from an unsigned bitfield
777 // that fits into an unsigned int?
778 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
779 return To->getKind() == BuiltinType::UInt;
780 }
Mike Stump11289f42009-09-09 15:08:12 +0000781
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000782 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000783 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000784 }
Mike Stump11289f42009-09-09 15:08:12 +0000785
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000786 // An rvalue of type bool can be converted to an rvalue of type int,
787 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000788 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000789 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000790 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000791
792 return false;
793}
794
795/// IsFloatingPointPromotion - Determines whether the conversion from
796/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
797/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000798bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000799 /// An rvalue of type float can be converted to an rvalue of type
800 /// double. (C++ 4.6p1).
801 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000802 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000803 if (FromBuiltin->getKind() == BuiltinType::Float &&
804 ToBuiltin->getKind() == BuiltinType::Double)
805 return true;
806
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000807 // C99 6.3.1.5p1:
808 // When a float is promoted to double or long double, or a
809 // double is promoted to long double [...].
810 if (!getLangOptions().CPlusPlus &&
811 (FromBuiltin->getKind() == BuiltinType::Float ||
812 FromBuiltin->getKind() == BuiltinType::Double) &&
813 (ToBuiltin->getKind() == BuiltinType::LongDouble))
814 return true;
815 }
816
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000817 return false;
818}
819
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000820/// \brief Determine if a conversion is a complex promotion.
821///
822/// A complex promotion is defined as a complex -> complex conversion
823/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000824/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000825bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
826 const ComplexType *FromComplex = FromType->getAsComplexType();
827 if (!FromComplex)
828 return false;
829
830 const ComplexType *ToComplex = ToType->getAsComplexType();
831 if (!ToComplex)
832 return false;
833
834 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000835 ToComplex->getElementType()) ||
836 IsIntegralPromotion(0, FromComplex->getElementType(),
837 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000838}
839
Douglas Gregor237f96c2008-11-26 23:31:11 +0000840/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
841/// the pointer type FromPtr to a pointer to type ToPointee, with the
842/// same type qualifiers as FromPtr has on its pointee type. ToType,
843/// if non-empty, will be a pointer to ToType that may or may not have
844/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000845static QualType
846BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000847 QualType ToPointee, QualType ToType,
848 ASTContext &Context) {
849 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
850 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
851 unsigned Quals = CanonFromPointee.getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000852
853 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor237f96c2008-11-26 23:31:11 +0000854 if (CanonToPointee.getCVRQualifiers() == Quals) {
855 // ToType is exactly what we need. Return it.
856 if (ToType.getTypePtr())
857 return ToType;
858
859 // Build a pointer to ToPointee. It has the right qualifiers
860 // already.
861 return Context.getPointerType(ToPointee);
862 }
863
864 // Just build a canonical type that has the right qualifiers.
865 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
866}
867
Mike Stump11289f42009-09-09 15:08:12 +0000868static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000869 bool InOverloadResolution,
870 ASTContext &Context) {
871 // Handle value-dependent integral null pointer constants correctly.
872 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
873 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
874 Expr->getType()->isIntegralType())
875 return !InOverloadResolution;
876
877 return Expr->isNullPointerConstant(Context);
878}
Mike Stump11289f42009-09-09 15:08:12 +0000879
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000880/// IsPointerConversion - Determines whether the conversion of the
881/// expression From, which has the (possibly adjusted) type FromType,
882/// can be converted to the type ToType via a pointer conversion (C++
883/// 4.10). If so, returns true and places the converted type (that
884/// might differ from ToType in its cv-qualifiers at some level) into
885/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000886///
Douglas Gregora29dc052008-11-27 01:19:21 +0000887/// This routine also supports conversions to and from block pointers
888/// and conversions with Objective-C's 'id', 'id<protocols...>', and
889/// pointers to interfaces. FIXME: Once we've determined the
890/// appropriate overloading rules for Objective-C, we may want to
891/// split the Objective-C checks into a different routine; however,
892/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000893/// conversions, so for now they live here. IncompatibleObjC will be
894/// set if the conversion is an allowed Objective-C conversion that
895/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000896bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000897 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000898 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000899 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000900 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000901 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
902 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000903
Mike Stump11289f42009-09-09 15:08:12 +0000904 // Conversion from a null pointer constant to any Objective-C pointer type.
905 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000906 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000907 ConvertedType = ToType;
908 return true;
909 }
910
Douglas Gregor231d1c62008-11-27 00:15:41 +0000911 // Blocks: Block pointers can be converted to void*.
912 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000913 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000914 ConvertedType = ToType;
915 return true;
916 }
917 // Blocks: A null pointer constant can be converted to a block
918 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000919 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000920 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000921 ConvertedType = ToType;
922 return true;
923 }
924
Sebastian Redl576fd422009-05-10 18:38:11 +0000925 // If the left-hand-side is nullptr_t, the right side can be a null
926 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000927 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000928 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000929 ConvertedType = ToType;
930 return true;
931 }
932
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000933 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000934 if (!ToTypePtr)
935 return false;
936
937 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000938 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000939 ConvertedType = ToType;
940 return true;
941 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000942
Douglas Gregor237f96c2008-11-26 23:31:11 +0000943 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000944 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000945 if (!FromTypePtr)
946 return false;
947
948 QualType FromPointeeType = FromTypePtr->getPointeeType();
949 QualType ToPointeeType = ToTypePtr->getPointeeType();
950
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000951 // An rvalue of type "pointer to cv T," where T is an object type,
952 // can be converted to an rvalue of type "pointer to cv void" (C++
953 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000954 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000955 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000956 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000957 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000958 return true;
959 }
960
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000961 // When we're overloading in C, we allow a special kind of pointer
962 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +0000963 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000964 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000965 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000966 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +0000967 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000968 return true;
969 }
970
Douglas Gregor5c407d92008-10-23 00:40:37 +0000971 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +0000972 //
Douglas Gregor5c407d92008-10-23 00:40:37 +0000973 // An rvalue of type "pointer to cv D," where D is a class type,
974 // can be converted to an rvalue of type "pointer to cv B," where
975 // B is a base class (clause 10) of D. If B is an inaccessible
976 // (clause 11) or ambiguous (10.2) base class of D, a program that
977 // necessitates this conversion is ill-formed. The result of the
978 // conversion is a pointer to the base class sub-object of the
979 // derived class object. The null pointer value is converted to
980 // the null pointer value of the destination type.
981 //
Douglas Gregor39c16d42008-10-24 04:54:22 +0000982 // Note that we do not check for ambiguity or inaccessibility
983 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000984 if (getLangOptions().CPlusPlus &&
985 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor237f96c2008-11-26 23:31:11 +0000986 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000987 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000988 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000989 ToType, Context);
990 return true;
991 }
Douglas Gregor5c407d92008-10-23 00:40:37 +0000992
Douglas Gregora119f102008-12-19 19:13:09 +0000993 return false;
994}
995
996/// isObjCPointerConversion - Determines whether this is an
997/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
998/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +0000999bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001000 QualType& ConvertedType,
1001 bool &IncompatibleObjC) {
1002 if (!getLangOptions().ObjC1)
1003 return false;
1004
Steve Naroff7cae42b2009-07-10 23:34:53 +00001005 // First, we handle all conversions on ObjC object pointer types.
1006 const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
Mike Stump11289f42009-09-09 15:08:12 +00001007 const ObjCObjectPointerType *FromObjCPtr =
Steve Naroff7cae42b2009-07-10 23:34:53 +00001008 FromType->getAsObjCObjectPointerType();
Douglas Gregora119f102008-12-19 19:13:09 +00001009
Steve Naroff7cae42b2009-07-10 23:34:53 +00001010 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001011 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001012 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001013 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001014 ConvertedType = ToType;
1015 return true;
1016 }
1017 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001018 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001019 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001020 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001021 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001022 ConvertedType = ToType;
1023 return true;
1024 }
1025 // Objective C++: We're able to convert from a pointer to an
1026 // interface to a pointer to a different interface.
1027 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1028 ConvertedType = ToType;
1029 return true;
1030 }
1031
1032 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1033 // Okay: this is some kind of implicit downcast of Objective-C
1034 // interfaces, which is permitted. However, we're going to
1035 // complain about it.
1036 IncompatibleObjC = true;
1037 ConvertedType = FromType;
1038 return true;
1039 }
Mike Stump11289f42009-09-09 15:08:12 +00001040 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001041 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001042 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001043 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001044 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001045 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001046 ToPointeeType = ToBlockPtr->getPointeeType();
1047 else
Douglas Gregora119f102008-12-19 19:13:09 +00001048 return false;
1049
Douglas Gregor033f56d2008-12-23 00:53:59 +00001050 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001051 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001052 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001053 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001054 FromPointeeType = FromBlockPtr->getPointeeType();
1055 else
Douglas Gregora119f102008-12-19 19:13:09 +00001056 return false;
1057
Douglas Gregora119f102008-12-19 19:13:09 +00001058 // If we have pointers to pointers, recursively check whether this
1059 // is an Objective-C conversion.
1060 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1061 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1062 IncompatibleObjC)) {
1063 // We always complain about this conversion.
1064 IncompatibleObjC = true;
1065 ConvertedType = ToType;
1066 return true;
1067 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001068 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001069 // differences in the argument and result types are in Objective-C
1070 // pointer conversions. If so, we permit the conversion (but
1071 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001072 const FunctionProtoType *FromFunctionType
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001073 = FromPointeeType->getAsFunctionProtoType();
1074 const FunctionProtoType *ToFunctionType
1075 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregora119f102008-12-19 19:13:09 +00001076 if (FromFunctionType && ToFunctionType) {
1077 // If the function types are exactly the same, this isn't an
1078 // Objective-C pointer conversion.
1079 if (Context.getCanonicalType(FromPointeeType)
1080 == Context.getCanonicalType(ToPointeeType))
1081 return false;
1082
1083 // Perform the quick checks that will tell us whether these
1084 // function types are obviously different.
1085 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1086 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1087 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1088 return false;
1089
1090 bool HasObjCConversion = false;
1091 if (Context.getCanonicalType(FromFunctionType->getResultType())
1092 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1093 // Okay, the types match exactly. Nothing to do.
1094 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1095 ToFunctionType->getResultType(),
1096 ConvertedType, IncompatibleObjC)) {
1097 // Okay, we have an Objective-C pointer conversion.
1098 HasObjCConversion = true;
1099 } else {
1100 // Function types are too different. Abort.
1101 return false;
1102 }
Mike Stump11289f42009-09-09 15:08:12 +00001103
Douglas Gregora119f102008-12-19 19:13:09 +00001104 // Check argument types.
1105 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1106 ArgIdx != NumArgs; ++ArgIdx) {
1107 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1108 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1109 if (Context.getCanonicalType(FromArgType)
1110 == Context.getCanonicalType(ToArgType)) {
1111 // Okay, the types match exactly. Nothing to do.
1112 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1113 ConvertedType, IncompatibleObjC)) {
1114 // Okay, we have an Objective-C pointer conversion.
1115 HasObjCConversion = true;
1116 } else {
1117 // Argument types are too different. Abort.
1118 return false;
1119 }
1120 }
1121
1122 if (HasObjCConversion) {
1123 // We had an Objective-C conversion. Allow this pointer
1124 // conversion, but complain about it.
1125 ConvertedType = ToType;
1126 IncompatibleObjC = true;
1127 return true;
1128 }
1129 }
1130
Sebastian Redl72b597d2009-01-25 19:43:20 +00001131 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001132}
1133
Douglas Gregor39c16d42008-10-24 04:54:22 +00001134/// CheckPointerConversion - Check the pointer conversion from the
1135/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001136/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001137/// conversions for which IsPointerConversion has already returned
1138/// true. It returns true and produces a diagnostic if there was an
1139/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001140bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1141 CastExpr::CastKind &Kind) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001142 QualType FromType = From->getType();
1143
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001144 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1145 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001146 QualType FromPointeeType = FromPtrType->getPointeeType(),
1147 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001148
Douglas Gregor39c16d42008-10-24 04:54:22 +00001149 if (FromPointeeType->isRecordType() &&
1150 ToPointeeType->isRecordType()) {
1151 // We must have a derived-to-base conversion. Check an
1152 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001153 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1154 From->getExprLoc(),
1155 From->getSourceRange()))
1156 return true;
1157
1158 // The conversion was successful.
1159 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001160 }
1161 }
Mike Stump11289f42009-09-09 15:08:12 +00001162 if (const ObjCObjectPointerType *FromPtrType =
Steve Naroff7cae42b2009-07-10 23:34:53 +00001163 FromType->getAsObjCObjectPointerType())
Mike Stump11289f42009-09-09 15:08:12 +00001164 if (const ObjCObjectPointerType *ToPtrType =
Steve Naroff7cae42b2009-07-10 23:34:53 +00001165 ToType->getAsObjCObjectPointerType()) {
1166 // Objective-C++ conversions are always okay.
1167 // FIXME: We should have a different class of conversions for the
1168 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001169 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001170 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001171
Steve Naroff7cae42b2009-07-10 23:34:53 +00001172 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001173 return false;
1174}
1175
Sebastian Redl72b597d2009-01-25 19:43:20 +00001176/// IsMemberPointerConversion - Determines whether the conversion of the
1177/// expression From, which has the (possibly adjusted) type FromType, can be
1178/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1179/// If so, returns true and places the converted type (that might differ from
1180/// ToType in its cv-qualifiers at some level) into ConvertedType.
1181bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Mike Stump11289f42009-09-09 15:08:12 +00001182 QualType ToType, QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001183 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001184 if (!ToTypePtr)
1185 return false;
1186
1187 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1188 if (From->isNullPointerConstant(Context)) {
1189 ConvertedType = ToType;
1190 return true;
1191 }
1192
1193 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001194 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001195 if (!FromTypePtr)
1196 return false;
1197
1198 // A pointer to member of B can be converted to a pointer to member of D,
1199 // where D is derived from B (C++ 4.11p2).
1200 QualType FromClass(FromTypePtr->getClass(), 0);
1201 QualType ToClass(ToTypePtr->getClass(), 0);
1202 // FIXME: What happens when these are dependent? Is this function even called?
1203
1204 if (IsDerivedFrom(ToClass, FromClass)) {
1205 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1206 ToClass.getTypePtr());
1207 return true;
1208 }
1209
1210 return false;
1211}
1212
1213/// CheckMemberPointerConversion - Check the member pointer conversion from the
1214/// expression From to the type ToType. This routine checks for ambiguous or
1215/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1216/// for which IsMemberPointerConversion has already returned true. It returns
1217/// true and produces a diagnostic if there was an error, or returns false
1218/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001219bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Anders Carlssond7923c62009-08-22 23:33:40 +00001220 CastExpr::CastKind &Kind) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001221 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001222 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001223 if (!FromPtrType) {
1224 // This must be a null pointer to member pointer conversion
Mike Stump11289f42009-09-09 15:08:12 +00001225 assert(From->isNullPointerConstant(Context) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001226 "Expr must be null pointer constant!");
1227 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001228 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001229 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001230
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001231 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001232 assert(ToPtrType && "No member pointer cast has a target type "
1233 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001234
Sebastian Redled8f2002009-01-28 18:33:18 +00001235 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1236 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001237
Sebastian Redled8f2002009-01-28 18:33:18 +00001238 // FIXME: What about dependent types?
1239 assert(FromClass->isRecordType() && "Pointer into non-class.");
1240 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001241
Sebastian Redled8f2002009-01-28 18:33:18 +00001242 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1243 /*DetectVirtual=*/true);
1244 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1245 assert(DerivationOkay &&
1246 "Should not have been called if derivation isn't OK.");
1247 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001248
Sebastian Redled8f2002009-01-28 18:33:18 +00001249 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1250 getUnqualifiedType())) {
1251 // Derivation is ambiguous. Redo the check to find the exact paths.
1252 Paths.clear();
1253 Paths.setRecordingPaths(true);
1254 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1255 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1256 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001257
Sebastian Redled8f2002009-01-28 18:33:18 +00001258 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1259 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1260 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1261 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001262 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001263
Douglas Gregor89ee6822009-02-28 01:32:25 +00001264 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001265 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1266 << FromClass << ToClass << QualType(VBase, 0)
1267 << From->getSourceRange();
1268 return true;
1269 }
1270
Anders Carlssond7923c62009-08-22 23:33:40 +00001271 // Must be a base to derived member conversion.
1272 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001273 return false;
1274}
1275
Douglas Gregor9a657932008-10-21 23:43:52 +00001276/// IsQualificationConversion - Determines whether the conversion from
1277/// an rvalue of type FromType to ToType is a qualification conversion
1278/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001279bool
1280Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001281 FromType = Context.getCanonicalType(FromType);
1282 ToType = Context.getCanonicalType(ToType);
1283
1284 // If FromType and ToType are the same type, this is not a
1285 // qualification conversion.
1286 if (FromType == ToType)
1287 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001288
Douglas Gregor9a657932008-10-21 23:43:52 +00001289 // (C++ 4.4p4):
1290 // A conversion can add cv-qualifiers at levels other than the first
1291 // in multi-level pointers, subject to the following rules: [...]
1292 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001293 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001294 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001295 // Within each iteration of the loop, we check the qualifiers to
1296 // determine if this still looks like a qualification
1297 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001298 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001299 // until there are no more pointers or pointers-to-members left to
1300 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001301 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001302
1303 // -- for every j > 0, if const is in cv 1,j then const is in cv
1304 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001305 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001306 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001307
Douglas Gregor9a657932008-10-21 23:43:52 +00001308 // -- if the cv 1,j and cv 2,j are different, then const is in
1309 // every cv for 0 < k < j.
1310 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001311 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001312 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001313
Douglas Gregor9a657932008-10-21 23:43:52 +00001314 // Keep track of whether all prior cv-qualifiers in the "to" type
1315 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001316 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001317 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001318 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001319
1320 // We are left with FromType and ToType being the pointee types
1321 // after unwrapping the original FromType and ToType the same number
1322 // of types. If we unwrapped any pointers, and if FromType and
1323 // ToType have the same unqualified type (since we checked
1324 // qualifiers above), then this is a qualification conversion.
1325 return UnwrappedAnyPointer &&
1326 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1327}
1328
Douglas Gregor05155d82009-08-21 23:19:43 +00001329/// \brief Given a function template or function, extract the function template
1330/// declaration (if any) and the underlying function declaration.
1331template<typename T>
1332static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1333 FunctionTemplateDecl *&FunctionTemplate) {
1334 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1335 if (FunctionTemplate)
1336 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1337 else
1338 Function = cast<T>(Orig);
1339}
1340
Douglas Gregor576e98c2009-01-30 23:27:23 +00001341/// Determines whether there is a user-defined conversion sequence
1342/// (C++ [over.ics.user]) that converts expression From to the type
1343/// ToType. If such a conversion exists, User will contain the
1344/// user-defined conversion sequence that performs such a conversion
1345/// and this routine will return true. Otherwise, this routine returns
1346/// false and User is unspecified.
1347///
1348/// \param AllowConversionFunctions true if the conversion should
1349/// consider conversion functions at all. If false, only constructors
1350/// will be considered.
1351///
1352/// \param AllowExplicit true if the conversion should consider C++0x
1353/// "explicit" conversion functions as well as non-explicit conversion
1354/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001355///
1356/// \param ForceRValue true if the expression should be treated as an rvalue
1357/// for overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00001358bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001359 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001360 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001361 bool AllowConversionFunctions,
Mike Stump11289f42009-09-09 15:08:12 +00001362 bool AllowExplicit, bool ForceRValue) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001363 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001364 if (CXXRecordDecl *ToRecordDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001365 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1366 // C++ [over.match.ctor]p1:
1367 // When objects of class type are direct-initialized (8.5), or
1368 // copy-initialized from an expression of the same or a
1369 // derived class type (8.5), overload resolution selects the
1370 // constructor. [...] For copy-initialization, the candidate
1371 // functions are all the converting constructors (12.3.1) of
1372 // that class. The argument list is the expression-list within
1373 // the parentheses of the initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001374 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001375 = Context.DeclarationNames.getCXXConstructorName(
1376 Context.getCanonicalType(ToType).getUnqualifiedType());
1377 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001378 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001379 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001380 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001381 // Find the constructor (which may be a template).
1382 CXXConstructorDecl *Constructor = 0;
1383 FunctionTemplateDecl *ConstructorTmpl
1384 = dyn_cast<FunctionTemplateDecl>(*Con);
1385 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001386 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001387 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1388 else
1389 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump11289f42009-09-09 15:08:12 +00001390
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001391 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001392 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001393 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001394 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001395 1, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00001396 /*SuppressUserConversions=*/true,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001397 ForceRValue);
1398 else
1399 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1400 /*SuppressUserConversions=*/true, ForceRValue);
1401 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001402 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001403 }
1404 }
1405
Douglas Gregor576e98c2009-01-30 23:27:23 +00001406 if (!AllowConversionFunctions) {
1407 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001408 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1409 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001410 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001411 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001412 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001413 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001414 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001415 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1416 // Add all of the conversion functions as candidates.
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001417 OverloadedFunctionDecl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001418 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001419 for (OverloadedFunctionDecl::function_iterator Func
1420 = Conversions->function_begin();
1421 Func != Conversions->function_end(); ++Func) {
1422 CXXConversionDecl *Conv;
1423 FunctionTemplateDecl *ConvTemplate;
1424 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1425 if (ConvTemplate)
1426 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1427 else
1428 Conv = dyn_cast<CXXConversionDecl>(*Func);
1429
1430 if (AllowExplicit || !Conv->isExplicit()) {
1431 if (ConvTemplate)
1432 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1433 CandidateSet);
1434 else
1435 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1436 }
1437 }
1438 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001439 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001440
1441 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001442 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001443 case OR_Success:
1444 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001445 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001446 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1447 // C++ [over.ics.user]p1:
1448 // If the user-defined conversion is specified by a
1449 // constructor (12.3.1), the initial standard conversion
1450 // sequence converts the source type to the type required by
1451 // the argument of the constructor.
1452 //
1453 // FIXME: What about ellipsis conversions?
1454 QualType ThisType = Constructor->getThisType(Context);
1455 User.Before = Best->Conversions[0].Standard;
1456 User.ConversionFunction = Constructor;
1457 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001458 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001459 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001460 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1461 return true;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001462 } else if (CXXConversionDecl *Conversion
1463 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1464 // C++ [over.ics.user]p1:
1465 //
1466 // [...] If the user-defined conversion is specified by a
1467 // conversion function (12.3.2), the initial standard
1468 // conversion sequence converts the source type to the
1469 // implicit object parameter of the conversion function.
1470 User.Before = Best->Conversions[0].Standard;
1471 User.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00001472
1473 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001474 // The second standard conversion sequence converts the
1475 // result of the user-defined conversion to the target type
1476 // for the sequence. Since an implicit conversion sequence
1477 // is an initialization, the special rules for
1478 // initialization by user-defined conversion apply when
1479 // selecting the best user-defined conversion for a
1480 // user-defined conversion sequence (see 13.3.3 and
1481 // 13.3.3.1).
1482 User.After = Best->FinalConversion;
1483 return true;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001484 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001485 assert(false && "Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001486 return false;
1487 }
Mike Stump11289f42009-09-09 15:08:12 +00001488
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001489 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001490 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001491 // No conversion here! We're done.
1492 return false;
1493
1494 case OR_Ambiguous:
1495 // FIXME: See C++ [over.best.ics]p10 for the handling of
1496 // ambiguous conversion sequences.
1497 return false;
1498 }
1499
1500 return false;
1501}
1502
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001503/// CompareImplicitConversionSequences - Compare two implicit
1504/// conversion sequences to determine whether one is better than the
1505/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001506ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001507Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1508 const ImplicitConversionSequence& ICS2)
1509{
1510 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1511 // conversion sequences (as defined in 13.3.3.1)
1512 // -- a standard conversion sequence (13.3.3.1.1) is a better
1513 // conversion sequence than a user-defined conversion sequence or
1514 // an ellipsis conversion sequence, and
1515 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1516 // conversion sequence than an ellipsis conversion sequence
1517 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001518 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001519 if (ICS1.ConversionKind < ICS2.ConversionKind)
1520 return ImplicitConversionSequence::Better;
1521 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1522 return ImplicitConversionSequence::Worse;
1523
1524 // Two implicit conversion sequences of the same form are
1525 // indistinguishable conversion sequences unless one of the
1526 // following rules apply: (C++ 13.3.3.2p3):
1527 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1528 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001529 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001530 ImplicitConversionSequence::UserDefinedConversion) {
1531 // User-defined conversion sequence U1 is a better conversion
1532 // sequence than another user-defined conversion sequence U2 if
1533 // they contain the same user-defined conversion function or
1534 // constructor and if the second standard conversion sequence of
1535 // U1 is better than the second standard conversion sequence of
1536 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001537 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001538 ICS2.UserDefined.ConversionFunction)
1539 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1540 ICS2.UserDefined.After);
1541 }
1542
1543 return ImplicitConversionSequence::Indistinguishable;
1544}
1545
1546/// CompareStandardConversionSequences - Compare two standard
1547/// conversion sequences to determine whether one is better than the
1548/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001549ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001550Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1551 const StandardConversionSequence& SCS2)
1552{
1553 // Standard conversion sequence S1 is a better conversion sequence
1554 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1555
1556 // -- S1 is a proper subsequence of S2 (comparing the conversion
1557 // sequences in the canonical form defined by 13.3.3.1.1,
1558 // excluding any Lvalue Transformation; the identity conversion
1559 // sequence is considered to be a subsequence of any
1560 // non-identity conversion sequence) or, if not that,
1561 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1562 // Neither is a proper subsequence of the other. Do nothing.
1563 ;
1564 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1565 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001566 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001567 SCS1.Third == ICK_Identity))
1568 // SCS1 is a proper subsequence of SCS2.
1569 return ImplicitConversionSequence::Better;
1570 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1571 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001572 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001573 SCS2.Third == ICK_Identity))
1574 // SCS2 is a proper subsequence of SCS1.
1575 return ImplicitConversionSequence::Worse;
1576
1577 // -- the rank of S1 is better than the rank of S2 (by the rules
1578 // defined below), or, if not that,
1579 ImplicitConversionRank Rank1 = SCS1.getRank();
1580 ImplicitConversionRank Rank2 = SCS2.getRank();
1581 if (Rank1 < Rank2)
1582 return ImplicitConversionSequence::Better;
1583 else if (Rank2 < Rank1)
1584 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001585
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001586 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1587 // are indistinguishable unless one of the following rules
1588 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001589
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001590 // A conversion that is not a conversion of a pointer, or
1591 // pointer to member, to bool is better than another conversion
1592 // that is such a conversion.
1593 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1594 return SCS2.isPointerConversionToBool()
1595 ? ImplicitConversionSequence::Better
1596 : ImplicitConversionSequence::Worse;
1597
Douglas Gregor5c407d92008-10-23 00:40:37 +00001598 // C++ [over.ics.rank]p4b2:
1599 //
1600 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001601 // conversion of B* to A* is better than conversion of B* to
1602 // void*, and conversion of A* to void* is better than conversion
1603 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001604 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001605 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001606 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001607 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001608 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1609 // Exactly one of the conversion sequences is a conversion to
1610 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001611 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1612 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001613 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1614 // Neither conversion sequence converts to a void pointer; compare
1615 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001616 if (ImplicitConversionSequence::CompareKind DerivedCK
1617 = CompareDerivedToBaseConversions(SCS1, SCS2))
1618 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001619 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1620 // Both conversion sequences are conversions to void
1621 // pointers. Compare the source types to determine if there's an
1622 // inheritance relationship in their sources.
1623 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1624 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1625
1626 // Adjust the types we're converting from via the array-to-pointer
1627 // conversion, if we need to.
1628 if (SCS1.First == ICK_Array_To_Pointer)
1629 FromType1 = Context.getArrayDecayedType(FromType1);
1630 if (SCS2.First == ICK_Array_To_Pointer)
1631 FromType2 = Context.getArrayDecayedType(FromType2);
1632
Mike Stump11289f42009-09-09 15:08:12 +00001633 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001634 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001635 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001636 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001637
1638 if (IsDerivedFrom(FromPointee2, FromPointee1))
1639 return ImplicitConversionSequence::Better;
1640 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1641 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001642
1643 // Objective-C++: If one interface is more specific than the
1644 // other, it is the better one.
1645 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1646 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1647 if (FromIface1 && FromIface1) {
1648 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1649 return ImplicitConversionSequence::Better;
1650 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1651 return ImplicitConversionSequence::Worse;
1652 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001653 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001654
1655 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1656 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001657 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001658 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001659 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001660
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001661 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001662 // C++0x [over.ics.rank]p3b4:
1663 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1664 // implicit object parameter of a non-static member function declared
1665 // without a ref-qualifier, and S1 binds an rvalue reference to an
1666 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001667 // FIXME: We don't know if we're dealing with the implicit object parameter,
1668 // or if the member function in this case has a ref qualifier.
1669 // (Of course, we don't have ref qualifiers yet.)
1670 if (SCS1.RRefBinding != SCS2.RRefBinding)
1671 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1672 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001673
1674 // C++ [over.ics.rank]p3b4:
1675 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1676 // which the references refer are the same type except for
1677 // top-level cv-qualifiers, and the type to which the reference
1678 // initialized by S2 refers is more cv-qualified than the type
1679 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001680 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1681 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001682 T1 = Context.getCanonicalType(T1);
1683 T2 = Context.getCanonicalType(T2);
1684 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1685 if (T2.isMoreQualifiedThan(T1))
1686 return ImplicitConversionSequence::Better;
1687 else if (T1.isMoreQualifiedThan(T2))
1688 return ImplicitConversionSequence::Worse;
1689 }
1690 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001691
1692 return ImplicitConversionSequence::Indistinguishable;
1693}
1694
1695/// CompareQualificationConversions - Compares two standard conversion
1696/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001697/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1698ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001699Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001700 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001701 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001702 // -- S1 and S2 differ only in their qualification conversion and
1703 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1704 // cv-qualification signature of type T1 is a proper subset of
1705 // the cv-qualification signature of type T2, and S1 is not the
1706 // deprecated string literal array-to-pointer conversion (4.2).
1707 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1708 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1709 return ImplicitConversionSequence::Indistinguishable;
1710
1711 // FIXME: the example in the standard doesn't use a qualification
1712 // conversion (!)
1713 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1714 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1715 T1 = Context.getCanonicalType(T1);
1716 T2 = Context.getCanonicalType(T2);
1717
1718 // If the types are the same, we won't learn anything by unwrapped
1719 // them.
1720 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1721 return ImplicitConversionSequence::Indistinguishable;
1722
Mike Stump11289f42009-09-09 15:08:12 +00001723 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001724 = ImplicitConversionSequence::Indistinguishable;
1725 while (UnwrapSimilarPointerTypes(T1, T2)) {
1726 // Within each iteration of the loop, we check the qualifiers to
1727 // determine if this still looks like a qualification
1728 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001729 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001730 // until there are no more pointers or pointers-to-members left
1731 // to unwrap. This essentially mimics what
1732 // IsQualificationConversion does, but here we're checking for a
1733 // strict subset of qualifiers.
1734 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1735 // The qualifiers are the same, so this doesn't tell us anything
1736 // about how the sequences rank.
1737 ;
1738 else if (T2.isMoreQualifiedThan(T1)) {
1739 // T1 has fewer qualifiers, so it could be the better sequence.
1740 if (Result == ImplicitConversionSequence::Worse)
1741 // Neither has qualifiers that are a subset of the other's
1742 // qualifiers.
1743 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001744
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001745 Result = ImplicitConversionSequence::Better;
1746 } else if (T1.isMoreQualifiedThan(T2)) {
1747 // T2 has fewer qualifiers, so it could be the better sequence.
1748 if (Result == ImplicitConversionSequence::Better)
1749 // Neither has qualifiers that are a subset of the other's
1750 // qualifiers.
1751 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001752
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001753 Result = ImplicitConversionSequence::Worse;
1754 } else {
1755 // Qualifiers are disjoint.
1756 return ImplicitConversionSequence::Indistinguishable;
1757 }
1758
1759 // If the types after this point are equivalent, we're done.
1760 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1761 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001762 }
1763
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001764 // Check that the winning standard conversion sequence isn't using
1765 // the deprecated string literal array to pointer conversion.
1766 switch (Result) {
1767 case ImplicitConversionSequence::Better:
1768 if (SCS1.Deprecated)
1769 Result = ImplicitConversionSequence::Indistinguishable;
1770 break;
1771
1772 case ImplicitConversionSequence::Indistinguishable:
1773 break;
1774
1775 case ImplicitConversionSequence::Worse:
1776 if (SCS2.Deprecated)
1777 Result = ImplicitConversionSequence::Indistinguishable;
1778 break;
1779 }
1780
1781 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001782}
1783
Douglas Gregor5c407d92008-10-23 00:40:37 +00001784/// CompareDerivedToBaseConversions - Compares two standard conversion
1785/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001786/// various kinds of derived-to-base conversions (C++
1787/// [over.ics.rank]p4b3). As part of these checks, we also look at
1788/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001789ImplicitConversionSequence::CompareKind
1790Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1791 const StandardConversionSequence& SCS2) {
1792 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1793 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1794 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1795 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1796
1797 // Adjust the types we're converting from via the array-to-pointer
1798 // conversion, if we need to.
1799 if (SCS1.First == ICK_Array_To_Pointer)
1800 FromType1 = Context.getArrayDecayedType(FromType1);
1801 if (SCS2.First == ICK_Array_To_Pointer)
1802 FromType2 = Context.getArrayDecayedType(FromType2);
1803
1804 // Canonicalize all of the types.
1805 FromType1 = Context.getCanonicalType(FromType1);
1806 ToType1 = Context.getCanonicalType(ToType1);
1807 FromType2 = Context.getCanonicalType(FromType2);
1808 ToType2 = Context.getCanonicalType(ToType2);
1809
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001810 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001811 //
1812 // If class B is derived directly or indirectly from class A and
1813 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001814 //
1815 // For Objective-C, we let A, B, and C also be Objective-C
1816 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001817
1818 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001819 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001820 SCS2.Second == ICK_Pointer_Conversion &&
1821 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1822 FromType1->isPointerType() && FromType2->isPointerType() &&
1823 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001824 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001825 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001826 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001827 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001828 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001829 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001830 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001831 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001832
1833 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1834 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1835 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1836 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1837
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001838 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001839 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1840 if (IsDerivedFrom(ToPointee1, ToPointee2))
1841 return ImplicitConversionSequence::Better;
1842 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1843 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001844
1845 if (ToIface1 && ToIface2) {
1846 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1847 return ImplicitConversionSequence::Better;
1848 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1849 return ImplicitConversionSequence::Worse;
1850 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001851 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001852
1853 // -- conversion of B* to A* is better than conversion of C* to A*,
1854 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1855 if (IsDerivedFrom(FromPointee2, FromPointee1))
1856 return ImplicitConversionSequence::Better;
1857 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1858 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001859
Douglas Gregor237f96c2008-11-26 23:31:11 +00001860 if (FromIface1 && FromIface2) {
1861 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1862 return ImplicitConversionSequence::Better;
1863 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1864 return ImplicitConversionSequence::Worse;
1865 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001866 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001867 }
1868
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001869 // Compare based on reference bindings.
1870 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1871 SCS1.Second == ICK_Derived_To_Base) {
1872 // -- binding of an expression of type C to a reference of type
1873 // B& is better than binding an expression of type C to a
1874 // reference of type A&,
1875 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1876 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1877 if (IsDerivedFrom(ToType1, ToType2))
1878 return ImplicitConversionSequence::Better;
1879 else if (IsDerivedFrom(ToType2, ToType1))
1880 return ImplicitConversionSequence::Worse;
1881 }
1882
Douglas Gregor2fe98832008-11-03 19:09:14 +00001883 // -- binding of an expression of type B to a reference of type
1884 // A& is better than binding an expression of type C to a
1885 // reference of type A&,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001886 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1887 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1888 if (IsDerivedFrom(FromType2, FromType1))
1889 return ImplicitConversionSequence::Better;
1890 else if (IsDerivedFrom(FromType1, FromType2))
1891 return ImplicitConversionSequence::Worse;
1892 }
1893 }
1894
1895
1896 // FIXME: conversion of A::* to B::* is better than conversion of
1897 // A::* to C::*,
1898
1899 // FIXME: conversion of B::* to C::* is better than conversion of
1900 // A::* to C::*, and
1901
Douglas Gregor2fe98832008-11-03 19:09:14 +00001902 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1903 SCS1.Second == ICK_Derived_To_Base) {
1904 // -- conversion of C to B is better than conversion of C to A,
1905 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1906 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1907 if (IsDerivedFrom(ToType1, ToType2))
1908 return ImplicitConversionSequence::Better;
1909 else if (IsDerivedFrom(ToType2, ToType1))
1910 return ImplicitConversionSequence::Worse;
1911 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001912
Douglas Gregor2fe98832008-11-03 19:09:14 +00001913 // -- conversion of B to A is better than conversion of C to A.
1914 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1915 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1916 if (IsDerivedFrom(FromType2, FromType1))
1917 return ImplicitConversionSequence::Better;
1918 else if (IsDerivedFrom(FromType1, FromType2))
1919 return ImplicitConversionSequence::Worse;
1920 }
1921 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001922
Douglas Gregor5c407d92008-10-23 00:40:37 +00001923 return ImplicitConversionSequence::Indistinguishable;
1924}
1925
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001926/// TryCopyInitialization - Try to copy-initialize a value of type
1927/// ToType from the expression From. Return the implicit conversion
1928/// sequence required to pass this argument, which may be a bad
1929/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00001930/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00001931/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1932/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00001933ImplicitConversionSequence
1934Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00001935 bool SuppressUserConversions, bool ForceRValue,
1936 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001937 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001938 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00001939 CheckReferenceInit(From, ToType,
Anders Carlsson271e3a42009-08-27 17:30:43 +00001940 SuppressUserConversions,
1941 /*AllowExplicit=*/false,
1942 ForceRValue,
1943 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001944 return ICS;
1945 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001946 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001947 SuppressUserConversions,
1948 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001949 ForceRValue,
1950 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001951 }
1952}
1953
Sebastian Redl42e92c42009-04-12 17:16:29 +00001954/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1955/// the expression @p From. Returns true (and emits a diagnostic) if there was
1956/// an error, returns false if the initialization succeeded. Elidable should
1957/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1958/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00001959bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00001960 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001961 if (!getLangOptions().CPlusPlus) {
1962 // In C, argument passing is the same as performing an assignment.
1963 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001964
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001965 AssignConvertType ConvTy =
1966 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00001967 if (ConvTy != Compatible &&
1968 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1969 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00001970
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001971 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1972 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001973 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00001974
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001975 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00001976 return CheckReferenceInit(From, ToType,
1977 /*SuppressUserConversions=*/false,
1978 /*AllowExplicit=*/false,
1979 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001980
Sebastian Redl42e92c42009-04-12 17:16:29 +00001981 if (!PerformImplicitConversion(From, ToType, Flavor,
1982 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001983 return false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00001984
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001985 return Diag(From->getSourceRange().getBegin(),
1986 diag::err_typecheck_convert_incompatible)
1987 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001988}
1989
Douglas Gregor436424c2008-11-18 23:14:02 +00001990/// TryObjectArgumentInitialization - Try to initialize the object
1991/// parameter of the given member function (@c Method) from the
1992/// expression @p From.
1993ImplicitConversionSequence
1994Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1995 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1996 unsigned MethodQuals = Method->getTypeQualifiers();
1997 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1998
1999 // Set up the conversion sequence as a "bad" conversion, to allow us
2000 // to exit early.
2001 ImplicitConversionSequence ICS;
2002 ICS.Standard.setAsIdentityConversion();
2003 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2004
2005 // We need to have an object of class type.
2006 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002007 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002008 FromType = PT->getPointeeType();
2009
2010 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002011
2012 // The implicit object parmeter is has the type "reference to cv X",
2013 // where X is the class of which the function is a member
2014 // (C++ [over.match.funcs]p4). However, when finding an implicit
2015 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002016 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002017 // (C++ [over.match.funcs]p5). We perform a simplified version of
2018 // reference binding here, that allows class rvalues to bind to
2019 // non-constant references.
2020
2021 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2022 // with the implicit object parameter (C++ [over.match.funcs]p5).
2023 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2024 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2025 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2026 return ICS;
2027
2028 // Check that we have either the same type or a derived type. It
2029 // affects the conversion rank.
2030 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2031 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2032 ICS.Standard.Second = ICK_Identity;
2033 else if (IsDerivedFrom(FromType, ClassType))
2034 ICS.Standard.Second = ICK_Derived_To_Base;
2035 else
2036 return ICS;
2037
2038 // Success. Mark this as a reference binding.
2039 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2040 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2041 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2042 ICS.Standard.ReferenceBinding = true;
2043 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002044 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002045 return ICS;
2046}
2047
2048/// PerformObjectArgumentInitialization - Perform initialization of
2049/// the implicit object parameter for the given Method with the given
2050/// expression.
2051bool
2052Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002053 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002054 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002055 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002056
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002057 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002058 FromRecordType = PT->getPointeeType();
2059 DestType = Method->getThisType(Context);
2060 } else {
2061 FromRecordType = From->getType();
2062 DestType = ImplicitParamRecordType;
2063 }
2064
Mike Stump11289f42009-09-09 15:08:12 +00002065 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002066 = TryObjectArgumentInitialization(From, Method);
2067 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2068 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002069 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002070 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002071
Douglas Gregor436424c2008-11-18 23:14:02 +00002072 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002073 CheckDerivedToBaseConversion(FromRecordType,
2074 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002075 From->getSourceRange().getBegin(),
2076 From->getSourceRange()))
2077 return true;
2078
Mike Stump11289f42009-09-09 15:08:12 +00002079 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002080 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002081 return false;
2082}
2083
Douglas Gregor5fb53972009-01-14 15:45:31 +00002084/// TryContextuallyConvertToBool - Attempt to contextually convert the
2085/// expression From to bool (C++0x [conv]p3).
2086ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002087 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002088 // FIXME: Are these flags correct?
2089 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002090 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002091 /*ForceRValue=*/false,
2092 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002093}
2094
2095/// PerformContextuallyConvertToBool - Perform a contextual conversion
2096/// of the expression From to bool (C++0x [conv]p3).
2097bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2098 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2099 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2100 return false;
2101
Fariborz Jahanian19c73282009-09-15 00:10:11 +00002102 OverloadCandidateSet CandidateSet;
2103 IsUserDefinedConversion(From, Context.BoolTy, ICS.UserDefined,
2104 CandidateSet,
2105 true, true, false);
2106 if (CandidateSet.begin() == CandidateSet.end())
2107 return Diag(From->getSourceRange().getBegin(),
2108 diag::err_typecheck_bool_condition)
2109 << From->getType() << From->getSourceRange();
2110 Diag(From->getSourceRange().getBegin(),
2111 diag::err_typecheck_ambiguous_bool_condition)
2112 << From->getType() << From->getSourceRange();
2113 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
2114 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002115}
2116
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002117/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002118/// candidate functions, using the given function call arguments. If
2119/// @p SuppressUserConversions, then don't allow user-defined
2120/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002121/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2122/// hacky way to implement the overloading rules for elidable copy
2123/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002124void
2125Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002126 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002127 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002128 bool SuppressUserConversions,
Mike Stump11289f42009-09-09 15:08:12 +00002129 bool ForceRValue) {
2130 const FunctionProtoType* Proto
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002131 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002132 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002133 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002134 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002135 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002136 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002137
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002138 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002139 if (!isa<CXXConstructorDecl>(Method)) {
2140 // If we get here, it's because we're calling a member function
2141 // that is named without a member access expression (e.g.,
2142 // "this->f") that was either written explicitly or created
2143 // implicitly. This can happen with a qualified call to a member
2144 // function, e.g., X::f(). We use a NULL object as the implied
2145 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002146 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002147 SuppressUserConversions, ForceRValue);
2148 return;
2149 }
2150 // We treat a constructor like a non-member function, since its object
2151 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002152 }
2153
2154
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002155 // Add this candidate
2156 CandidateSet.push_back(OverloadCandidate());
2157 OverloadCandidate& Candidate = CandidateSet.back();
2158 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002159 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002160 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002161 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002162
2163 unsigned NumArgsInProto = Proto->getNumArgs();
2164
2165 // (C++ 13.3.2p2): A candidate function having fewer than m
2166 // parameters is viable only if it has an ellipsis in its parameter
2167 // list (8.3.5).
2168 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2169 Candidate.Viable = false;
2170 return;
2171 }
2172
2173 // (C++ 13.3.2p2): A candidate function having more than m parameters
2174 // is viable only if the (m+1)st parameter has a default argument
2175 // (8.3.6). For the purposes of overload resolution, the
2176 // parameter list is truncated on the right, so that there are
2177 // exactly m parameters.
2178 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2179 if (NumArgs < MinRequiredArgs) {
2180 // Not enough arguments.
2181 Candidate.Viable = false;
2182 return;
2183 }
2184
2185 // Determine the implicit conversion sequences for each of the
2186 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002187 Candidate.Conversions.resize(NumArgs);
2188 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2189 if (ArgIdx < NumArgsInProto) {
2190 // (C++ 13.3.2p3): for F to be a viable function, there shall
2191 // exist for each argument an implicit conversion sequence
2192 // (13.3.3.1) that converts that argument to the corresponding
2193 // parameter of F.
2194 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002195 Candidate.Conversions[ArgIdx]
2196 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002197 SuppressUserConversions, ForceRValue,
2198 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002199 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002200 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002201 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002202 break;
2203 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002204 } else {
2205 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2206 // argument for which there is no corresponding parameter is
2207 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002208 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002209 = ImplicitConversionSequence::EllipsisConversion;
2210 }
2211 }
2212}
2213
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002214/// \brief Add all of the function declarations in the given function set to
2215/// the overload canddiate set.
2216void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2217 Expr **Args, unsigned NumArgs,
2218 OverloadCandidateSet& CandidateSet,
2219 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002220 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002221 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002222 F != FEnd; ++F) {
2223 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
Mike Stump11289f42009-09-09 15:08:12 +00002224 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002225 SuppressUserConversions);
2226 else
Douglas Gregor89026b52009-06-30 23:57:56 +00002227 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2228 /*FIXME: explicit args */false, 0, 0,
Mike Stump11289f42009-09-09 15:08:12 +00002229 Args, NumArgs, CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002230 SuppressUserConversions);
2231 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002232}
2233
Douglas Gregor436424c2008-11-18 23:14:02 +00002234/// AddMethodCandidate - Adds the given C++ member function to the set
2235/// of candidate functions, using the given function call arguments
2236/// and the object argument (@c Object). For example, in a call
2237/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2238/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2239/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002240/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2241/// a slightly hacky way to implement the overloading rules for elidable copy
2242/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002243void
Douglas Gregor436424c2008-11-18 23:14:02 +00002244Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2245 Expr **Args, unsigned NumArgs,
2246 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002247 bool SuppressUserConversions, bool ForceRValue) {
2248 const FunctionProtoType* Proto
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002249 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002250 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002251 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002252 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002253 assert(!isa<CXXConstructorDecl>(Method) &&
2254 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002255
2256 // Add this candidate
2257 CandidateSet.push_back(OverloadCandidate());
2258 OverloadCandidate& Candidate = CandidateSet.back();
2259 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002260 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002261 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002262
2263 unsigned NumArgsInProto = Proto->getNumArgs();
2264
2265 // (C++ 13.3.2p2): A candidate function having fewer than m
2266 // parameters is viable only if it has an ellipsis in its parameter
2267 // list (8.3.5).
2268 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2269 Candidate.Viable = false;
2270 return;
2271 }
2272
2273 // (C++ 13.3.2p2): A candidate function having more than m parameters
2274 // is viable only if the (m+1)st parameter has a default argument
2275 // (8.3.6). For the purposes of overload resolution, the
2276 // parameter list is truncated on the right, so that there are
2277 // exactly m parameters.
2278 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2279 if (NumArgs < MinRequiredArgs) {
2280 // Not enough arguments.
2281 Candidate.Viable = false;
2282 return;
2283 }
2284
2285 Candidate.Viable = true;
2286 Candidate.Conversions.resize(NumArgs + 1);
2287
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002288 if (Method->isStatic() || !Object)
2289 // The implicit object argument is ignored.
2290 Candidate.IgnoreObjectArgument = true;
2291 else {
2292 // Determine the implicit conversion sequence for the object
2293 // parameter.
2294 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002295 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002296 == ImplicitConversionSequence::BadConversion) {
2297 Candidate.Viable = false;
2298 return;
2299 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002300 }
2301
2302 // Determine the implicit conversion sequences for each of the
2303 // arguments.
2304 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2305 if (ArgIdx < NumArgsInProto) {
2306 // (C++ 13.3.2p3): for F to be a viable function, there shall
2307 // exist for each argument an implicit conversion sequence
2308 // (13.3.3.1) that converts that argument to the corresponding
2309 // parameter of F.
2310 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002311 Candidate.Conversions[ArgIdx + 1]
2312 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002313 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002314 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002315 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002316 == ImplicitConversionSequence::BadConversion) {
2317 Candidate.Viable = false;
2318 break;
2319 }
2320 } else {
2321 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2322 // argument for which there is no corresponding parameter is
2323 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002324 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002325 = ImplicitConversionSequence::EllipsisConversion;
2326 }
2327 }
2328}
2329
Douglas Gregor97628d62009-08-21 00:16:32 +00002330/// \brief Add a C++ member function template as a candidate to the candidate
2331/// set, using template argument deduction to produce an appropriate member
2332/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002333void
Douglas Gregor97628d62009-08-21 00:16:32 +00002334Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2335 bool HasExplicitTemplateArgs,
2336 const TemplateArgument *ExplicitTemplateArgs,
2337 unsigned NumExplicitTemplateArgs,
2338 Expr *Object, Expr **Args, unsigned NumArgs,
2339 OverloadCandidateSet& CandidateSet,
2340 bool SuppressUserConversions,
2341 bool ForceRValue) {
2342 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002343 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002344 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002345 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002346 // candidate functions in the usual way.113) A given name can refer to one
2347 // or more function templates and also to a set of overloaded non-template
2348 // functions. In such a case, the candidate functions generated from each
2349 // function template are combined with the set of non-template candidate
2350 // functions.
2351 TemplateDeductionInfo Info(Context);
2352 FunctionDecl *Specialization = 0;
2353 if (TemplateDeductionResult Result
2354 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2355 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2356 Args, NumArgs, Specialization, Info)) {
2357 // FIXME: Record what happened with template argument deduction, so
2358 // that we can give the user a beautiful diagnostic.
2359 (void)Result;
2360 return;
2361 }
Mike Stump11289f42009-09-09 15:08:12 +00002362
Douglas Gregor97628d62009-08-21 00:16:32 +00002363 // Add the function template specialization produced by template argument
2364 // deduction as a candidate.
2365 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002366 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002367 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002368 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002369 CandidateSet, SuppressUserConversions, ForceRValue);
2370}
2371
Douglas Gregor05155d82009-08-21 23:19:43 +00002372/// \brief Add a C++ function template specialization as a candidate
2373/// in the candidate set, using template argument deduction to produce
2374/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002375void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002376Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor89026b52009-06-30 23:57:56 +00002377 bool HasExplicitTemplateArgs,
2378 const TemplateArgument *ExplicitTemplateArgs,
2379 unsigned NumExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002380 Expr **Args, unsigned NumArgs,
2381 OverloadCandidateSet& CandidateSet,
2382 bool SuppressUserConversions,
2383 bool ForceRValue) {
2384 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002385 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002386 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002387 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002388 // candidate functions in the usual way.113) A given name can refer to one
2389 // or more function templates and also to a set of overloaded non-template
2390 // functions. In such a case, the candidate functions generated from each
2391 // function template are combined with the set of non-template candidate
2392 // functions.
2393 TemplateDeductionInfo Info(Context);
2394 FunctionDecl *Specialization = 0;
2395 if (TemplateDeductionResult Result
Douglas Gregor89026b52009-06-30 23:57:56 +00002396 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2397 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2398 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002399 // FIXME: Record what happened with template argument deduction, so
2400 // that we can give the user a beautiful diagnostic.
2401 (void)Result;
2402 return;
2403 }
Mike Stump11289f42009-09-09 15:08:12 +00002404
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002405 // Add the function template specialization produced by template argument
2406 // deduction as a candidate.
2407 assert(Specialization && "Missing function template specialization?");
2408 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2409 SuppressUserConversions, ForceRValue);
2410}
Mike Stump11289f42009-09-09 15:08:12 +00002411
Douglas Gregora1f013e2008-11-07 22:36:19 +00002412/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002413/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002414/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002415/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002416/// (which may or may not be the same type as the type that the
2417/// conversion function produces).
2418void
2419Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2420 Expr *From, QualType ToType,
2421 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002422 assert(!Conversion->getDescribedFunctionTemplate() &&
2423 "Conversion function templates use AddTemplateConversionCandidate");
2424
Douglas Gregora1f013e2008-11-07 22:36:19 +00002425 // Add this candidate
2426 CandidateSet.push_back(OverloadCandidate());
2427 OverloadCandidate& Candidate = CandidateSet.back();
2428 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002429 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002430 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002431 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002432 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002433 = Conversion->getConversionType().getAsOpaquePtr();
2434 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2435
Douglas Gregor436424c2008-11-18 23:14:02 +00002436 // Determine the implicit conversion sequence for the implicit
2437 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002438 Candidate.Viable = true;
2439 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002440 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002441 // Conversion functions to a different type in the base class is visible in
2442 // the derived class. So, a derived to base conversion should not participate
2443 // in overload resolution.
2444 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2445 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002446 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002447 == ImplicitConversionSequence::BadConversion) {
2448 Candidate.Viable = false;
2449 return;
2450 }
2451
2452 // To determine what the conversion from the result of calling the
2453 // conversion function to the type we're eventually trying to
2454 // convert to (ToType), we need to synthesize a call to the
2455 // conversion function and attempt copy initialization from it. This
2456 // makes sure that we get the right semantics with respect to
2457 // lvalues/rvalues and the type. Fortunately, we can allocate this
2458 // call on the stack and we don't need its arguments to be
2459 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002460 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregora1f013e2008-11-07 22:36:19 +00002461 SourceLocation());
2462 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlssona2615922009-07-31 00:48:10 +00002463 CastExpr::CK_Unknown,
Douglas Gregora11693b2008-11-12 17:17:38 +00002464 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002465
2466 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002467 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2468 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002469 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002470 Conversion->getConversionType().getNonReferenceType(),
2471 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002472 ImplicitConversionSequence ICS =
2473 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002474 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002475 /*ForceRValue=*/false,
2476 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002477
Douglas Gregora1f013e2008-11-07 22:36:19 +00002478 switch (ICS.ConversionKind) {
2479 case ImplicitConversionSequence::StandardConversion:
2480 Candidate.FinalConversion = ICS.Standard;
2481 break;
2482
2483 case ImplicitConversionSequence::BadConversion:
2484 Candidate.Viable = false;
2485 break;
2486
2487 default:
Mike Stump11289f42009-09-09 15:08:12 +00002488 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002489 "Can only end up with a standard conversion sequence or failure");
2490 }
2491}
2492
Douglas Gregor05155d82009-08-21 23:19:43 +00002493/// \brief Adds a conversion function template specialization
2494/// candidate to the overload set, using template argument deduction
2495/// to deduce the template arguments of the conversion function
2496/// template from the type that we are converting to (C++
2497/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002498void
Douglas Gregor05155d82009-08-21 23:19:43 +00002499Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2500 Expr *From, QualType ToType,
2501 OverloadCandidateSet &CandidateSet) {
2502 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2503 "Only conversion function templates permitted here");
2504
2505 TemplateDeductionInfo Info(Context);
2506 CXXConversionDecl *Specialization = 0;
2507 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002508 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002509 Specialization, Info)) {
2510 // FIXME: Record what happened with template argument deduction, so
2511 // that we can give the user a beautiful diagnostic.
2512 (void)Result;
2513 return;
2514 }
Mike Stump11289f42009-09-09 15:08:12 +00002515
Douglas Gregor05155d82009-08-21 23:19:43 +00002516 // Add the conversion function template specialization produced by
2517 // template argument deduction as a candidate.
2518 assert(Specialization && "Missing function template specialization?");
2519 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2520}
2521
Douglas Gregorab7897a2008-11-19 22:57:39 +00002522/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2523/// converts the given @c Object to a function pointer via the
2524/// conversion function @c Conversion, and then attempts to call it
2525/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2526/// the type of function that we'll eventually be calling.
2527void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002528 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002529 Expr *Object, Expr **Args, unsigned NumArgs,
2530 OverloadCandidateSet& CandidateSet) {
2531 CandidateSet.push_back(OverloadCandidate());
2532 OverloadCandidate& Candidate = CandidateSet.back();
2533 Candidate.Function = 0;
2534 Candidate.Surrogate = Conversion;
2535 Candidate.Viable = true;
2536 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002537 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002538 Candidate.Conversions.resize(NumArgs + 1);
2539
2540 // Determine the implicit conversion sequence for the implicit
2541 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002542 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002543 = TryObjectArgumentInitialization(Object, Conversion);
2544 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2545 Candidate.Viable = false;
2546 return;
2547 }
2548
2549 // The first conversion is actually a user-defined conversion whose
2550 // first conversion is ObjectInit's standard conversion (which is
2551 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002552 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002553 = ImplicitConversionSequence::UserDefinedConversion;
2554 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2555 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002556 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002557 = Candidate.Conversions[0].UserDefined.Before;
2558 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2559
Mike Stump11289f42009-09-09 15:08:12 +00002560 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002561 unsigned NumArgsInProto = Proto->getNumArgs();
2562
2563 // (C++ 13.3.2p2): A candidate function having fewer than m
2564 // parameters is viable only if it has an ellipsis in its parameter
2565 // list (8.3.5).
2566 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2567 Candidate.Viable = false;
2568 return;
2569 }
2570
2571 // Function types don't have any default arguments, so just check if
2572 // we have enough arguments.
2573 if (NumArgs < NumArgsInProto) {
2574 // Not enough arguments.
2575 Candidate.Viable = false;
2576 return;
2577 }
2578
2579 // Determine the implicit conversion sequences for each of the
2580 // arguments.
2581 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2582 if (ArgIdx < NumArgsInProto) {
2583 // (C++ 13.3.2p3): for F to be a viable function, there shall
2584 // exist for each argument an implicit conversion sequence
2585 // (13.3.3.1) that converts that argument to the corresponding
2586 // parameter of F.
2587 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002588 Candidate.Conversions[ArgIdx + 1]
2589 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002590 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002591 /*ForceRValue=*/false,
2592 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002593 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002594 == ImplicitConversionSequence::BadConversion) {
2595 Candidate.Viable = false;
2596 break;
2597 }
2598 } else {
2599 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2600 // argument for which there is no corresponding parameter is
2601 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002602 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002603 = ImplicitConversionSequence::EllipsisConversion;
2604 }
2605 }
2606}
2607
Mike Stump87c57ac2009-05-16 07:39:55 +00002608// FIXME: This will eventually be removed, once we've migrated all of the
2609// operator overloading logic over to the scheme used by binary operators, which
2610// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002611void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002612 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002613 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002614 OverloadCandidateSet& CandidateSet,
2615 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002616
2617 FunctionSet Functions;
2618
2619 QualType T1 = Args[0]->getType();
2620 QualType T2;
2621 if (NumArgs > 1)
2622 T2 = Args[1]->getType();
2623
2624 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002625 if (S)
2626 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002627 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2628 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2629 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2630 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2631}
2632
2633/// \brief Add overload candidates for overloaded operators that are
2634/// member functions.
2635///
2636/// Add the overloaded operator candidates that are member functions
2637/// for the operator Op that was used in an operator expression such
2638/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2639/// CandidateSet will store the added overload candidates. (C++
2640/// [over.match.oper]).
2641void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2642 SourceLocation OpLoc,
2643 Expr **Args, unsigned NumArgs,
2644 OverloadCandidateSet& CandidateSet,
2645 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002646 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2647
2648 // C++ [over.match.oper]p3:
2649 // For a unary operator @ with an operand of a type whose
2650 // cv-unqualified version is T1, and for a binary operator @ with
2651 // a left operand of a type whose cv-unqualified version is T1 and
2652 // a right operand of a type whose cv-unqualified version is T2,
2653 // three sets of candidate functions, designated member
2654 // candidates, non-member candidates and built-in candidates, are
2655 // constructed as follows:
2656 QualType T1 = Args[0]->getType();
2657 QualType T2;
2658 if (NumArgs > 1)
2659 T2 = Args[1]->getType();
2660
2661 // -- If T1 is a class type, the set of member candidates is the
2662 // result of the qualified lookup of T1::operator@
2663 // (13.3.1.1.1); otherwise, the set of member candidates is
2664 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002665 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002666 // Complete the type if it can be completed. Otherwise, we're done.
2667 if (RequireCompleteType(OpLoc, T1, PartialDiagnostic(0)))
2668 return;
Mike Stump11289f42009-09-09 15:08:12 +00002669
2670 LookupResult Operators = LookupQualifiedName(T1Rec->getDecl(), OpName,
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002671 LookupOrdinaryName, false);
Mike Stump11289f42009-09-09 15:08:12 +00002672 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002673 OperEnd = Operators.end();
2674 Oper != OperEnd;
2675 ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00002676 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
Douglas Gregor55297ac2008-12-23 00:26:44 +00002677 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor436424c2008-11-18 23:14:02 +00002678 /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002679 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002680}
2681
Douglas Gregora11693b2008-11-12 17:17:38 +00002682/// AddBuiltinCandidate - Add a candidate for a built-in
2683/// operator. ResultTy and ParamTys are the result and parameter types
2684/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002685/// arguments being passed to the candidate. IsAssignmentOperator
2686/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002687/// operator. NumContextualBoolArguments is the number of arguments
2688/// (at the beginning of the argument list) that will be contextually
2689/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002690void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002691 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002692 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002693 bool IsAssignmentOperator,
2694 unsigned NumContextualBoolArguments) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002695 // Add this candidate
2696 CandidateSet.push_back(OverloadCandidate());
2697 OverloadCandidate& Candidate = CandidateSet.back();
2698 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002699 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002700 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002701 Candidate.BuiltinTypes.ResultTy = ResultTy;
2702 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2703 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2704
2705 // Determine the implicit conversion sequences for each of the
2706 // arguments.
2707 Candidate.Viable = true;
2708 Candidate.Conversions.resize(NumArgs);
2709 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002710 // C++ [over.match.oper]p4:
2711 // For the built-in assignment operators, conversions of the
2712 // left operand are restricted as follows:
2713 // -- no temporaries are introduced to hold the left operand, and
2714 // -- no user-defined conversions are applied to the left
2715 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002716 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002717 //
2718 // We block these conversions by turning off user-defined
2719 // conversions, since that is the only way that initialization of
2720 // a reference to a non-class type can occur from something that
2721 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002722 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002723 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002724 "Contextual conversion to bool requires bool type");
2725 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2726 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002727 Candidate.Conversions[ArgIdx]
2728 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002729 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002730 /*ForceRValue=*/false,
2731 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002732 }
Mike Stump11289f42009-09-09 15:08:12 +00002733 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002734 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002735 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002736 break;
2737 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002738 }
2739}
2740
2741/// BuiltinCandidateTypeSet - A set of types that will be used for the
2742/// candidate operator functions for built-in operators (C++
2743/// [over.built]). The types are separated into pointer types and
2744/// enumeration types.
2745class BuiltinCandidateTypeSet {
2746 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002747 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002748
2749 /// PointerTypes - The set of pointer types that will be used in the
2750 /// built-in candidates.
2751 TypeSet PointerTypes;
2752
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002753 /// MemberPointerTypes - The set of member pointer types that will be
2754 /// used in the built-in candidates.
2755 TypeSet MemberPointerTypes;
2756
Douglas Gregora11693b2008-11-12 17:17:38 +00002757 /// EnumerationTypes - The set of enumeration types that will be
2758 /// used in the built-in candidates.
2759 TypeSet EnumerationTypes;
2760
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002761 /// Sema - The semantic analysis instance where we are building the
2762 /// candidate type set.
2763 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002764
Douglas Gregora11693b2008-11-12 17:17:38 +00002765 /// Context - The AST context in which we will build the type sets.
2766 ASTContext &Context;
2767
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002768 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2769 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002770
2771public:
2772 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002773 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002774
Mike Stump11289f42009-09-09 15:08:12 +00002775 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002776 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002777
Douglas Gregor5fb53972009-01-14 15:45:31 +00002778 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2779 bool AllowExplicitConversions);
Douglas Gregora11693b2008-11-12 17:17:38 +00002780
2781 /// pointer_begin - First pointer type found;
2782 iterator pointer_begin() { return PointerTypes.begin(); }
2783
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002784 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002785 iterator pointer_end() { return PointerTypes.end(); }
2786
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002787 /// member_pointer_begin - First member pointer type found;
2788 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2789
2790 /// member_pointer_end - Past the last member pointer type found;
2791 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2792
Douglas Gregora11693b2008-11-12 17:17:38 +00002793 /// enumeration_begin - First enumeration type found;
2794 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2795
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002796 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002797 iterator enumeration_end() { return EnumerationTypes.end(); }
2798};
2799
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002800/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00002801/// the set of pointer types along with any more-qualified variants of
2802/// that type. For example, if @p Ty is "int const *", this routine
2803/// will add "int const *", "int const volatile *", "int const
2804/// restrict *", and "int const volatile restrict *" to the set of
2805/// pointer types. Returns true if the add of @p Ty itself succeeded,
2806/// false otherwise.
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002807bool
2808BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002809 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002810 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002811 return false;
2812
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002813 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002814 QualType PointeeTy = PointerTy->getPointeeType();
2815 // FIXME: Optimize this so that we don't keep trying to add the same types.
2816
Mike Stump87c57ac2009-05-16 07:39:55 +00002817 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2818 // pointer conversions that don't cast away constness?
Douglas Gregora11693b2008-11-12 17:17:38 +00002819 if (!PointeeTy.isConstQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002820 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002821 (Context.getPointerType(PointeeTy.withConst()));
2822 if (!PointeeTy.isVolatileQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002823 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002824 (Context.getPointerType(PointeeTy.withVolatile()));
2825 if (!PointeeTy.isRestrictQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002826 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002827 (Context.getPointerType(PointeeTy.withRestrict()));
2828 }
2829
2830 return true;
2831}
2832
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002833/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2834/// to the set of pointer types along with any more-qualified variants of
2835/// that type. For example, if @p Ty is "int const *", this routine
2836/// will add "int const *", "int const volatile *", "int const
2837/// restrict *", and "int const volatile restrict *" to the set of
2838/// pointer types. Returns true if the add of @p Ty itself succeeded,
2839/// false otherwise.
2840bool
2841BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2842 QualType Ty) {
2843 // Insert this type.
2844 if (!MemberPointerTypes.insert(Ty))
2845 return false;
2846
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002847 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002848 QualType PointeeTy = PointerTy->getPointeeType();
2849 const Type *ClassTy = PointerTy->getClass();
2850 // FIXME: Optimize this so that we don't keep trying to add the same types.
2851
2852 if (!PointeeTy.isConstQualified())
2853 AddMemberPointerWithMoreQualifiedTypeVariants
2854 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2855 if (!PointeeTy.isVolatileQualified())
2856 AddMemberPointerWithMoreQualifiedTypeVariants
2857 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2858 if (!PointeeTy.isRestrictQualified())
2859 AddMemberPointerWithMoreQualifiedTypeVariants
2860 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2861 }
2862
2863 return true;
2864}
2865
Douglas Gregora11693b2008-11-12 17:17:38 +00002866/// AddTypesConvertedFrom - Add each of the types to which the type @p
2867/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002868/// primarily interested in pointer types and enumeration types. We also
2869/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002870/// AllowUserConversions is true if we should look at the conversion
2871/// functions of a class type, and AllowExplicitConversions if we
2872/// should also include the explicit conversion functions of a class
2873/// type.
Mike Stump11289f42009-09-09 15:08:12 +00002874void
Douglas Gregor5fb53972009-01-14 15:45:31 +00002875BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2876 bool AllowUserConversions,
2877 bool AllowExplicitConversions) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002878 // Only deal with canonical types.
2879 Ty = Context.getCanonicalType(Ty);
2880
2881 // Look through reference types; they aren't part of the type of an
2882 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002883 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00002884 Ty = RefTy->getPointeeType();
2885
2886 // We don't care about qualifiers on the type.
2887 Ty = Ty.getUnqualifiedType();
2888
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002889 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002890 QualType PointeeTy = PointerTy->getPointeeType();
2891
2892 // Insert our type, and its more-qualified variants, into the set
2893 // of types.
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002894 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002895 return;
2896
2897 // Add 'cv void*' to our set of types.
2898 if (!Ty->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002899 QualType QualVoid
Douglas Gregora11693b2008-11-12 17:17:38 +00002900 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002901 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregora11693b2008-11-12 17:17:38 +00002902 }
2903
2904 // If this is a pointer to a class type, add pointers to its bases
2905 // (with the same level of cv-qualification as the original
2906 // derived class, of course).
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002907 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002908 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2909 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2910 Base != ClassDecl->bases_end(); ++Base) {
2911 QualType BaseTy = Context.getCanonicalType(Base->getType());
2912 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2913
2914 // Add the pointer type, recursively, so that we get all of
2915 // the indirect base classes, too.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002916 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00002917 }
2918 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002919 } else if (Ty->isMemberPointerType()) {
2920 // Member pointers are far easier, since the pointee can't be converted.
2921 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2922 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00002923 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00002924 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002925 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002926 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002927 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2928 // No conversion functions in incomplete types.
2929 return;
2930 }
Mike Stump11289f42009-09-09 15:08:12 +00002931
Douglas Gregora11693b2008-11-12 17:17:38 +00002932 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2933 // FIXME: Visit conversion functions in the base classes, too.
Mike Stump11289f42009-09-09 15:08:12 +00002934 OverloadedFunctionDecl *Conversions
Douglas Gregora11693b2008-11-12 17:17:38 +00002935 = ClassDecl->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00002936 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregora11693b2008-11-12 17:17:38 +00002937 = Conversions->function_begin();
2938 Func != Conversions->function_end(); ++Func) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002939 CXXConversionDecl *Conv;
2940 FunctionTemplateDecl *ConvTemplate;
2941 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2942
Mike Stump11289f42009-09-09 15:08:12 +00002943 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00002944 // about which builtin types we can convert to.
2945 if (ConvTemplate)
2946 continue;
2947
Douglas Gregor5fb53972009-01-14 15:45:31 +00002948 if (AllowExplicitConversions || !Conv->isExplicit())
2949 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00002950 }
2951 }
2952 }
2953}
2954
Douglas Gregor84605ae2009-08-24 13:43:27 +00002955/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2956/// the volatile- and non-volatile-qualified assignment operators for the
2957/// given type to the candidate set.
2958static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2959 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00002960 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00002961 unsigned NumArgs,
2962 OverloadCandidateSet &CandidateSet) {
2963 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002964
Douglas Gregor84605ae2009-08-24 13:43:27 +00002965 // T& operator=(T&, T)
2966 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2967 ParamTypes[1] = T;
2968 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2969 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002970
Douglas Gregor84605ae2009-08-24 13:43:27 +00002971 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2972 // volatile T& operator=(volatile T&, T)
2973 ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
2974 ParamTypes[1] = T;
2975 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002976 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00002977 }
2978}
Mike Stump11289f42009-09-09 15:08:12 +00002979
Douglas Gregord08452f2008-11-19 15:42:04 +00002980/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2981/// operator overloads to the candidate set (C++ [over.built]), based
2982/// on the operator @p Op and the arguments given. For example, if the
2983/// operator is a binary '+', this routine might add "int
2984/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00002985void
Mike Stump11289f42009-09-09 15:08:12 +00002986Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregord08452f2008-11-19 15:42:04 +00002987 Expr **Args, unsigned NumArgs,
2988 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002989 // The set of "promoted arithmetic types", which are the arithmetic
2990 // types are that preserved by promotion (C++ [over.built]p2). Note
2991 // that the first few of these types are the promoted integral
2992 // types; these types need to be first.
2993 // FIXME: What about complex?
2994 const unsigned FirstIntegralType = 0;
2995 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00002996 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00002997 LastPromotedIntegralType = 13;
2998 const unsigned FirstPromotedArithmeticType = 7,
2999 LastPromotedArithmeticType = 16;
3000 const unsigned NumArithmeticTypes = 16;
3001 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003002 Context.BoolTy, Context.CharTy, Context.WCharTy,
3003// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003004 Context.SignedCharTy, Context.ShortTy,
3005 Context.UnsignedCharTy, Context.UnsignedShortTy,
3006 Context.IntTy, Context.LongTy, Context.LongLongTy,
3007 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3008 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3009 };
3010
3011 // Find all of the types that the arguments can convert to, but only
3012 // if the operator we're looking at has built-in operator candidates
3013 // that make use of these types.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003014 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003015 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3016 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003017 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003018 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003019 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003020 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003021 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003022 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3023 true,
3024 (Op == OO_Exclaim ||
3025 Op == OO_AmpAmp ||
3026 Op == OO_PipePipe));
Douglas Gregora11693b2008-11-12 17:17:38 +00003027 }
3028
3029 bool isComparison = false;
3030 switch (Op) {
3031 case OO_None:
3032 case NUM_OVERLOADED_OPERATORS:
3033 assert(false && "Expected an overloaded operator");
3034 break;
3035
Douglas Gregord08452f2008-11-19 15:42:04 +00003036 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003037 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003038 goto UnaryStar;
3039 else
3040 goto BinaryStar;
3041 break;
3042
3043 case OO_Plus: // '+' is either unary or binary
3044 if (NumArgs == 1)
3045 goto UnaryPlus;
3046 else
3047 goto BinaryPlus;
3048 break;
3049
3050 case OO_Minus: // '-' is either unary or binary
3051 if (NumArgs == 1)
3052 goto UnaryMinus;
3053 else
3054 goto BinaryMinus;
3055 break;
3056
3057 case OO_Amp: // '&' is either unary or binary
3058 if (NumArgs == 1)
3059 goto UnaryAmp;
3060 else
3061 goto BinaryAmp;
3062
3063 case OO_PlusPlus:
3064 case OO_MinusMinus:
3065 // C++ [over.built]p3:
3066 //
3067 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3068 // is either volatile or empty, there exist candidate operator
3069 // functions of the form
3070 //
3071 // VQ T& operator++(VQ T&);
3072 // T operator++(VQ T&, int);
3073 //
3074 // C++ [over.built]p4:
3075 //
3076 // For every pair (T, VQ), where T is an arithmetic type other
3077 // than bool, and VQ is either volatile or empty, there exist
3078 // candidate operator functions of the form
3079 //
3080 // VQ T& operator--(VQ T&);
3081 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003082 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003083 Arith < NumArithmeticTypes; ++Arith) {
3084 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003085 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003086 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003087
3088 // Non-volatile version.
3089 if (NumArgs == 1)
3090 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3091 else
3092 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3093
3094 // Volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003095 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregord08452f2008-11-19 15:42:04 +00003096 if (NumArgs == 1)
3097 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3098 else
3099 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3100 }
3101
3102 // C++ [over.built]p5:
3103 //
3104 // For every pair (T, VQ), where T is a cv-qualified or
3105 // cv-unqualified object type, and VQ is either volatile or
3106 // empty, there exist candidate operator functions of the form
3107 //
3108 // T*VQ& operator++(T*VQ&);
3109 // T*VQ& operator--(T*VQ&);
3110 // T* operator++(T*VQ&, int);
3111 // T* operator--(T*VQ&, int);
3112 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3113 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3114 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003115 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003116 continue;
3117
Mike Stump11289f42009-09-09 15:08:12 +00003118 QualType ParamTypes[2] = {
3119 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003120 };
Mike Stump11289f42009-09-09 15:08:12 +00003121
Douglas Gregord08452f2008-11-19 15:42:04 +00003122 // Without volatile
3123 if (NumArgs == 1)
3124 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3125 else
3126 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3127
3128 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3129 // With volatile
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003130 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregord08452f2008-11-19 15:42:04 +00003131 if (NumArgs == 1)
3132 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3133 else
3134 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3135 }
3136 }
3137 break;
3138
3139 UnaryStar:
3140 // C++ [over.built]p6:
3141 // For every cv-qualified or cv-unqualified object type T, there
3142 // exist candidate operator functions of the form
3143 //
3144 // T& operator*(T*);
3145 //
3146 // C++ [over.built]p7:
3147 // For every function type T, there exist candidate operator
3148 // functions of the form
3149 // T& operator*(T*);
3150 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3151 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3152 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003153 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003154 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003155 &ParamTy, Args, 1, CandidateSet);
3156 }
3157 break;
3158
3159 UnaryPlus:
3160 // C++ [over.built]p8:
3161 // For every type T, there exist candidate operator functions of
3162 // the form
3163 //
3164 // T* operator+(T*);
3165 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3166 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3167 QualType ParamTy = *Ptr;
3168 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3169 }
Mike Stump11289f42009-09-09 15:08:12 +00003170
Douglas Gregord08452f2008-11-19 15:42:04 +00003171 // Fall through
3172
3173 UnaryMinus:
3174 // C++ [over.built]p9:
3175 // For every promoted arithmetic type T, there exist candidate
3176 // operator functions of the form
3177 //
3178 // T operator+(T);
3179 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003180 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003181 Arith < LastPromotedArithmeticType; ++Arith) {
3182 QualType ArithTy = ArithmeticTypes[Arith];
3183 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3184 }
3185 break;
3186
3187 case OO_Tilde:
3188 // C++ [over.built]p10:
3189 // For every promoted integral type T, there exist candidate
3190 // operator functions of the form
3191 //
3192 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003193 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003194 Int < LastPromotedIntegralType; ++Int) {
3195 QualType IntTy = ArithmeticTypes[Int];
3196 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3197 }
3198 break;
3199
Douglas Gregora11693b2008-11-12 17:17:38 +00003200 case OO_New:
3201 case OO_Delete:
3202 case OO_Array_New:
3203 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003204 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003205 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003206 break;
3207
3208 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003209 UnaryAmp:
3210 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003211 // C++ [over.match.oper]p3:
3212 // -- For the operator ',', the unary operator '&', or the
3213 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003214 break;
3215
Douglas Gregor84605ae2009-08-24 13:43:27 +00003216 case OO_EqualEqual:
3217 case OO_ExclaimEqual:
3218 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003219 // For every pointer to member type T, there exist candidate operator
3220 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003221 //
3222 // bool operator==(T,T);
3223 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003224 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003225 MemPtr = CandidateTypes.member_pointer_begin(),
3226 MemPtrEnd = CandidateTypes.member_pointer_end();
3227 MemPtr != MemPtrEnd;
3228 ++MemPtr) {
3229 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3230 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3231 }
Mike Stump11289f42009-09-09 15:08:12 +00003232
Douglas Gregor84605ae2009-08-24 13:43:27 +00003233 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003234
Douglas Gregora11693b2008-11-12 17:17:38 +00003235 case OO_Less:
3236 case OO_Greater:
3237 case OO_LessEqual:
3238 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003239 // C++ [over.built]p15:
3240 //
3241 // For every pointer or enumeration type T, there exist
3242 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003243 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003244 // bool operator<(T, T);
3245 // bool operator>(T, T);
3246 // bool operator<=(T, T);
3247 // bool operator>=(T, T);
3248 // bool operator==(T, T);
3249 // bool operator!=(T, T);
3250 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3251 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3252 QualType ParamTypes[2] = { *Ptr, *Ptr };
3253 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3254 }
Mike Stump11289f42009-09-09 15:08:12 +00003255 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003256 = CandidateTypes.enumeration_begin();
3257 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3258 QualType ParamTypes[2] = { *Enum, *Enum };
3259 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3260 }
3261
3262 // Fall through.
3263 isComparison = true;
3264
Douglas Gregord08452f2008-11-19 15:42:04 +00003265 BinaryPlus:
3266 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003267 if (!isComparison) {
3268 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3269
3270 // C++ [over.built]p13:
3271 //
3272 // For every cv-qualified or cv-unqualified object type T
3273 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003274 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003275 // T* operator+(T*, ptrdiff_t);
3276 // T& operator[](T*, ptrdiff_t); [BELOW]
3277 // T* operator-(T*, ptrdiff_t);
3278 // T* operator+(ptrdiff_t, T*);
3279 // T& operator[](ptrdiff_t, T*); [BELOW]
3280 //
3281 // C++ [over.built]p14:
3282 //
3283 // For every T, where T is a pointer to object type, there
3284 // exist candidate operator functions of the form
3285 //
3286 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003287 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003288 = CandidateTypes.pointer_begin();
3289 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3290 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3291
3292 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3293 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3294
3295 if (Op == OO_Plus) {
3296 // T* operator+(ptrdiff_t, T*);
3297 ParamTypes[0] = ParamTypes[1];
3298 ParamTypes[1] = *Ptr;
3299 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3300 } else {
3301 // ptrdiff_t operator-(T, T);
3302 ParamTypes[1] = *Ptr;
3303 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3304 Args, 2, CandidateSet);
3305 }
3306 }
3307 }
3308 // Fall through
3309
Douglas Gregora11693b2008-11-12 17:17:38 +00003310 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003311 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003312 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003313 // C++ [over.built]p12:
3314 //
3315 // For every pair of promoted arithmetic types L and R, there
3316 // exist candidate operator functions of the form
3317 //
3318 // LR operator*(L, R);
3319 // LR operator/(L, R);
3320 // LR operator+(L, R);
3321 // LR operator-(L, R);
3322 // bool operator<(L, R);
3323 // bool operator>(L, R);
3324 // bool operator<=(L, R);
3325 // bool operator>=(L, R);
3326 // bool operator==(L, R);
3327 // bool operator!=(L, R);
3328 //
3329 // where LR is the result of the usual arithmetic conversions
3330 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003331 //
3332 // C++ [over.built]p24:
3333 //
3334 // For every pair of promoted arithmetic types L and R, there exist
3335 // candidate operator functions of the form
3336 //
3337 // LR operator?(bool, L, R);
3338 //
3339 // where LR is the result of the usual arithmetic conversions
3340 // between types L and R.
3341 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003342 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003343 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003344 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003345 Right < LastPromotedArithmeticType; ++Right) {
3346 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003347 QualType Result
3348 = isComparison
3349 ? Context.BoolTy
3350 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003351 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3352 }
3353 }
3354 break;
3355
3356 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003357 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003358 case OO_Caret:
3359 case OO_Pipe:
3360 case OO_LessLess:
3361 case OO_GreaterGreater:
3362 // C++ [over.built]p17:
3363 //
3364 // For every pair of promoted integral types L and R, there
3365 // exist candidate operator functions of the form
3366 //
3367 // LR operator%(L, R);
3368 // LR operator&(L, R);
3369 // LR operator^(L, R);
3370 // LR operator|(L, R);
3371 // L operator<<(L, R);
3372 // L operator>>(L, R);
3373 //
3374 // where LR is the result of the usual arithmetic conversions
3375 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003376 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003377 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003378 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003379 Right < LastPromotedIntegralType; ++Right) {
3380 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3381 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3382 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003383 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003384 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3385 }
3386 }
3387 break;
3388
3389 case OO_Equal:
3390 // C++ [over.built]p20:
3391 //
3392 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003393 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003394 // empty, there exist candidate operator functions of the form
3395 //
3396 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003397 for (BuiltinCandidateTypeSet::iterator
3398 Enum = CandidateTypes.enumeration_begin(),
3399 EnumEnd = CandidateTypes.enumeration_end();
3400 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003401 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003402 CandidateSet);
3403 for (BuiltinCandidateTypeSet::iterator
3404 MemPtr = CandidateTypes.member_pointer_begin(),
3405 MemPtrEnd = CandidateTypes.member_pointer_end();
3406 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003407 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003408 CandidateSet);
3409 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003410
3411 case OO_PlusEqual:
3412 case OO_MinusEqual:
3413 // C++ [over.built]p19:
3414 //
3415 // For every pair (T, VQ), where T is any type and VQ is either
3416 // volatile or empty, there exist candidate operator functions
3417 // of the form
3418 //
3419 // T*VQ& operator=(T*VQ&, T*);
3420 //
3421 // C++ [over.built]p21:
3422 //
3423 // For every pair (T, VQ), where T is a cv-qualified or
3424 // cv-unqualified object type and VQ is either volatile or
3425 // empty, there exist candidate operator functions of the form
3426 //
3427 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3428 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3429 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3430 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3431 QualType ParamTypes[2];
3432 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3433
3434 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003435 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003436 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3437 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003438
Douglas Gregord08452f2008-11-19 15:42:04 +00003439 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3440 // volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003441 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorc5e61072009-01-13 00:52:54 +00003442 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3443 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003444 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003445 }
3446 // Fall through.
3447
3448 case OO_StarEqual:
3449 case OO_SlashEqual:
3450 // C++ [over.built]p18:
3451 //
3452 // For every triple (L, VQ, R), where L is an arithmetic type,
3453 // VQ is either volatile or empty, and R is a promoted
3454 // arithmetic type, there exist candidate operator functions of
3455 // the form
3456 //
3457 // VQ L& operator=(VQ L&, R);
3458 // VQ L& operator*=(VQ L&, R);
3459 // VQ L& operator/=(VQ L&, R);
3460 // VQ L& operator+=(VQ L&, R);
3461 // VQ L& operator-=(VQ L&, R);
3462 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003463 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003464 Right < LastPromotedArithmeticType; ++Right) {
3465 QualType ParamTypes[2];
3466 ParamTypes[1] = ArithmeticTypes[Right];
3467
3468 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003469 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003470 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3471 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003472
3473 // Add this built-in operator as a candidate (VQ is 'volatile').
3474 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003475 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003476 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3477 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003478 }
3479 }
3480 break;
3481
3482 case OO_PercentEqual:
3483 case OO_LessLessEqual:
3484 case OO_GreaterGreaterEqual:
3485 case OO_AmpEqual:
3486 case OO_CaretEqual:
3487 case OO_PipeEqual:
3488 // C++ [over.built]p22:
3489 //
3490 // For every triple (L, VQ, R), where L is an integral type, VQ
3491 // is either volatile or empty, and R is a promoted integral
3492 // type, there exist candidate operator functions of the form
3493 //
3494 // VQ L& operator%=(VQ L&, R);
3495 // VQ L& operator<<=(VQ L&, R);
3496 // VQ L& operator>>=(VQ L&, R);
3497 // VQ L& operator&=(VQ L&, R);
3498 // VQ L& operator^=(VQ L&, R);
3499 // VQ L& operator|=(VQ L&, R);
3500 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003501 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003502 Right < LastPromotedIntegralType; ++Right) {
3503 QualType ParamTypes[2];
3504 ParamTypes[1] = ArithmeticTypes[Right];
3505
3506 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003507 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003508 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3509
3510 // Add this built-in operator as a candidate (VQ is 'volatile').
3511 ParamTypes[0] = ArithmeticTypes[Left];
3512 ParamTypes[0].addVolatile();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003513 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003514 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3515 }
3516 }
3517 break;
3518
Douglas Gregord08452f2008-11-19 15:42:04 +00003519 case OO_Exclaim: {
3520 // C++ [over.operator]p23:
3521 //
3522 // There also exist candidate operator functions of the form
3523 //
Mike Stump11289f42009-09-09 15:08:12 +00003524 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003525 // bool operator&&(bool, bool); [BELOW]
3526 // bool operator||(bool, bool); [BELOW]
3527 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003528 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3529 /*IsAssignmentOperator=*/false,
3530 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003531 break;
3532 }
3533
Douglas Gregora11693b2008-11-12 17:17:38 +00003534 case OO_AmpAmp:
3535 case OO_PipePipe: {
3536 // C++ [over.operator]p23:
3537 //
3538 // There also exist candidate operator functions of the form
3539 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003540 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003541 // bool operator&&(bool, bool);
3542 // bool operator||(bool, bool);
3543 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003544 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3545 /*IsAssignmentOperator=*/false,
3546 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003547 break;
3548 }
3549
3550 case OO_Subscript:
3551 // C++ [over.built]p13:
3552 //
3553 // For every cv-qualified or cv-unqualified object type T there
3554 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003555 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003556 // T* operator+(T*, ptrdiff_t); [ABOVE]
3557 // T& operator[](T*, ptrdiff_t);
3558 // T* operator-(T*, ptrdiff_t); [ABOVE]
3559 // T* operator+(ptrdiff_t, T*); [ABOVE]
3560 // T& operator[](ptrdiff_t, T*);
3561 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3562 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3563 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003564 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003565 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003566
3567 // T& operator[](T*, ptrdiff_t)
3568 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3569
3570 // T& operator[](ptrdiff_t, T*);
3571 ParamTypes[0] = ParamTypes[1];
3572 ParamTypes[1] = *Ptr;
3573 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3574 }
3575 break;
3576
3577 case OO_ArrowStar:
3578 // FIXME: No support for pointer-to-members yet.
3579 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003580
3581 case OO_Conditional:
3582 // Note that we don't consider the first argument, since it has been
3583 // contextually converted to bool long ago. The candidates below are
3584 // therefore added as binary.
3585 //
3586 // C++ [over.built]p24:
3587 // For every type T, where T is a pointer or pointer-to-member type,
3588 // there exist candidate operator functions of the form
3589 //
3590 // T operator?(bool, T, T);
3591 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003592 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3593 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3594 QualType ParamTypes[2] = { *Ptr, *Ptr };
3595 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3596 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003597 for (BuiltinCandidateTypeSet::iterator Ptr =
3598 CandidateTypes.member_pointer_begin(),
3599 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3600 QualType ParamTypes[2] = { *Ptr, *Ptr };
3601 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3602 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003603 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003604 }
3605}
3606
Douglas Gregore254f902009-02-04 00:32:51 +00003607/// \brief Add function candidates found via argument-dependent lookup
3608/// to the set of overloading candidates.
3609///
3610/// This routine performs argument-dependent name lookup based on the
3611/// given function name (which may also be an operator name) and adds
3612/// all of the overload candidates found by ADL to the overload
3613/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003614void
Douglas Gregore254f902009-02-04 00:32:51 +00003615Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3616 Expr **Args, unsigned NumArgs,
3617 OverloadCandidateSet& CandidateSet) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003618 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003619
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003620 // Record all of the function candidates that we've already
3621 // added to the overload set, so that we don't add those same
3622 // candidates a second time.
3623 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3624 CandEnd = CandidateSet.end();
3625 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003626 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003627 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003628 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3629 Functions.insert(FunTmpl);
3630 }
Douglas Gregore254f902009-02-04 00:32:51 +00003631
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003632 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003633
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003634 // Erase all of the candidates we already knew about.
3635 // FIXME: This is suboptimal. Is there a better way?
3636 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3637 CandEnd = CandidateSet.end();
3638 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003639 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003640 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003641 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3642 Functions.erase(FunTmpl);
3643 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003644
3645 // For each of the ADL candidates we found, add it to the overload
3646 // set.
3647 for (FunctionSet::iterator Func = Functions.begin(),
3648 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00003649 Func != FuncEnd; ++Func) {
3650 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3651 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3652 else
Mike Stump11289f42009-09-09 15:08:12 +00003653 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregor89026b52009-06-30 23:57:56 +00003654 /*FIXME: explicit args */false, 0, 0,
3655 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00003656 }
Douglas Gregore254f902009-02-04 00:32:51 +00003657}
3658
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003659/// isBetterOverloadCandidate - Determines whether the first overload
3660/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00003661bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003662Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00003663 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003664 // Define viable functions to be better candidates than non-viable
3665 // functions.
3666 if (!Cand2.Viable)
3667 return Cand1.Viable;
3668 else if (!Cand1.Viable)
3669 return false;
3670
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003671 // C++ [over.match.best]p1:
3672 //
3673 // -- if F is a static member function, ICS1(F) is defined such
3674 // that ICS1(F) is neither better nor worse than ICS1(G) for
3675 // any function G, and, symmetrically, ICS1(G) is neither
3676 // better nor worse than ICS1(F).
3677 unsigned StartArg = 0;
3678 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3679 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003680
Douglas Gregord3cb3562009-07-07 23:38:56 +00003681 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00003682 // A viable function F1 is defined to be a better function than another
3683 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00003684 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003685 unsigned NumArgs = Cand1.Conversions.size();
3686 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3687 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003688 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003689 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3690 Cand2.Conversions[ArgIdx])) {
3691 case ImplicitConversionSequence::Better:
3692 // Cand1 has a better conversion sequence.
3693 HasBetterConversion = true;
3694 break;
3695
3696 case ImplicitConversionSequence::Worse:
3697 // Cand1 can't be better than Cand2.
3698 return false;
3699
3700 case ImplicitConversionSequence::Indistinguishable:
3701 // Do nothing.
3702 break;
3703 }
3704 }
3705
Mike Stump11289f42009-09-09 15:08:12 +00003706 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00003707 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003708 if (HasBetterConversion)
3709 return true;
3710
Mike Stump11289f42009-09-09 15:08:12 +00003711 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00003712 // specialization, or, if not that,
3713 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3714 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3715 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003716
3717 // -- F1 and F2 are function template specializations, and the function
3718 // template for F1 is more specialized than the template for F2
3719 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00003720 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00003721 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3722 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00003723 if (FunctionTemplateDecl *BetterTemplate
3724 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3725 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00003726 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
3727 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00003728 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003729
Douglas Gregora1f013e2008-11-07 22:36:19 +00003730 // -- the context is an initialization by user-defined conversion
3731 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3732 // from the return type of F1 to the destination type (i.e.,
3733 // the type of the entity being initialized) is a better
3734 // conversion sequence than the standard conversion sequence
3735 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00003736 if (Cand1.Function && Cand2.Function &&
3737 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003738 isa<CXXConversionDecl>(Cand2.Function)) {
3739 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3740 Cand2.FinalConversion)) {
3741 case ImplicitConversionSequence::Better:
3742 // Cand1 has a better conversion sequence.
3743 return true;
3744
3745 case ImplicitConversionSequence::Worse:
3746 // Cand1 can't be better than Cand2.
3747 return false;
3748
3749 case ImplicitConversionSequence::Indistinguishable:
3750 // Do nothing
3751 break;
3752 }
3753 }
3754
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003755 return false;
3756}
3757
Mike Stump11289f42009-09-09 15:08:12 +00003758/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003759/// within an overload candidate set.
3760///
3761/// \param CandidateSet the set of candidate functions.
3762///
3763/// \param Loc the location of the function name (or operator symbol) for
3764/// which overload resolution occurs.
3765///
Mike Stump11289f42009-09-09 15:08:12 +00003766/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003767/// function, Best points to the candidate function found.
3768///
3769/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00003770Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003771Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003772 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003773 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003774 // Find the best viable function.
3775 Best = CandidateSet.end();
3776 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3777 Cand != CandidateSet.end(); ++Cand) {
3778 if (Cand->Viable) {
3779 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3780 Best = Cand;
3781 }
3782 }
3783
3784 // If we didn't find any viable functions, abort.
3785 if (Best == CandidateSet.end())
3786 return OR_No_Viable_Function;
3787
3788 // Make sure that this function is better than every other viable
3789 // function. If not, we have an ambiguity.
3790 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3791 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00003792 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003793 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00003794 !isBetterOverloadCandidate(*Best, *Cand)) {
3795 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003796 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003797 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003798 }
Mike Stump11289f42009-09-09 15:08:12 +00003799
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003800 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003801 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00003802 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003803 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003804 return OR_Deleted;
3805
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003806 // C++ [basic.def.odr]p2:
3807 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00003808 // when referred to from a potentially-evaluated expression. [Note: this
3809 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003810 // (clause 13), user-defined conversions (12.3.2), allocation function for
3811 // placement new (5.3.4), as well as non-default initialization (8.5).
3812 if (Best->Function)
3813 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003814 return OR_Success;
3815}
3816
3817/// PrintOverloadCandidates - When overload resolution fails, prints
3818/// diagnostic messages containing the candidates in the candidate
3819/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00003820void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003821Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003822 bool OnlyViable) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003823 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3824 LastCand = CandidateSet.end();
3825 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003826 if (Cand->Viable || !OnlyViable) {
3827 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003828 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003829 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003830 // Deleted or "unavailable" function.
3831 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3832 << Cand->Function->isDeleted();
3833 } else {
3834 // Normal function
3835 // FIXME: Give a better reason!
3836 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3837 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00003838 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003839 // Desugar the type of the surrogate down to a function type,
3840 // retaining as many typedefs as possible while still showing
3841 // the function type (and, therefore, its parameter types).
3842 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003843 bool isLValueReference = false;
3844 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003845 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003846 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003847 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003848 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003849 isLValueReference = true;
3850 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003851 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003852 FnType = FnTypeRef->getPointeeType();
3853 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003854 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003855 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003856 FnType = FnTypePtr->getPointeeType();
3857 isPointer = true;
3858 }
3859 // Desugar down to a function type.
3860 FnType = QualType(FnType->getAsFunctionType(), 0);
3861 // Reconstruct the pointer/reference as appropriate.
3862 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003863 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3864 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003865
Douglas Gregorab7897a2008-11-19 22:57:39 +00003866 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003867 << FnType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003868 } else {
3869 // FIXME: We need to get the identifier in here
Mike Stump87c57ac2009-05-16 07:39:55 +00003870 // FIXME: Do we want the error message to point at the operator?
3871 // (built-ins won't have a location)
Mike Stump11289f42009-09-09 15:08:12 +00003872 QualType FnType
Douglas Gregora11693b2008-11-12 17:17:38 +00003873 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3874 Cand->BuiltinTypes.ParamTypes,
3875 Cand->Conversions.size(),
3876 false, 0);
3877
Chris Lattner1e5665e2008-11-24 06:25:27 +00003878 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003879 }
3880 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003881 }
3882}
3883
Douglas Gregorcd695e52008-11-10 20:40:00 +00003884/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3885/// an overloaded function (C++ [over.over]), where @p From is an
3886/// expression with overloaded function type and @p ToType is the type
3887/// we're trying to resolve to. For example:
3888///
3889/// @code
3890/// int f(double);
3891/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00003892///
Douglas Gregorcd695e52008-11-10 20:40:00 +00003893/// int (*pfd)(double) = f; // selects f(double)
3894/// @endcode
3895///
3896/// This routine returns the resulting FunctionDecl if it could be
3897/// resolved, and NULL otherwise. When @p Complain is true, this
3898/// routine will emit diagnostics if there is an error.
3899FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003900Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003901 bool Complain) {
3902 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003903 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003904 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00003905 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003906 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00003907 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003908 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003909 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003910 FunctionType = MemTypePtr->getPointeeType();
3911 IsMember = true;
3912 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003913
3914 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00003915 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00003916 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00003917 return 0;
3918
3919 // Find the actual overloaded function declaration.
3920 OverloadedFunctionDecl *Ovl = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003921
Douglas Gregorcd695e52008-11-10 20:40:00 +00003922 // C++ [over.over]p1:
3923 // [...] [Note: any redundant set of parentheses surrounding the
3924 // overloaded function name is ignored (5.1). ]
3925 Expr *OvlExpr = From->IgnoreParens();
3926
3927 // C++ [over.over]p1:
3928 // [...] The overloaded function name can be preceded by the &
3929 // operator.
3930 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3931 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3932 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3933 }
3934
3935 // Try to dig out the overloaded function.
Douglas Gregor9b146582009-07-08 20:55:45 +00003936 FunctionTemplateDecl *FunctionTemplate = 0;
3937 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00003938 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor9b146582009-07-08 20:55:45 +00003939 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3940 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003941
Mike Stump11289f42009-09-09 15:08:12 +00003942 // If there's no overloaded function declaration or function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00003943 // we're done.
3944 if (!Ovl && !FunctionTemplate)
Douglas Gregorcd695e52008-11-10 20:40:00 +00003945 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003946
Douglas Gregor9b146582009-07-08 20:55:45 +00003947 OverloadIterator Fun;
3948 if (Ovl)
3949 Fun = Ovl;
3950 else
3951 Fun = FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00003952
Douglas Gregorcd695e52008-11-10 20:40:00 +00003953 // Look through all of the overloaded functions, searching for one
3954 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003955 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Mike Stump11289f42009-09-09 15:08:12 +00003956
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003957 bool FoundNonTemplateFunction = false;
Douglas Gregor9b146582009-07-08 20:55:45 +00003958 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00003959 // C++ [over.over]p3:
3960 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00003961 // targets of type "pointer-to-function" or "reference-to-function."
3962 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003963 // type "pointer-to-member-function."
3964 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00003965
Mike Stump11289f42009-09-09 15:08:12 +00003966 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor9b146582009-07-08 20:55:45 +00003967 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump11289f42009-09-09 15:08:12 +00003968 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003969 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003970 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003971 // static when converting to member pointer.
3972 if (Method->isStatic() == IsMember)
3973 continue;
3974 } else if (IsMember)
3975 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003976
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003977 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003978 // If the name is a function template, template argument deduction is
3979 // done (14.8.2.2), and if the argument deduction succeeds, the
3980 // resulting template argument list is used to generate a single
3981 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003982 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00003983 FunctionDecl *Specialization = 0;
3984 TemplateDeductionInfo Info(Context);
3985 if (TemplateDeductionResult Result
3986 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3987 /*FIXME:*/0, /*FIXME:*/0,
3988 FunctionType, Specialization, Info)) {
3989 // FIXME: make a note of the failed deduction for diagnostics.
3990 (void)Result;
3991 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003992 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00003993 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003994 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003995 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00003996 }
3997 }
Mike Stump11289f42009-09-09 15:08:12 +00003998
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003999 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4000 // Skip non-static functions when converting to pointer, and static
4001 // when converting to member pointer.
4002 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004003 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004004 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004005 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004006
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004007 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004008 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004009 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004010 FoundNonTemplateFunction = true;
4011 }
Mike Stump11289f42009-09-09 15:08:12 +00004012 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004013 }
4014
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004015 // If there were 0 or 1 matches, we're done.
4016 if (Matches.empty())
4017 return 0;
4018 else if (Matches.size() == 1)
4019 return *Matches.begin();
4020
4021 // C++ [over.over]p4:
4022 // If more than one function is selected, [...]
4023 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor05155d82009-08-21 23:19:43 +00004024 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004025 if (FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004026 // [...] any function template specializations in the set are
4027 // eliminated if the set also contains a non-template function, [...]
4028 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004029 if ((*M)->getPrimaryTemplate() == 0)
4030 RemainingMatches.push_back(*M);
4031 } else {
Douglas Gregor05155d82009-08-21 23:19:43 +00004032 // [...] and any given function template specialization F1 is
4033 // eliminated if the set contains a second function template
4034 // specialization whose function template is more specialized
4035 // than the function template of F1 according to the partial
4036 // ordering rules of 14.5.5.2.
4037
4038 // The algorithm specified above is quadratic. We instead use a
4039 // two-pass algorithm (similar to the one used to identify the
4040 // best viable function in an overload set) that identifies the
4041 // best function template (if it exists).
4042 MatchIter Best = Matches.begin();
4043 MatchIter M = Best, MEnd = Matches.end();
4044 // Find the most specialized function.
4045 for (++M; M != MEnd; ++M)
4046 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4047 (*Best)->getPrimaryTemplate(),
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004048 TPOC_Other)
Douglas Gregor05155d82009-08-21 23:19:43 +00004049 == (*M)->getPrimaryTemplate())
4050 Best = M;
4051
4052 // Determine whether this function template is more specialized
4053 // that all of the others.
4054 bool Ambiguous = false;
4055 for (M = Matches.begin(); M != MEnd; ++M) {
4056 if (M != Best &&
4057 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4058 (*Best)->getPrimaryTemplate(),
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004059 TPOC_Other)
Douglas Gregor05155d82009-08-21 23:19:43 +00004060 != (*Best)->getPrimaryTemplate()) {
4061 Ambiguous = true;
4062 break;
4063 }
4064 }
4065
4066 // If one function template was more specialized than all of the
4067 // others, return it.
4068 if (!Ambiguous)
4069 return *Best;
4070
4071 // We could not find a most-specialized function template, which
4072 // is equivalent to having a set of function templates with more
4073 // than one such template. So, we place all of the function
4074 // templates into the set of remaining matches and produce a
4075 // diagnostic below. FIXME: we could perform the quadratic
4076 // algorithm here, pruning the result set to limit the number of
4077 // candidates output later.
Douglas Gregor48bc3742009-09-14 22:02:01 +00004078 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004079 }
Mike Stump11289f42009-09-09 15:08:12 +00004080
4081 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004082 // selected function.
4083 if (RemainingMatches.size() == 1)
4084 return RemainingMatches.front();
Mike Stump11289f42009-09-09 15:08:12 +00004085
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004086 // FIXME: We should probably return the same thing that BestViableFunction
4087 // returns (even if we issue the diagnostics here).
4088 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4089 << RemainingMatches[0]->getDeclName();
4090 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4091 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004092 return 0;
4093}
4094
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004095/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004096/// (which eventually refers to the declaration Func) and the call
4097/// arguments Args/NumArgs, attempt to resolve the function call down
4098/// to a specific function. If overload resolution succeeds, returns
4099/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004100/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004101/// arguments and Fn, and returns NULL.
Douglas Gregore254f902009-02-04 00:32:51 +00004102FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004103 DeclarationName UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00004104 bool HasExplicitTemplateArgs,
4105 const TemplateArgument *ExplicitTemplateArgs,
4106 unsigned NumExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004107 SourceLocation LParenLoc,
4108 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004109 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004110 SourceLocation RParenLoc,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004111 bool &ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004112 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004113
4114 // Add the functions denoted by Callee to the set of candidate
4115 // functions. While we're doing so, track whether argument-dependent
4116 // lookup still applies, per:
4117 //
4118 // C++0x [basic.lookup.argdep]p3:
4119 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4120 // and let Y be the lookup set produced by argument dependent
4121 // lookup (defined as follows). If X contains
4122 //
Mike Stump11289f42009-09-09 15:08:12 +00004123 // -- a declaration of a class member, or
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004124 //
4125 // -- a block-scope function declaration that is not a
Mike Stump11289f42009-09-09 15:08:12 +00004126 // using-declaration, or
4127 //
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004128 // -- a declaration that is neither a function or a function
4129 // template
4130 //
Mike Stump11289f42009-09-09 15:08:12 +00004131 // then Y is empty.
4132 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004133 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4134 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4135 FuncEnd = Ovl->function_end();
4136 Func != FuncEnd; ++Func) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004137 DeclContext *Ctx = 0;
4138 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregor89026b52009-06-30 23:57:56 +00004139 if (HasExplicitTemplateArgs)
4140 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004141
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004142 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4143 Ctx = FunDecl->getDeclContext();
4144 } else {
4145 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregor89026b52009-06-30 23:57:56 +00004146 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4147 ExplicitTemplateArgs,
4148 NumExplicitTemplateArgs,
4149 Args, NumArgs, CandidateSet);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004150 Ctx = FunTmpl->getDeclContext();
4151 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004152
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004153
4154 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004155 ArgumentDependentLookup = false;
4156 }
4157 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregor89026b52009-06-30 23:57:56 +00004158 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004159 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4160
4161 if (Func->getDeclContext()->isRecord() ||
4162 Func->getDeclContext()->isFunctionOrMethod())
4163 ArgumentDependentLookup = false;
Mike Stump11289f42009-09-09 15:08:12 +00004164 } else if (FunctionTemplateDecl *FuncTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004165 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregor89026b52009-06-30 23:57:56 +00004166 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4167 ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004168 NumExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004169 Args, NumArgs, CandidateSet);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004170
4171 if (FuncTemplate->getDeclContext()->isRecord())
4172 ArgumentDependentLookup = false;
4173 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004174
4175 if (Callee)
4176 UnqualifiedName = Callee->getDeclName();
4177
Douglas Gregor89026b52009-06-30 23:57:56 +00004178 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregore254f902009-02-04 00:32:51 +00004179 if (ArgumentDependentLookup)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004180 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregore254f902009-02-04 00:32:51 +00004181 CandidateSet);
4182
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004183 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004184 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004185 case OR_Success:
4186 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004187
4188 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004189 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004190 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004191 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004192 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4193 break;
4194
4195 case OR_Ambiguous:
4196 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004197 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004198 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4199 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004200
4201 case OR_Deleted:
4202 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4203 << Best->Function->isDeleted()
4204 << UnqualifiedName
4205 << Fn->getSourceRange();
4206 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4207 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004208 }
4209
4210 // Overload resolution failed. Destroy all of the subexpressions and
4211 // return NULL.
4212 Fn->Destroy(Context);
4213 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4214 Args[Arg]->Destroy(Context);
4215 return 0;
4216}
4217
Douglas Gregor084d8552009-03-13 23:49:33 +00004218/// \brief Create a unary operation that may resolve to an overloaded
4219/// operator.
4220///
4221/// \param OpLoc The location of the operator itself (e.g., '*').
4222///
4223/// \param OpcIn The UnaryOperator::Opcode that describes this
4224/// operator.
4225///
4226/// \param Functions The set of non-member functions that will be
4227/// considered by overload resolution. The caller needs to build this
4228/// set based on the context using, e.g.,
4229/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4230/// set should not contain any member functions; those will be added
4231/// by CreateOverloadedUnaryOp().
4232///
4233/// \param input The input argument.
4234Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4235 unsigned OpcIn,
4236 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004237 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004238 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4239 Expr *Input = (Expr *)input.get();
4240
4241 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4242 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4243 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4244
4245 Expr *Args[2] = { Input, 0 };
4246 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004247
Douglas Gregor084d8552009-03-13 23:49:33 +00004248 // For post-increment and post-decrement, add the implicit '0' as
4249 // the second argument, so that we know this is a post-increment or
4250 // post-decrement.
4251 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4252 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004253 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004254 SourceLocation());
4255 NumArgs = 2;
4256 }
4257
4258 if (Input->isTypeDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00004259 OverloadedFunctionDecl *Overloads
Douglas Gregor084d8552009-03-13 23:49:33 +00004260 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004261 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004262 FuncEnd = Functions.end();
4263 Func != FuncEnd; ++Func)
4264 Overloads->addOverload(*Func);
4265
4266 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4267 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004268
Douglas Gregor084d8552009-03-13 23:49:33 +00004269 input.release();
4270 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4271 &Args[0], NumArgs,
4272 Context.DependentTy,
4273 OpLoc));
4274 }
4275
4276 // Build an empty overload set.
4277 OverloadCandidateSet CandidateSet;
4278
4279 // Add the candidates from the given function set.
4280 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4281
4282 // Add operator candidates that are member functions.
4283 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4284
4285 // Add builtin operator candidates.
4286 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4287
4288 // Perform overload resolution.
4289 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004290 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004291 case OR_Success: {
4292 // We found a built-in operator or an overloaded operator.
4293 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004294
Douglas Gregor084d8552009-03-13 23:49:33 +00004295 if (FnDecl) {
4296 // We matched an overloaded operator. Build a call to that
4297 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004298
Douglas Gregor084d8552009-03-13 23:49:33 +00004299 // Convert the arguments.
4300 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4301 if (PerformObjectArgumentInitialization(Input, Method))
4302 return ExprError();
4303 } else {
4304 // Convert the arguments.
4305 if (PerformCopyInitialization(Input,
4306 FnDecl->getParamDecl(0)->getType(),
4307 "passing"))
4308 return ExprError();
4309 }
4310
4311 // Determine the result type
4312 QualType ResultTy
4313 = FnDecl->getType()->getAsFunctionType()->getResultType();
4314 ResultTy = ResultTy.getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004315
Douglas Gregor084d8552009-03-13 23:49:33 +00004316 // Build the actual expression node.
4317 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4318 SourceLocation());
4319 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004320
Douglas Gregor084d8552009-03-13 23:49:33 +00004321 input.release();
Mike Stump11289f42009-09-09 15:08:12 +00004322
4323 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004324 &Input, 1, ResultTy, OpLoc);
4325 return MaybeBindToTemporary(CE);
Douglas Gregor084d8552009-03-13 23:49:33 +00004326 } else {
4327 // We matched a built-in operator. Convert the arguments, then
4328 // break out so that we will build the appropriate built-in
4329 // operator node.
4330 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4331 Best->Conversions[0], "passing"))
4332 return ExprError();
4333
4334 break;
4335 }
4336 }
4337
4338 case OR_No_Viable_Function:
4339 // No viable function; fall through to handling this as a
4340 // built-in operator, which will produce an error message for us.
4341 break;
4342
4343 case OR_Ambiguous:
4344 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4345 << UnaryOperator::getOpcodeStr(Opc)
4346 << Input->getSourceRange();
4347 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4348 return ExprError();
4349
4350 case OR_Deleted:
4351 Diag(OpLoc, diag::err_ovl_deleted_oper)
4352 << Best->Function->isDeleted()
4353 << UnaryOperator::getOpcodeStr(Opc)
4354 << Input->getSourceRange();
4355 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4356 return ExprError();
4357 }
4358
4359 // Either we found no viable overloaded operator or we matched a
4360 // built-in operator. In either case, fall through to trying to
4361 // build a built-in operation.
4362 input.release();
4363 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4364}
4365
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004366/// \brief Create a binary operation that may resolve to an overloaded
4367/// operator.
4368///
4369/// \param OpLoc The location of the operator itself (e.g., '+').
4370///
4371/// \param OpcIn The BinaryOperator::Opcode that describes this
4372/// operator.
4373///
4374/// \param Functions The set of non-member functions that will be
4375/// considered by overload resolution. The caller needs to build this
4376/// set based on the context using, e.g.,
4377/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4378/// set should not contain any member functions; those will be added
4379/// by CreateOverloadedBinOp().
4380///
4381/// \param LHS Left-hand argument.
4382/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004383Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004384Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004385 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004386 FunctionSet &Functions,
4387 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004388 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004389 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004390
4391 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4392 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4393 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4394
4395 // If either side is type-dependent, create an appropriate dependent
4396 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004397 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004398 // .* cannot be overloaded.
4399 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004400 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004401 Context.DependentTy, OpLoc));
4402
Mike Stump11289f42009-09-09 15:08:12 +00004403 OverloadedFunctionDecl *Overloads
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004404 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004405 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004406 FuncEnd = Functions.end();
4407 Func != FuncEnd; ++Func)
4408 Overloads->addOverload(*Func);
4409
4410 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4411 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004412
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004413 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004414 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004415 Context.DependentTy,
4416 OpLoc));
4417 }
4418
4419 // If this is the .* operator, which is not overloadable, just
4420 // create a built-in binary operator.
4421 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004422 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004423
4424 // If this is one of the assignment operators, we only perform
4425 // overload resolution if the left-hand side is a class or
4426 // enumeration type (C++ [expr.ass]p3).
4427 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregore9899d92009-08-26 17:08:25 +00004428 !Args[0]->getType()->isOverloadableType())
4429 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004430
Douglas Gregor084d8552009-03-13 23:49:33 +00004431 // Build an empty overload set.
4432 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004433
4434 // Add the candidates from the given function set.
4435 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4436
4437 // Add operator candidates that are member functions.
4438 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4439
4440 // Add builtin operator candidates.
4441 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4442
4443 // Perform overload resolution.
4444 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004445 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004446 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004447 // We found a built-in operator or an overloaded operator.
4448 FunctionDecl *FnDecl = Best->Function;
4449
4450 if (FnDecl) {
4451 // We matched an overloaded operator. Build a call to that
4452 // operator.
4453
4454 // Convert the arguments.
4455 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004456 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4457 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004458 "passing"))
4459 return ExprError();
4460 } else {
4461 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004462 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004463 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004464 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004465 "passing"))
4466 return ExprError();
4467 }
4468
4469 // Determine the result type
4470 QualType ResultTy
4471 = FnDecl->getType()->getAsFunctionType()->getResultType();
4472 ResultTy = ResultTy.getNonReferenceType();
4473
4474 // Build the actual expression node.
4475 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004476 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004477 UsualUnaryConversions(FnExpr);
4478
Mike Stump11289f42009-09-09 15:08:12 +00004479 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004480 Args, 2, ResultTy, OpLoc);
4481 return MaybeBindToTemporary(CE);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004482 } else {
4483 // We matched a built-in operator. Convert the arguments, then
4484 // break out so that we will build the appropriate built-in
4485 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004486 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004487 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004488 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004489 Best->Conversions[1], "passing"))
4490 return ExprError();
4491
4492 break;
4493 }
4494 }
4495
4496 case OR_No_Viable_Function:
Sebastian Redl027de2a2009-05-21 11:50:50 +00004497 // For class as left operand for assignment or compound assigment operator
4498 // do not fall through to handling in built-in, but report that no overloaded
4499 // assignment operator found
Douglas Gregore9899d92009-08-26 17:08:25 +00004500 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004501 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4502 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004503 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl027de2a2009-05-21 11:50:50 +00004504 return ExprError();
4505 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004506 // No viable function; fall through to handling this as a
4507 // built-in operator, which will produce an error message for us.
4508 break;
4509
4510 case OR_Ambiguous:
4511 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4512 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004513 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004514 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4515 return ExprError();
4516
4517 case OR_Deleted:
4518 Diag(OpLoc, diag::err_ovl_deleted_oper)
4519 << Best->Function->isDeleted()
4520 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004521 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004522 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4523 return ExprError();
4524 }
4525
4526 // Either we found no viable overloaded operator or we matched a
4527 // built-in operator. In either case, try to build a built-in
4528 // operation.
Douglas Gregore9899d92009-08-26 17:08:25 +00004529 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004530}
4531
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004532/// BuildCallToMemberFunction - Build a call to a member
4533/// function. MemExpr is the expression that refers to the member
4534/// function (and includes the object parameter), Args/NumArgs are the
4535/// arguments to the function call (not including the object
4536/// parameter). The caller needs to validate that the member
4537/// expression refers to a member function or an overloaded member
4538/// function.
4539Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00004540Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4541 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004542 unsigned NumArgs, SourceLocation *CommaLocs,
4543 SourceLocation RParenLoc) {
4544 // Dig out the member expression. This holds both the object
4545 // argument and the member function we're referring to.
4546 MemberExpr *MemExpr = 0;
4547 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4548 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4549 else
4550 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4551 assert(MemExpr && "Building member call without member expression");
4552
4553 // Extract the object argument.
4554 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004555
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004556 CXXMethodDecl *Method = 0;
Douglas Gregor97628d62009-08-21 00:16:32 +00004557 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4558 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004559 // Add overload candidates
4560 OverloadCandidateSet CandidateSet;
Douglas Gregor97628d62009-08-21 00:16:32 +00004561 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004562
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004563 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4564 Func != FuncEnd; ++Func) {
4565 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
Mike Stump11289f42009-09-09 15:08:12 +00004566 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004567 /*SuppressUserConversions=*/false);
4568 else
Douglas Gregor84f14dd2009-09-01 00:37:14 +00004569 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4570 MemExpr->hasExplicitTemplateArgumentList(),
4571 MemExpr->getTemplateArgs(),
4572 MemExpr->getNumTemplateArgs(),
4573 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004574 CandidateSet,
4575 /*SuppressUsedConversions=*/false);
4576 }
Mike Stump11289f42009-09-09 15:08:12 +00004577
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004578 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004579 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004580 case OR_Success:
4581 Method = cast<CXXMethodDecl>(Best->Function);
4582 break;
4583
4584 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004585 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004586 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004587 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004588 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4589 // FIXME: Leaking incoming expressions!
4590 return true;
4591
4592 case OR_Ambiguous:
Mike Stump11289f42009-09-09 15:08:12 +00004593 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004594 diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004595 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004596 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4597 // FIXME: Leaking incoming expressions!
4598 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004599
4600 case OR_Deleted:
Mike Stump11289f42009-09-09 15:08:12 +00004601 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00004602 diag::err_ovl_deleted_member_call)
4603 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00004604 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004605 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4606 // FIXME: Leaking incoming expressions!
4607 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004608 }
4609
4610 FixOverloadedFunctionReference(MemExpr, Method);
4611 } else {
4612 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4613 }
4614
4615 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00004616 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004617 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00004618 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004619 Method->getResultType().getNonReferenceType(),
4620 RParenLoc));
4621
4622 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00004623 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004624 PerformObjectArgumentInitialization(ObjectArg, Method))
4625 return true;
4626 MemExpr->setBase(ObjectArg);
4627
4628 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004629 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004630 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004631 RParenLoc))
4632 return true;
4633
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004634 if (CheckFunctionCall(Method, TheCall.get()))
4635 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00004636
4637 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004638}
4639
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004640/// BuildCallToObjectOfClassType - Build a call to an object of class
4641/// type (C++ [over.call.object]), which can end up invoking an
4642/// overloaded function call operator (@c operator()) or performing a
4643/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00004644Sema::ExprResult
4645Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00004646 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004647 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004648 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004649 SourceLocation RParenLoc) {
4650 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004651 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00004652
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004653 // C++ [over.call.object]p1:
4654 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00004655 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004656 // candidate functions includes at least the function call
4657 // operators of T. The function call operators of T are obtained by
4658 // ordinary lookup of the name operator() in the context of
4659 // (E).operator().
4660 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00004661 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004662 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004663 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004664 Oper != OperEnd; ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00004665 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor55297ac2008-12-23 00:26:44 +00004666 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004667
Douglas Gregorab7897a2008-11-19 22:57:39 +00004668 // C++ [over.call.object]p2:
4669 // In addition, for each conversion function declared in T of the
4670 // form
4671 //
4672 // operator conversion-type-id () cv-qualifier;
4673 //
4674 // where cv-qualifier is the same cv-qualification as, or a
4675 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00004676 // denotes the type "pointer to function of (P1,...,Pn) returning
4677 // R", or the type "reference to pointer to function of
4678 // (P1,...,Pn) returning R", or the type "reference to function
4679 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00004680 // is also considered as a candidate function. Similarly,
4681 // surrogate call functions are added to the set of candidate
4682 // functions for each conversion function declared in an
4683 // accessible base class provided the function is not hidden
4684 // within T by another intervening declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004685
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004686 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4687 // FIXME: Look in base classes for more conversion operators!
Mike Stump11289f42009-09-09 15:08:12 +00004688 OverloadedFunctionDecl *Conversions
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004689 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00004690 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004691 Func = Conversions->function_begin(),
4692 FuncEnd = Conversions->function_end();
4693 Func != FuncEnd; ++Func) {
4694 CXXConversionDecl *Conv;
4695 FunctionTemplateDecl *ConvTemplate;
4696 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00004697
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004698 // Skip over templated conversion functions; they aren't
4699 // surrogates.
4700 if (ConvTemplate)
4701 continue;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004702
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004703 // Strip the reference type (if any) and then the pointer type (if
4704 // any) to get down to what might be a function type.
4705 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4706 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4707 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004708
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004709 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
4710 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4711 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004712 }
Mike Stump11289f42009-09-09 15:08:12 +00004713
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004714 // Perform overload resolution.
4715 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004716 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004717 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00004718 // Overload resolution succeeded; we'll build the appropriate call
4719 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004720 break;
4721
4722 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004723 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00004724 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004725 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00004726 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004727 break;
4728
4729 case OR_Ambiguous:
4730 Diag(Object->getSourceRange().getBegin(),
4731 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004732 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004733 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4734 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004735
4736 case OR_Deleted:
4737 Diag(Object->getSourceRange().getBegin(),
4738 diag::err_ovl_deleted_object_call)
4739 << Best->Function->isDeleted()
4740 << Object->getType() << Object->getSourceRange();
4741 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4742 break;
Mike Stump11289f42009-09-09 15:08:12 +00004743 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004744
Douglas Gregorab7897a2008-11-19 22:57:39 +00004745 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004746 // We had an error; delete all of the subexpressions and return
4747 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00004748 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004749 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00004750 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004751 return true;
4752 }
4753
Douglas Gregorab7897a2008-11-19 22:57:39 +00004754 if (Best->Function == 0) {
4755 // Since there is no function declaration, this is one of the
4756 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00004757 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00004758 = cast<CXXConversionDecl>(
4759 Best->Conversions[0].UserDefined.ConversionFunction);
4760
4761 // We selected one of the surrogate functions that converts the
4762 // object parameter to a function pointer. Perform the conversion
4763 // on the object argument, then let ActOnCallExpr finish the job.
4764 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004765 ImpCastExprToType(Object,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004766 Conv->getConversionType().getNonReferenceType(),
Anders Carlssona076d142009-07-31 01:23:52 +00004767 CastExpr::CK_Unknown,
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004768 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004769 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4770 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4771 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004772 }
4773
4774 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4775 // that calls this method, using Object for the implicit object
4776 // parameter and passing along the remaining arguments.
4777 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004778 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004779
4780 unsigned NumArgsInProto = Proto->getNumArgs();
4781 unsigned NumArgsToCheck = NumArgs;
4782
4783 // Build the full argument list for the method call (the
4784 // implicit object parameter is placed at the beginning of the
4785 // list).
4786 Expr **MethodArgs;
4787 if (NumArgs < NumArgsInProto) {
4788 NumArgsToCheck = NumArgsInProto;
4789 MethodArgs = new Expr*[NumArgsInProto + 1];
4790 } else {
4791 MethodArgs = new Expr*[NumArgs + 1];
4792 }
4793 MethodArgs[0] = Object;
4794 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4795 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00004796
4797 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004798 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004799 UsualUnaryConversions(NewFn);
4800
4801 // Once we've built TheCall, all of the expressions are properly
4802 // owned.
4803 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004804 ExprOwningPtr<CXXOperatorCallExpr>
4805 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004806 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00004807 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004808 delete [] MethodArgs;
4809
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004810 // We may have default arguments. If so, we need to allocate more
4811 // slots in the call for them.
4812 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00004813 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004814 else if (NumArgs > NumArgsInProto)
4815 NumArgsToCheck = NumArgsInProto;
4816
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004817 bool IsError = false;
4818
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004819 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004820 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004821 TheCall->setArg(0, Object);
4822
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004823
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004824 // Check the argument types.
4825 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004826 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004827 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004828 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00004829
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004830 // Pass the argument.
4831 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004832 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004833 } else {
Anders Carlssone8271232009-08-14 18:30:22 +00004834 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004835 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004836
4837 TheCall->setArg(i + 1, Arg);
4838 }
4839
4840 // If this is a variadic call, handle args passed through "...".
4841 if (Proto->isVariadic()) {
4842 // Promote the arguments (C99 6.5.2.2p7).
4843 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4844 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004845 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004846 TheCall->setArg(i + 1, Arg);
4847 }
4848 }
4849
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004850 if (IsError) return true;
4851
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004852 if (CheckFunctionCall(Method, TheCall.get()))
4853 return true;
4854
Anders Carlsson1c83deb2009-08-16 03:53:54 +00004855 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004856}
4857
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004858/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00004859/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004860/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00004861Sema::OwningExprResult
4862Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4863 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004864 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00004865
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004866 // C++ [over.ref]p1:
4867 //
4868 // [...] An expression x->m is interpreted as (x.operator->())->m
4869 // for a class object x of type T if T::operator->() exists and if
4870 // the operator is selected as the best match function by the
4871 // overload resolution mechanism (13.3).
4872 // FIXME: look in base classes.
4873 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4874 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004875 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00004876
Anders Carlsson78b54932009-09-10 23:18:36 +00004877 LookupResult R = LookupQualifiedName(BaseRecord->getDecl(), OpName,
4878 LookupOrdinaryName);
4879
4880 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
4881 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00004882 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004883 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004884
4885 // Perform overload resolution.
4886 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004887 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004888 case OR_Success:
4889 // Overload resolution succeeded; we'll build the call below.
4890 break;
4891
4892 case OR_No_Viable_Function:
4893 if (CandidateSet.empty())
4894 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00004895 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004896 else
4897 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00004898 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004899 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00004900 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004901
4902 case OR_Ambiguous:
4903 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00004904 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004905 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00004906 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004907
4908 case OR_Deleted:
4909 Diag(OpLoc, diag::err_ovl_deleted_oper)
4910 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00004911 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004912 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00004913 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004914 }
4915
4916 // Convert the object parameter.
4917 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00004918 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00004919 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00004920
4921 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00004922 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004923
4924 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00004925 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4926 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004927 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004928 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004929 Method->getResultType().getNonReferenceType(),
4930 OpLoc);
Douglas Gregord8061562009-08-06 03:17:00 +00004931 return Owned(Base);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004932}
4933
Douglas Gregorcd695e52008-11-10 20:40:00 +00004934/// FixOverloadedFunctionReference - E is an expression that refers to
4935/// a C++ overloaded function (possibly with some parentheses and
4936/// perhaps a '&' around it). We have resolved the overloaded function
4937/// to the function declaration Fn, so patch up the expression E to
4938/// refer (possibly indirectly) to Fn.
4939void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4940 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4941 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4942 E->setType(PE->getSubExpr()->getType());
4943 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00004944 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00004945 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004946 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4947 if (Method->isStatic()) {
4948 // Do nothing: static member functions aren't any different
4949 // from non-member functions.
Mike Stump11289f42009-09-09 15:08:12 +00004950 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004951 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4952 // We have taken the address of a pointer to member
4953 // function. Perform the computation here so that we get the
4954 // appropriate pointer to member type.
4955 DRE->setDecl(Fn);
4956 DRE->setType(Fn->getType());
4957 QualType ClassType
4958 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
Mike Stump11289f42009-09-09 15:08:12 +00004959 E->setType(Context.getMemberPointerType(Fn->getType(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004960 ClassType.getTypePtr()));
4961 return;
4962 }
4963 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004964 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00004965 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregorcd695e52008-11-10 20:40:00 +00004966 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor9b146582009-07-08 20:55:45 +00004967 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Mike Stump11289f42009-09-09 15:08:12 +00004968 isa<FunctionTemplateDecl>(DR->getDecl())) &&
Douglas Gregor9b146582009-07-08 20:55:45 +00004969 "Expected overloaded function or function template");
Douglas Gregorcd695e52008-11-10 20:40:00 +00004970 DR->setDecl(Fn);
4971 E->setType(Fn->getType());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004972 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4973 MemExpr->setMemberDecl(Fn);
4974 E->setType(Fn->getType());
Douglas Gregorcd695e52008-11-10 20:40:00 +00004975 } else {
4976 assert(false && "Invalid reference to overloaded function");
4977 }
4978}
4979
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004980} // end namespace clang