Deleted Added
full compact
SemaOverload.cpp (195099) SemaOverload.cpp (195341)
1//===--- 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"
15#include "SemaInherit.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/TypeOrdering.h"
22#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/Support/Compiler.h"
25#include <algorithm>
26
27namespace clang {
28
29/// GetConversionCategory - Retrieve the implicit conversion
30/// category corresponding to the given implicit conversion kind.
31ImplicitConversionCategory
32GetConversionCategory(ImplicitConversionKind Kind) {
33 static const ImplicitConversionCategory
34 Category[(int)ICK_Num_Conversion_Kinds] = {
35 ICC_Identity,
36 ICC_Lvalue_Transformation,
37 ICC_Lvalue_Transformation,
38 ICC_Lvalue_Transformation,
39 ICC_Qualification_Adjustment,
40 ICC_Promotion,
41 ICC_Promotion,
42 ICC_Promotion,
43 ICC_Conversion,
44 ICC_Conversion,
45 ICC_Conversion,
46 ICC_Conversion,
47 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion
53 };
54 return Category[(int)Kind];
55}
56
57/// GetConversionRank - Retrieve the implicit conversion rank
58/// corresponding to the given implicit conversion kind.
59ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
60 static const ImplicitConversionRank
61 Rank[(int)ICK_Num_Conversion_Kinds] = {
62 ICR_Exact_Match,
63 ICR_Exact_Match,
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Promotion,
68 ICR_Promotion,
69 ICR_Promotion,
70 ICR_Conversion,
71 ICR_Conversion,
72 ICR_Conversion,
73 ICR_Conversion,
74 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion
80 };
81 return Rank[(int)Kind];
82}
83
84/// GetImplicitConversionName - Return the name of this kind of
85/// implicit conversion.
86const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
87 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
88 "No conversion",
89 "Lvalue-to-rvalue",
90 "Array-to-pointer",
91 "Function-to-pointer",
92 "Qualification",
93 "Integral promotion",
94 "Floating point promotion",
95 "Complex promotion",
96 "Integral conversion",
97 "Floating conversion",
98 "Complex conversion",
99 "Floating-integral conversion",
100 "Complex-real conversion",
101 "Pointer conversion",
102 "Pointer-to-member conversion",
103 "Boolean conversion",
104 "Compatible-types conversion",
105 "Derived-to-base conversion"
106 };
107 return Name[Kind];
108}
109
110/// StandardConversionSequence - Set the standard conversion
111/// sequence to the identity conversion.
112void StandardConversionSequence::setAsIdentityConversion() {
113 First = ICK_Identity;
114 Second = ICK_Identity;
115 Third = ICK_Identity;
116 Deprecated = false;
117 ReferenceBinding = false;
118 DirectBinding = false;
119 RRefBinding = false;
120 CopyConstructor = 0;
121}
122
123/// getRank - Retrieve the rank of this standard conversion sequence
124/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
125/// implicit conversions.
126ImplicitConversionRank StandardConversionSequence::getRank() const {
127 ImplicitConversionRank Rank = ICR_Exact_Match;
128 if (GetConversionRank(First) > Rank)
129 Rank = GetConversionRank(First);
130 if (GetConversionRank(Second) > Rank)
131 Rank = GetConversionRank(Second);
132 if (GetConversionRank(Third) > Rank)
133 Rank = GetConversionRank(Third);
134 return Rank;
135}
136
137/// isPointerConversionToBool - Determines whether this conversion is
138/// a conversion of a pointer or pointer-to-member to bool. This is
139/// used as part of the ranking of standard conversion sequences
140/// (C++ 13.3.3.2p4).
141bool StandardConversionSequence::isPointerConversionToBool() const
142{
143 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
144 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
145
146 // Note that FromType has not necessarily been transformed by the
147 // array-to-pointer or function-to-pointer implicit conversions, so
148 // check for their presence as well as checking whether FromType is
149 // a pointer.
150 if (ToType->isBooleanType() &&
151 (FromType->isPointerType() || FromType->isBlockPointerType() ||
152 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
153 return true;
154
155 return false;
156}
157
158/// isPointerConversionToVoidPointer - Determines whether this
159/// conversion is a conversion of a pointer to a void pointer. This is
160/// used as part of the ranking of standard conversion sequences (C++
161/// 13.3.3.2p4).
162bool
163StandardConversionSequence::
164isPointerConversionToVoidPointer(ASTContext& Context) const
165{
166 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)
176 if (const PointerType* ToPtrType = ToType->getAsPointerType())
177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
182/// 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));
196
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 }
204 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 }
227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
228 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
263// FunctionDecl that New cannot be overloaded with.
264//
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",
272// so IsOverload will not be used.
273//
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
286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl)
288{
289 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
290 // Is this new function an overload of every function in the
291 // overload set?
292 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
293 FuncEnd = Ovl->function_end();
294 for (; Func != FuncEnd; ++Func) {
295 if (!IsOverload(New, *Func, MatchedDecl)) {
296 MatchedDecl = Func;
297 return false;
298 }
299 }
300
301 // This function overloads every function in the overload set.
302 return true;
303 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
304 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
305 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
306 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
307 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
308
309 // C++ [temp.fct]p2:
310 // A function template can be overloaded with other function templates
311 // and with normal (non-template) functions.
312 if ((OldTemplate == 0) != (NewTemplate == 0))
313 return true;
314
315 // Is the function New an overload of the function Old?
316 QualType OldQType = Context.getCanonicalType(Old->getType());
317 QualType NewQType = Context.getCanonicalType(New->getType());
318
319 // Compare the signatures (C++ 1.3.10) of the two functions to
320 // determine whether they are overloads. If we find any mismatch
321 // in the signature, they are overloads.
322
323 // If either of these functions is a K&R-style function (no
324 // prototype), then we consider them to have matching signatures.
325 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
326 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
327 return false;
328
329 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
330 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
331
332 // The signature of a function includes the types of its
333 // parameters (C++ 1.3.10), which includes the presence or absence
334 // of the ellipsis; see C++ DR 357).
335 if (OldQType != NewQType &&
336 (OldType->getNumArgs() != NewType->getNumArgs() ||
337 OldType->isVariadic() != NewType->isVariadic() ||
338 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
339 NewType->arg_type_begin())))
340 return true;
341
342 // C++ [temp.over.link]p4:
343 // The signature of a function template consists of its function
344 // signature, its return type and its template parameter list. The names
345 // of the template parameters are significant only for establishing the
346 // relationship between the template parameters and the rest of the
347 // signature.
348 //
349 // We check the return type and template parameter lists for function
350 // templates first; the remaining checks follow.
351 if (NewTemplate &&
352 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
353 OldTemplate->getTemplateParameters(),
354 false, false, SourceLocation()) ||
355 OldType->getResultType() != NewType->getResultType()))
356 return true;
357
358 // If the function is a class member, its signature includes the
359 // cv-qualifiers (if any) on the function itself.
360 //
361 // As part of this, also check whether one of the member functions
362 // is static, in which case they are not overloads (C++
363 // 13.1p2). While not part of the definition of the signature,
364 // this check is important to determine whether these functions
365 // can be overloaded.
366 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
367 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
368 if (OldMethod && NewMethod &&
369 !OldMethod->isStatic() && !NewMethod->isStatic() &&
370 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
371 return true;
372
373 // The signatures match; this is not an overload.
374 return false;
375 } else {
376 // (C++ 13p1):
377 // Only function declarations can be overloaded; object and type
378 // declarations cannot be overloaded.
379 return false;
380 }
381}
382
383/// TryImplicitConversion - Attempt to perform an implicit conversion
384/// from the given expression (Expr) to the given type (ToType). This
385/// function returns an implicit conversion sequence that can be used
386/// to perform the initialization. Given
387///
388/// void f(float f);
389/// void g(int i) { f(i); }
390///
391/// this routine would produce an implicit conversion sequence to
392/// describe the initialization of f from i, which will be a standard
393/// conversion sequence containing an lvalue-to-rvalue conversion (C++
394/// 4.1) followed by a floating-integral conversion (C++ 4.9).
395//
396/// Note that this routine only determines how the conversion can be
397/// performed; it does not actually perform the conversion. As such,
398/// it will not produce any diagnostics if no conversion is available,
399/// but will instead return an implicit conversion sequence of kind
400/// "BadConversion".
401///
402/// If @p SuppressUserConversions, then user-defined conversions are
403/// not permitted.
404/// If @p AllowExplicit, then explicit user-defined conversions are
405/// permitted.
406/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
407/// no matter its actual lvalueness.
408ImplicitConversionSequence
409Sema::TryImplicitConversion(Expr* From, QualType ToType,
410 bool SuppressUserConversions,
411 bool AllowExplicit, bool ForceRValue)
412{
413 ImplicitConversionSequence ICS;
414 if (IsStandardConversion(From, ToType, ICS.Standard))
415 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
416 else if (getLangOptions().CPlusPlus &&
417 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
418 !SuppressUserConversions, AllowExplicit,
419 ForceRValue)) {
420 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
421 // C++ [over.ics.user]p4:
422 // A conversion of an expression of class type to the same class
423 // type is given Exact Match rank, and a conversion of an
424 // expression of class type to a base class of that type is
425 // given Conversion rank, in spite of the fact that a copy
426 // constructor (i.e., a user-defined conversion function) is
427 // called for those cases.
428 if (CXXConstructorDecl *Constructor
429 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
430 QualType FromCanon
431 = Context.getCanonicalType(From->getType().getUnqualifiedType());
432 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
433 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
434 // Turn this into a "standard" conversion sequence, so that it
435 // gets ranked with standard conversion sequences.
436 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
437 ICS.Standard.setAsIdentityConversion();
438 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
439 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
440 ICS.Standard.CopyConstructor = Constructor;
441 if (ToCanon != FromCanon)
442 ICS.Standard.Second = ICK_Derived_To_Base;
443 }
444 }
445
446 // C++ [over.best.ics]p4:
447 // However, when considering the argument of a user-defined
448 // conversion function that is a candidate by 13.3.1.3 when
449 // invoked for the copying of the temporary in the second step
450 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
451 // 13.3.1.6 in all cases, only standard conversion sequences and
452 // ellipsis conversion sequences are allowed.
453 if (SuppressUserConversions &&
454 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
455 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
456 } else
457 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
458
459 return ICS;
460}
461
462/// IsStandardConversion - Determines whether there is a standard
463/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
464/// expression From to the type ToType. Standard conversion sequences
465/// only consider non-class types; for conversions that involve class
466/// types, use TryImplicitConversion. If a conversion exists, SCS will
467/// contain the standard conversion sequence required to perform this
468/// conversion and this routine will return true. Otherwise, this
469/// routine will return false and the value of SCS is unspecified.
470bool
471Sema::IsStandardConversion(Expr* From, QualType ToType,
472 StandardConversionSequence &SCS)
473{
474 QualType FromType = From->getType();
475
476 // Standard conversions (C++ [conv])
477 SCS.setAsIdentityConversion();
478 SCS.Deprecated = false;
479 SCS.IncompatibleObjC = false;
480 SCS.FromTypePtr = FromType.getAsOpaquePtr();
481 SCS.CopyConstructor = 0;
482
483 // There are no standard conversions for class types in C++, so
484 // abort early. When overloading in C, however, we do permit
485 if (FromType->isRecordType() || ToType->isRecordType()) {
486 if (getLangOptions().CPlusPlus)
487 return false;
488
489 // When we're overloading in C, we allow, as standard conversions,
490 }
491
492 // The first conversion can be an lvalue-to-rvalue conversion,
493 // array-to-pointer conversion, or function-to-pointer conversion
494 // (C++ 4p1).
495
496 // Lvalue-to-rvalue conversion (C++ 4.1):
497 // An lvalue (3.10) of a non-function, non-array type T can be
498 // converted to an rvalue.
499 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
500 if (argIsLvalue == Expr::LV_Valid &&
501 !FromType->isFunctionType() && !FromType->isArrayType() &&
502 Context.getCanonicalType(FromType) != Context.OverloadTy) {
503 SCS.First = ICK_Lvalue_To_Rvalue;
504
505 // If T is a non-class type, the type of the rvalue is the
506 // cv-unqualified version of T. Otherwise, the type of the rvalue
507 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
508 // just strip the qualifiers because they don't matter.
509
510 // FIXME: Doesn't see through to qualifiers behind a typedef!
511 FromType = FromType.getUnqualifiedType();
512 }
513 // Array-to-pointer conversion (C++ 4.2)
514 else if (FromType->isArrayType()) {
515 SCS.First = ICK_Array_To_Pointer;
516
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).
524 SCS.Deprecated = true;
525
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)
530 SCS.Second = ICK_Identity;
531 SCS.Third = ICK_Qualification;
532 SCS.ToTypePtr = ToType.getAsOpaquePtr();
533 return true;
534 }
535 }
536 // Function-to-pointer conversion (C++ 4.3).
537 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
538 SCS.First = ICK_Function_To_Pointer;
539
540 // An lvalue of function type T can be converted to an rvalue of
541 // type "pointer to T." The result is a pointer to the
542 // function. (C++ 4.3p1).
543 FromType = Context.getPointerType(FromType);
544 }
545 // Address of overloaded function (C++ [over.over]).
546 else if (FunctionDecl *Fn
547 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
548 SCS.First = ICK_Function_To_Pointer;
549
550 // We were able to resolve the address of the overloaded function,
551 // so we can convert to the type of that function.
552 FromType = Fn->getType();
553 if (ToType->isLValueReferenceType())
554 FromType = Context.getLValueReferenceType(FromType);
555 else if (ToType->isRValueReferenceType())
556 FromType = Context.getRValueReferenceType(FromType);
557 else if (ToType->isMemberPointerType()) {
558 // Resolve address only succeeds if both sides are member pointers,
559 // but it doesn't have to be the same class. See DR 247.
560 // Note that this means that the type of &Derived::fn can be
561 // Ret (Base::*)(Args) if the fn overload actually found is from the
562 // base class, even if it was brought into the derived class via a
563 // using declaration. The standard isn't clear on this issue at all.
564 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
565 FromType = Context.getMemberPointerType(FromType,
566 Context.getTypeDeclType(M->getParent()).getTypePtr());
567 } else
568 FromType = Context.getPointerType(FromType);
569 }
570 // We don't require any conversions for the first step.
571 else {
572 SCS.First = ICK_Identity;
573 }
574
575 // The second conversion can be an integral promotion, floating
576 // point promotion, integral conversion, floating point conversion,
577 // floating-integral conversion, pointer conversion,
578 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
579 // For overloading in C, this can also be a "compatible-type"
580 // conversion.
581 bool IncompatibleObjC = false;
582 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
583 // The unqualified versions of the types are the same: there's no
584 // conversion to do.
585 SCS.Second = ICK_Identity;
586 }
587 // Integral promotion (C++ 4.5).
588 else if (IsIntegralPromotion(From, FromType, ToType)) {
589 SCS.Second = ICK_Integral_Promotion;
590 FromType = ToType.getUnqualifiedType();
591 }
592 // Floating point promotion (C++ 4.6).
593 else if (IsFloatingPointPromotion(FromType, ToType)) {
594 SCS.Second = ICK_Floating_Promotion;
595 FromType = ToType.getUnqualifiedType();
596 }
597 // Complex promotion (Clang extension)
598 else if (IsComplexPromotion(FromType, ToType)) {
599 SCS.Second = ICK_Complex_Promotion;
600 FromType = ToType.getUnqualifiedType();
601 }
602 // Integral conversions (C++ 4.7).
603 // FIXME: isIntegralType shouldn't be true for enums in C++.
604 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
605 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
606 SCS.Second = ICK_Integral_Conversion;
607 FromType = ToType.getUnqualifiedType();
608 }
609 // Floating point conversions (C++ 4.8).
610 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
611 SCS.Second = ICK_Floating_Conversion;
612 FromType = ToType.getUnqualifiedType();
613 }
614 // Complex conversions (C99 6.3.1.6)
615 else if (FromType->isComplexType() && ToType->isComplexType()) {
616 SCS.Second = ICK_Complex_Conversion;
617 FromType = ToType.getUnqualifiedType();
618 }
619 // Floating-integral conversions (C++ 4.9).
620 // FIXME: isIntegralType shouldn't be true for enums in C++.
621 else if ((FromType->isFloatingType() &&
622 ToType->isIntegralType() && !ToType->isBooleanType() &&
623 !ToType->isEnumeralType()) ||
624 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
625 ToType->isFloatingType())) {
626 SCS.Second = ICK_Floating_Integral;
627 FromType = ToType.getUnqualifiedType();
628 }
629 // Complex-real conversions (C99 6.3.1.7)
630 else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
631 (ToType->isComplexType() && FromType->isArithmeticType())) {
632 SCS.Second = ICK_Complex_Real;
633 FromType = ToType.getUnqualifiedType();
634 }
635 // Pointer conversions (C++ 4.10).
636 else if (IsPointerConversion(From, FromType, ToType, FromType,
637 IncompatibleObjC)) {
638 SCS.Second = ICK_Pointer_Conversion;
639 SCS.IncompatibleObjC = IncompatibleObjC;
640 }
641 // Pointer to member conversions (4.11).
642 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
643 SCS.Second = ICK_Pointer_Member;
644 }
645 // Boolean conversions (C++ 4.12).
646 else if (ToType->isBooleanType() &&
647 (FromType->isArithmeticType() ||
648 FromType->isEnumeralType() ||
649 FromType->isPointerType() ||
650 FromType->isBlockPointerType() ||
651 FromType->isMemberPointerType() ||
652 FromType->isNullPtrType())) {
653 SCS.Second = ICK_Boolean_Conversion;
654 FromType = Context.BoolTy;
655 }
656 // Compatible conversions (Clang extension for C function overloading)
657 else if (!getLangOptions().CPlusPlus &&
658 Context.typesAreCompatible(ToType, FromType)) {
659 SCS.Second = ICK_Compatible_Conversion;
660 } else {
661 // No second conversion required.
662 SCS.Second = ICK_Identity;
663 }
664
665 QualType CanonFrom;
666 QualType CanonTo;
667 // The third conversion can be a qualification conversion (C++ 4p1).
668 if (IsQualificationConversion(FromType, ToType)) {
669 SCS.Third = ICK_Qualification;
670 FromType = ToType;
671 CanonFrom = Context.getCanonicalType(FromType);
672 CanonTo = Context.getCanonicalType(ToType);
673 } else {
674 // No conversion required
675 SCS.Third = ICK_Identity;
676
677 // C++ [over.best.ics]p6:
678 // [...] Any difference in top-level cv-qualification is
679 // subsumed by the initialization itself and does not constitute
680 // a conversion. [...]
681 CanonFrom = Context.getCanonicalType(FromType);
682 CanonTo = Context.getCanonicalType(ToType);
683 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
684 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
685 FromType = ToType;
686 CanonFrom = CanonTo;
687 }
688 }
689
690 // If we have not converted the argument type to the parameter type,
691 // this is a bad conversion sequence.
692 if (CanonFrom != CanonTo)
693 return false;
694
695 SCS.ToTypePtr = FromType.getAsOpaquePtr();
696 return true;
697}
698
699/// IsIntegralPromotion - Determines whether the conversion from the
700/// expression From (whose potentially-adjusted type is FromType) to
701/// ToType is an integral promotion (C++ 4.5). If so, returns true and
702/// sets PromotedType to the promoted type.
703bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
704{
705 const BuiltinType *To = ToType->getAsBuiltinType();
706 // All integers are built-in.
707 if (!To) {
708 return false;
709 }
710
711 // An rvalue of type char, signed char, unsigned char, short int, or
712 // unsigned short int can be converted to an rvalue of type int if
713 // int can represent all the values of the source type; otherwise,
714 // the source rvalue can be converted to an rvalue of type unsigned
715 // int (C++ 4.5p1).
716 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
717 if (// We can promote any signed, promotable integer type to an int
718 (FromType->isSignedIntegerType() ||
719 // We can promote any unsigned integer type whose size is
720 // less than int to an int.
721 (!FromType->isSignedIntegerType() &&
722 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
723 return To->getKind() == BuiltinType::Int;
724 }
725
726 return To->getKind() == BuiltinType::UInt;
727 }
728
729 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
730 // can be converted to an rvalue of the first of the following types
731 // that can represent all the values of its underlying type: int,
732 // unsigned int, long, or unsigned long (C++ 4.5p2).
733 if ((FromType->isEnumeralType() || FromType->isWideCharType())
734 && ToType->isIntegerType()) {
735 // Determine whether the type we're converting from is signed or
736 // unsigned.
737 bool FromIsSigned;
738 uint64_t FromSize = Context.getTypeSize(FromType);
739 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
740 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
741 FromIsSigned = UnderlyingType->isSignedIntegerType();
742 } else {
743 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
744 FromIsSigned = true;
745 }
746
747 // The types we'll try to promote to, in the appropriate
748 // order. Try each of these types.
749 QualType PromoteTypes[6] = {
750 Context.IntTy, Context.UnsignedIntTy,
751 Context.LongTy, Context.UnsignedLongTy ,
752 Context.LongLongTy, Context.UnsignedLongLongTy
753 };
754 for (int Idx = 0; Idx < 6; ++Idx) {
755 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
756 if (FromSize < ToSize ||
757 (FromSize == ToSize &&
758 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
759 // We found the type that we can promote to. If this is the
760 // type we wanted, we have a promotion. Otherwise, no
761 // promotion.
762 return Context.getCanonicalType(ToType).getUnqualifiedType()
763 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
764 }
765 }
766 }
767
768 // An rvalue for an integral bit-field (9.6) can be converted to an
769 // rvalue of type int if int can represent all the values of the
770 // bit-field; otherwise, it can be converted to unsigned int if
771 // unsigned int can represent all the values of the bit-field. If
772 // the bit-field is larger yet, no integral promotion applies to
773 // it. If the bit-field has an enumerated type, it is treated as any
774 // other value of that type for promotion purposes (C++ 4.5p3).
775 // FIXME: We should delay checking of bit-fields until we actually perform the
776 // conversion.
777 using llvm::APSInt;
778 if (From)
779 if (FieldDecl *MemberDecl = From->getBitField()) {
780 APSInt BitWidth;
781 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
782 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
783 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
784 ToSize = Context.getTypeSize(ToType);
785
786 // Are we promoting to an int from a bitfield that fits in an int?
787 if (BitWidth < ToSize ||
788 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
789 return To->getKind() == BuiltinType::Int;
790 }
791
792 // Are we promoting to an unsigned int from an unsigned bitfield
793 // that fits into an unsigned int?
794 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
795 return To->getKind() == BuiltinType::UInt;
796 }
797
798 return false;
799 }
800 }
801
802 // An rvalue of type bool can be converted to an rvalue of type int,
803 // with false becoming zero and true becoming one (C++ 4.5p4).
804 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
805 return true;
806 }
807
808 return false;
809}
810
811/// IsFloatingPointPromotion - Determines whether the conversion from
812/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
813/// returns true and sets PromotedType to the promoted type.
814bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
815{
816 /// An rvalue of type float can be converted to an rvalue of type
817 /// double. (C++ 4.6p1).
818 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
819 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
820 if (FromBuiltin->getKind() == BuiltinType::Float &&
821 ToBuiltin->getKind() == BuiltinType::Double)
822 return true;
823
824 // C99 6.3.1.5p1:
825 // When a float is promoted to double or long double, or a
826 // double is promoted to long double [...].
827 if (!getLangOptions().CPlusPlus &&
828 (FromBuiltin->getKind() == BuiltinType::Float ||
829 FromBuiltin->getKind() == BuiltinType::Double) &&
830 (ToBuiltin->getKind() == BuiltinType::LongDouble))
831 return true;
832 }
833
834 return false;
835}
836
837/// \brief Determine if a conversion is a complex promotion.
838///
839/// A complex promotion is defined as a complex -> complex conversion
840/// where the conversion between the underlying real types is a
841/// floating-point or integral promotion.
842bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
843 const ComplexType *FromComplex = FromType->getAsComplexType();
844 if (!FromComplex)
845 return false;
846
847 const ComplexType *ToComplex = ToType->getAsComplexType();
848 if (!ToComplex)
849 return false;
850
851 return IsFloatingPointPromotion(FromComplex->getElementType(),
852 ToComplex->getElementType()) ||
853 IsIntegralPromotion(0, FromComplex->getElementType(),
854 ToComplex->getElementType());
855}
856
857/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
858/// the pointer type FromPtr to a pointer to type ToPointee, with the
859/// same type qualifiers as FromPtr has on its pointee type. ToType,
860/// if non-empty, will be a pointer to ToType that may or may not have
861/// the right set of qualifiers on its pointee.
862static QualType
863BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
864 QualType ToPointee, QualType ToType,
865 ASTContext &Context) {
866 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
867 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
868 unsigned Quals = CanonFromPointee.getCVRQualifiers();
869
870 // Exact qualifier match -> return the pointer type we're converting to.
871 if (CanonToPointee.getCVRQualifiers() == Quals) {
872 // ToType is exactly what we need. Return it.
873 if (ToType.getTypePtr())
874 return ToType;
875
876 // Build a pointer to ToPointee. It has the right qualifiers
877 // already.
878 return Context.getPointerType(ToPointee);
879 }
880
881 // Just build a canonical type that has the right qualifiers.
882 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
883}
884
885/// IsPointerConversion - Determines whether the conversion of the
886/// expression From, which has the (possibly adjusted) type FromType,
887/// can be converted to the type ToType via a pointer conversion (C++
888/// 4.10). If so, returns true and places the converted type (that
889/// might differ from ToType in its cv-qualifiers at some level) into
890/// ConvertedType.
891///
892/// This routine also supports conversions to and from block pointers
893/// and conversions with Objective-C's 'id', 'id<protocols...>', and
894/// pointers to interfaces. FIXME: Once we've determined the
895/// appropriate overloading rules for Objective-C, we may want to
896/// split the Objective-C checks into a different routine; however,
897/// GCC seems to consider all of these conversions to be pointer
898/// conversions, so for now they live here. IncompatibleObjC will be
899/// set if the conversion is an allowed Objective-C conversion that
900/// should result in a warning.
901bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
902 QualType& ConvertedType,
903 bool &IncompatibleObjC)
904{
905 IncompatibleObjC = false;
906 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
907 return true;
908
909 // Conversion from a null pointer constant to any Objective-C pointer type.
910 if (Context.isObjCObjectPointerType(ToType) &&
911 From->isNullPointerConstant(Context)) {
912 ConvertedType = ToType;
913 return true;
914 }
915
916 // Blocks: Block pointers can be converted to void*.
917 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
918 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
919 ConvertedType = ToType;
920 return true;
921 }
922 // Blocks: A null pointer constant can be converted to a block
923 // pointer type.
924 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
925 ConvertedType = ToType;
926 return true;
927 }
928
929 // If the left-hand-side is nullptr_t, the right side can be a null
930 // pointer constant.
931 if (ToType->isNullPtrType() && From->isNullPointerConstant(Context)) {
932 ConvertedType = ToType;
933 return true;
934 }
935
936 const PointerType* ToTypePtr = ToType->getAsPointerType();
937 if (!ToTypePtr)
938 return false;
939
940 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
941 if (From->isNullPointerConstant(Context)) {
942 ConvertedType = ToType;
943 return true;
944 }
945
946 // Beyond this point, both types need to be pointers.
947 const PointerType *FromTypePtr = FromType->getAsPointerType();
948 if (!FromTypePtr)
949 return false;
950
951 QualType FromPointeeType = FromTypePtr->getPointeeType();
952 QualType ToPointeeType = ToTypePtr->getPointeeType();
953
954 // An rvalue of type "pointer to cv T," where T is an object type,
955 // can be converted to an rvalue of type "pointer to cv void" (C++
956 // 4.10p2).
957 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
958 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
959 ToPointeeType,
960 ToType, Context);
961 return true;
962 }
963
964 // When we're overloading in C, we allow a special kind of pointer
965 // conversion for compatible-but-not-identical pointee types.
966 if (!getLangOptions().CPlusPlus &&
967 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
968 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
969 ToPointeeType,
970 ToType, Context);
971 return true;
972 }
973
974 // C++ [conv.ptr]p3:
975 //
976 // An rvalue of type "pointer to cv D," where D is a class type,
977 // can be converted to an rvalue of type "pointer to cv B," where
978 // B is a base class (clause 10) of D. If B is an inaccessible
979 // (clause 11) or ambiguous (10.2) base class of D, a program that
980 // necessitates this conversion is ill-formed. The result of the
981 // conversion is a pointer to the base class sub-object of the
982 // derived class object. The null pointer value is converted to
983 // the null pointer value of the destination type.
984 //
985 // Note that we do not check for ambiguity or inaccessibility
986 // here. That is handled by CheckPointerConversion.
987 if (getLangOptions().CPlusPlus &&
988 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
989 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
990 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
991 ToPointeeType,
992 ToType, Context);
993 return true;
994 }
995
996 return false;
997}
998
999/// isObjCPointerConversion - Determines whether this is an
1000/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1001/// with the same arguments and return values.
1002bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1003 QualType& ConvertedType,
1004 bool &IncompatibleObjC) {
1005 if (!getLangOptions().ObjC1)
1006 return false;
1007
1008 // Conversions with Objective-C's id<...>.
1009 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
1010 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
1011 ConvertedType = ToType;
1012 return true;
1013 }
1014
1015 // Beyond this point, both types need to be pointers or block pointers.
1016 QualType ToPointeeType;
1017 const PointerType* ToTypePtr = ToType->getAsPointerType();
1018 if (ToTypePtr)
1019 ToPointeeType = ToTypePtr->getPointeeType();
1020 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
1021 ToPointeeType = ToBlockPtr->getPointeeType();
1022 else
1023 return false;
1024
1025 QualType FromPointeeType;
1026 const PointerType *FromTypePtr = FromType->getAsPointerType();
1027 if (FromTypePtr)
1028 FromPointeeType = FromTypePtr->getPointeeType();
1029 else if (const BlockPointerType *FromBlockPtr
1030 = FromType->getAsBlockPointerType())
1031 FromPointeeType = FromBlockPtr->getPointeeType();
1032 else
1033 return false;
1034
1035 // Objective C++: We're able to convert from a pointer to an
1036 // interface to a pointer to a different interface.
1037 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
1038 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
1039 if (FromIface && ToIface &&
1040 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
1041 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1042 ToPointeeType,
1043 ToType, Context);
1044 return true;
1045 }
1046
1047 if (FromIface && ToIface &&
1048 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
1049 // Okay: this is some kind of implicit downcast of Objective-C
1050 // interfaces, which is permitted. However, we're going to
1051 // complain about it.
1052 IncompatibleObjC = true;
1053 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1054 ToPointeeType,
1055 ToType, Context);
1056 return true;
1057 }
1058
1059 // Objective C++: We're able to convert between "id" and a pointer
1060 // to any interface (in both directions).
1061 if ((FromIface && Context.isObjCIdStructType(ToPointeeType))
1062 || (ToIface && Context.isObjCIdStructType(FromPointeeType))) {
1063 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1064 ToPointeeType,
1065 ToType, Context);
1066 return true;
1067 }
1068
1069 // Objective C++: Allow conversions between the Objective-C "id" and
1070 // "Class", in either direction.
1071 if ((Context.isObjCIdStructType(FromPointeeType) &&
1072 Context.isObjCClassStructType(ToPointeeType)) ||
1073 (Context.isObjCClassStructType(FromPointeeType) &&
1074 Context.isObjCIdStructType(ToPointeeType))) {
1075 ConvertedType = ToType;
1076 return true;
1077 }
1078
1079 // If we have pointers to pointers, recursively check whether this
1080 // is an Objective-C conversion.
1081 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1082 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1083 IncompatibleObjC)) {
1084 // We always complain about this conversion.
1085 IncompatibleObjC = true;
1086 ConvertedType = ToType;
1087 return true;
1088 }
1089
1090 // If we have pointers to functions or blocks, check whether the only
1091 // differences in the argument and result types are in Objective-C
1092 // pointer conversions. If so, we permit the conversion (but
1093 // complain about it).
1094 const FunctionProtoType *FromFunctionType
1095 = FromPointeeType->getAsFunctionProtoType();
1096 const FunctionProtoType *ToFunctionType
1097 = ToPointeeType->getAsFunctionProtoType();
1098 if (FromFunctionType && ToFunctionType) {
1099 // If the function types are exactly the same, this isn't an
1100 // Objective-C pointer conversion.
1101 if (Context.getCanonicalType(FromPointeeType)
1102 == Context.getCanonicalType(ToPointeeType))
1103 return false;
1104
1105 // Perform the quick checks that will tell us whether these
1106 // function types are obviously different.
1107 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1108 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1109 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1110 return false;
1111
1112 bool HasObjCConversion = false;
1113 if (Context.getCanonicalType(FromFunctionType->getResultType())
1114 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1115 // Okay, the types match exactly. Nothing to do.
1116 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1117 ToFunctionType->getResultType(),
1118 ConvertedType, IncompatibleObjC)) {
1119 // Okay, we have an Objective-C pointer conversion.
1120 HasObjCConversion = true;
1121 } else {
1122 // Function types are too different. Abort.
1123 return false;
1124 }
1125
1126 // Check argument types.
1127 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1128 ArgIdx != NumArgs; ++ArgIdx) {
1129 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1130 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1131 if (Context.getCanonicalType(FromArgType)
1132 == Context.getCanonicalType(ToArgType)) {
1133 // Okay, the types match exactly. Nothing to do.
1134 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1135 ConvertedType, IncompatibleObjC)) {
1136 // Okay, we have an Objective-C pointer conversion.
1137 HasObjCConversion = true;
1138 } else {
1139 // Argument types are too different. Abort.
1140 return false;
1141 }
1142 }
1143
1144 if (HasObjCConversion) {
1145 // We had an Objective-C conversion. Allow this pointer
1146 // conversion, but complain about it.
1147 ConvertedType = ToType;
1148 IncompatibleObjC = true;
1149 return true;
1150 }
1151 }
1152
1153 return false;
1154}
1155
1156/// CheckPointerConversion - Check the pointer conversion from the
1157/// expression From to the type ToType. This routine checks for
1158/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1159/// conversions for which IsPointerConversion has already returned
1160/// true. It returns true and produces a diagnostic if there was an
1161/// error, or returns false otherwise.
1162bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1163 QualType FromType = From->getType();
1164
1165 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1166 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
1167 QualType FromPointeeType = FromPtrType->getPointeeType(),
1168 ToPointeeType = ToPtrType->getPointeeType();
1169
1170 // Objective-C++ conversions are always okay.
1171 // FIXME: We should have a different class of conversions for the
1172 // Objective-C++ implicit conversions.
1173 if (Context.isObjCIdStructType(FromPointeeType) ||
1174 Context.isObjCIdStructType(ToPointeeType) ||
1175 Context.isObjCClassStructType(FromPointeeType) ||
1176 Context.isObjCClassStructType(ToPointeeType))
1177 return false;
1178
1179 if (FromPointeeType->isRecordType() &&
1180 ToPointeeType->isRecordType()) {
1181 // We must have a derived-to-base conversion. Check an
1182 // ambiguous or inaccessible conversion.
1183 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1184 From->getExprLoc(),
1185 From->getSourceRange());
1186 }
1187 }
1188
1189 return false;
1190}
1191
1192/// IsMemberPointerConversion - Determines whether the conversion of the
1193/// expression From, which has the (possibly adjusted) type FromType, can be
1194/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1195/// If so, returns true and places the converted type (that might differ from
1196/// ToType in its cv-qualifiers at some level) into ConvertedType.
1197bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1198 QualType ToType, QualType &ConvertedType)
1199{
1200 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1201 if (!ToTypePtr)
1202 return false;
1203
1204 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1205 if (From->isNullPointerConstant(Context)) {
1206 ConvertedType = ToType;
1207 return true;
1208 }
1209
1210 // Otherwise, both types have to be member pointers.
1211 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1212 if (!FromTypePtr)
1213 return false;
1214
1215 // A pointer to member of B can be converted to a pointer to member of D,
1216 // where D is derived from B (C++ 4.11p2).
1217 QualType FromClass(FromTypePtr->getClass(), 0);
1218 QualType ToClass(ToTypePtr->getClass(), 0);
1219 // FIXME: What happens when these are dependent? Is this function even called?
1220
1221 if (IsDerivedFrom(ToClass, FromClass)) {
1222 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1223 ToClass.getTypePtr());
1224 return true;
1225 }
1226
1227 return false;
1228}
1229
1230/// CheckMemberPointerConversion - Check the member pointer conversion from the
1231/// expression From to the type ToType. This routine checks for ambiguous or
1232/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1233/// for which IsMemberPointerConversion has already returned true. It returns
1234/// true and produces a diagnostic if there was an error, or returns false
1235/// otherwise.
1236bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1237 QualType FromType = From->getType();
1238 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1239 if (!FromPtrType)
1240 return false;
1241
1242 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1243 assert(ToPtrType && "No member pointer cast has a target type "
1244 "that is not a member pointer.");
1245
1246 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1247 QualType ToClass = QualType(ToPtrType->getClass(), 0);
1248
1249 // FIXME: What about dependent types?
1250 assert(FromClass->isRecordType() && "Pointer into non-class.");
1251 assert(ToClass->isRecordType() && "Pointer into non-class.");
1252
1253 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1254 /*DetectVirtual=*/true);
1255 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1256 assert(DerivationOkay &&
1257 "Should not have been called if derivation isn't OK.");
1258 (void)DerivationOkay;
1259
1260 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1261 getUnqualifiedType())) {
1262 // Derivation is ambiguous. Redo the check to find the exact paths.
1263 Paths.clear();
1264 Paths.setRecordingPaths(true);
1265 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1266 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1267 (void)StillOkay;
1268
1269 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1270 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1271 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1272 return true;
1273 }
1274
1275 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1276 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1277 << FromClass << ToClass << QualType(VBase, 0)
1278 << From->getSourceRange();
1279 return true;
1280 }
1281
1282 return false;
1283}
1284
1285/// IsQualificationConversion - Determines whether the conversion from
1286/// an rvalue of type FromType to ToType is a qualification conversion
1287/// (C++ 4.4).
1288bool
1289Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1290{
1291 FromType = Context.getCanonicalType(FromType);
1292 ToType = Context.getCanonicalType(ToType);
1293
1294 // If FromType and ToType are the same type, this is not a
1295 // qualification conversion.
1296 if (FromType == ToType)
1297 return false;
1298
1299 // (C++ 4.4p4):
1300 // A conversion can add cv-qualifiers at levels other than the first
1301 // in multi-level pointers, subject to the following rules: [...]
1302 bool PreviousToQualsIncludeConst = true;
1303 bool UnwrappedAnyPointer = false;
1304 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
1305 // Within each iteration of the loop, we check the qualifiers to
1306 // determine if this still looks like a qualification
1307 // conversion. Then, if all is well, we unwrap one more level of
1308 // pointers or pointers-to-members and do it all again
1309 // until there are no more pointers or pointers-to-members left to
1310 // unwrap.
1311 UnwrappedAnyPointer = true;
1312
1313 // -- for every j > 0, if const is in cv 1,j then const is in cv
1314 // 2,j, and similarly for volatile.
1315 if (!ToType.isAtLeastAsQualifiedAs(FromType))
1316 return false;
1317
1318 // -- if the cv 1,j and cv 2,j are different, then const is in
1319 // every cv for 0 < k < j.
1320 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
1321 && !PreviousToQualsIncludeConst)
1322 return false;
1323
1324 // Keep track of whether all prior cv-qualifiers in the "to" type
1325 // include const.
1326 PreviousToQualsIncludeConst
1327 = PreviousToQualsIncludeConst && ToType.isConstQualified();
1328 }
1329
1330 // We are left with FromType and ToType being the pointee types
1331 // after unwrapping the original FromType and ToType the same number
1332 // of types. If we unwrapped any pointers, and if FromType and
1333 // ToType have the same unqualified type (since we checked
1334 // qualifiers above), then this is a qualification conversion.
1335 return UnwrappedAnyPointer &&
1336 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1337}
1338
1339/// Determines whether there is a user-defined conversion sequence
1340/// (C++ [over.ics.user]) that converts expression From to the type
1341/// ToType. If such a conversion exists, User will contain the
1342/// user-defined conversion sequence that performs such a conversion
1343/// and this routine will return true. Otherwise, this routine returns
1344/// false and User is unspecified.
1345///
1346/// \param AllowConversionFunctions true if the conversion should
1347/// consider conversion functions at all. If false, only constructors
1348/// will be considered.
1349///
1350/// \param AllowExplicit true if the conversion should consider C++0x
1351/// "explicit" conversion functions as well as non-explicit conversion
1352/// functions (C++0x [class.conv.fct]p2).
1353///
1354/// \param ForceRValue true if the expression should be treated as an rvalue
1355/// for overload resolution.
1356bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1357 UserDefinedConversionSequence& User,
1358 bool AllowConversionFunctions,
1359 bool AllowExplicit, bool ForceRValue)
1360{
1361 OverloadCandidateSet CandidateSet;
1362 if (const RecordType *ToRecordType = ToType->getAsRecordType()) {
1363 if (CXXRecordDecl *ToRecordDecl
1364 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1365 // C++ [over.match.ctor]p1:
1366 // When objects of class type are direct-initialized (8.5), or
1367 // copy-initialized from an expression of the same or a
1368 // derived class type (8.5), overload resolution selects the
1369 // constructor. [...] For copy-initialization, the candidate
1370 // functions are all the converting constructors (12.3.1) of
1371 // that class. The argument list is the expression-list within
1372 // the parentheses of the initializer.
1373 DeclarationName ConstructorName
1374 = Context.DeclarationNames.getCXXConstructorName(
1375 Context.getCanonicalType(ToType).getUnqualifiedType());
1376 DeclContext::lookup_iterator Con, ConEnd;
1377 for (llvm::tie(Con, ConEnd)
1//===--- 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"
15#include "SemaInherit.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/TypeOrdering.h"
22#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/Support/Compiler.h"
25#include <algorithm>
26
27namespace clang {
28
29/// GetConversionCategory - Retrieve the implicit conversion
30/// category corresponding to the given implicit conversion kind.
31ImplicitConversionCategory
32GetConversionCategory(ImplicitConversionKind Kind) {
33 static const ImplicitConversionCategory
34 Category[(int)ICK_Num_Conversion_Kinds] = {
35 ICC_Identity,
36 ICC_Lvalue_Transformation,
37 ICC_Lvalue_Transformation,
38 ICC_Lvalue_Transformation,
39 ICC_Qualification_Adjustment,
40 ICC_Promotion,
41 ICC_Promotion,
42 ICC_Promotion,
43 ICC_Conversion,
44 ICC_Conversion,
45 ICC_Conversion,
46 ICC_Conversion,
47 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion
53 };
54 return Category[(int)Kind];
55}
56
57/// GetConversionRank - Retrieve the implicit conversion rank
58/// corresponding to the given implicit conversion kind.
59ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
60 static const ImplicitConversionRank
61 Rank[(int)ICK_Num_Conversion_Kinds] = {
62 ICR_Exact_Match,
63 ICR_Exact_Match,
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Promotion,
68 ICR_Promotion,
69 ICR_Promotion,
70 ICR_Conversion,
71 ICR_Conversion,
72 ICR_Conversion,
73 ICR_Conversion,
74 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion
80 };
81 return Rank[(int)Kind];
82}
83
84/// GetImplicitConversionName - Return the name of this kind of
85/// implicit conversion.
86const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
87 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
88 "No conversion",
89 "Lvalue-to-rvalue",
90 "Array-to-pointer",
91 "Function-to-pointer",
92 "Qualification",
93 "Integral promotion",
94 "Floating point promotion",
95 "Complex promotion",
96 "Integral conversion",
97 "Floating conversion",
98 "Complex conversion",
99 "Floating-integral conversion",
100 "Complex-real conversion",
101 "Pointer conversion",
102 "Pointer-to-member conversion",
103 "Boolean conversion",
104 "Compatible-types conversion",
105 "Derived-to-base conversion"
106 };
107 return Name[Kind];
108}
109
110/// StandardConversionSequence - Set the standard conversion
111/// sequence to the identity conversion.
112void StandardConversionSequence::setAsIdentityConversion() {
113 First = ICK_Identity;
114 Second = ICK_Identity;
115 Third = ICK_Identity;
116 Deprecated = false;
117 ReferenceBinding = false;
118 DirectBinding = false;
119 RRefBinding = false;
120 CopyConstructor = 0;
121}
122
123/// getRank - Retrieve the rank of this standard conversion sequence
124/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
125/// implicit conversions.
126ImplicitConversionRank StandardConversionSequence::getRank() const {
127 ImplicitConversionRank Rank = ICR_Exact_Match;
128 if (GetConversionRank(First) > Rank)
129 Rank = GetConversionRank(First);
130 if (GetConversionRank(Second) > Rank)
131 Rank = GetConversionRank(Second);
132 if (GetConversionRank(Third) > Rank)
133 Rank = GetConversionRank(Third);
134 return Rank;
135}
136
137/// isPointerConversionToBool - Determines whether this conversion is
138/// a conversion of a pointer or pointer-to-member to bool. This is
139/// used as part of the ranking of standard conversion sequences
140/// (C++ 13.3.3.2p4).
141bool StandardConversionSequence::isPointerConversionToBool() const
142{
143 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
144 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
145
146 // Note that FromType has not necessarily been transformed by the
147 // array-to-pointer or function-to-pointer implicit conversions, so
148 // check for their presence as well as checking whether FromType is
149 // a pointer.
150 if (ToType->isBooleanType() &&
151 (FromType->isPointerType() || FromType->isBlockPointerType() ||
152 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
153 return true;
154
155 return false;
156}
157
158/// isPointerConversionToVoidPointer - Determines whether this
159/// conversion is a conversion of a pointer to a void pointer. This is
160/// used as part of the ranking of standard conversion sequences (C++
161/// 13.3.3.2p4).
162bool
163StandardConversionSequence::
164isPointerConversionToVoidPointer(ASTContext& Context) const
165{
166 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)
176 if (const PointerType* ToPtrType = ToType->getAsPointerType())
177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
182/// 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));
196
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 }
204 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 }
227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
228 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
263// FunctionDecl that New cannot be overloaded with.
264//
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",
272// so IsOverload will not be used.
273//
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
286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl)
288{
289 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
290 // Is this new function an overload of every function in the
291 // overload set?
292 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
293 FuncEnd = Ovl->function_end();
294 for (; Func != FuncEnd; ++Func) {
295 if (!IsOverload(New, *Func, MatchedDecl)) {
296 MatchedDecl = Func;
297 return false;
298 }
299 }
300
301 // This function overloads every function in the overload set.
302 return true;
303 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
304 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
305 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
306 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
307 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
308
309 // C++ [temp.fct]p2:
310 // A function template can be overloaded with other function templates
311 // and with normal (non-template) functions.
312 if ((OldTemplate == 0) != (NewTemplate == 0))
313 return true;
314
315 // Is the function New an overload of the function Old?
316 QualType OldQType = Context.getCanonicalType(Old->getType());
317 QualType NewQType = Context.getCanonicalType(New->getType());
318
319 // Compare the signatures (C++ 1.3.10) of the two functions to
320 // determine whether they are overloads. If we find any mismatch
321 // in the signature, they are overloads.
322
323 // If either of these functions is a K&R-style function (no
324 // prototype), then we consider them to have matching signatures.
325 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
326 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
327 return false;
328
329 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
330 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
331
332 // The signature of a function includes the types of its
333 // parameters (C++ 1.3.10), which includes the presence or absence
334 // of the ellipsis; see C++ DR 357).
335 if (OldQType != NewQType &&
336 (OldType->getNumArgs() != NewType->getNumArgs() ||
337 OldType->isVariadic() != NewType->isVariadic() ||
338 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
339 NewType->arg_type_begin())))
340 return true;
341
342 // C++ [temp.over.link]p4:
343 // The signature of a function template consists of its function
344 // signature, its return type and its template parameter list. The names
345 // of the template parameters are significant only for establishing the
346 // relationship between the template parameters and the rest of the
347 // signature.
348 //
349 // We check the return type and template parameter lists for function
350 // templates first; the remaining checks follow.
351 if (NewTemplate &&
352 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
353 OldTemplate->getTemplateParameters(),
354 false, false, SourceLocation()) ||
355 OldType->getResultType() != NewType->getResultType()))
356 return true;
357
358 // If the function is a class member, its signature includes the
359 // cv-qualifiers (if any) on the function itself.
360 //
361 // As part of this, also check whether one of the member functions
362 // is static, in which case they are not overloads (C++
363 // 13.1p2). While not part of the definition of the signature,
364 // this check is important to determine whether these functions
365 // can be overloaded.
366 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
367 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
368 if (OldMethod && NewMethod &&
369 !OldMethod->isStatic() && !NewMethod->isStatic() &&
370 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
371 return true;
372
373 // The signatures match; this is not an overload.
374 return false;
375 } else {
376 // (C++ 13p1):
377 // Only function declarations can be overloaded; object and type
378 // declarations cannot be overloaded.
379 return false;
380 }
381}
382
383/// TryImplicitConversion - Attempt to perform an implicit conversion
384/// from the given expression (Expr) to the given type (ToType). This
385/// function returns an implicit conversion sequence that can be used
386/// to perform the initialization. Given
387///
388/// void f(float f);
389/// void g(int i) { f(i); }
390///
391/// this routine would produce an implicit conversion sequence to
392/// describe the initialization of f from i, which will be a standard
393/// conversion sequence containing an lvalue-to-rvalue conversion (C++
394/// 4.1) followed by a floating-integral conversion (C++ 4.9).
395//
396/// Note that this routine only determines how the conversion can be
397/// performed; it does not actually perform the conversion. As such,
398/// it will not produce any diagnostics if no conversion is available,
399/// but will instead return an implicit conversion sequence of kind
400/// "BadConversion".
401///
402/// If @p SuppressUserConversions, then user-defined conversions are
403/// not permitted.
404/// If @p AllowExplicit, then explicit user-defined conversions are
405/// permitted.
406/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
407/// no matter its actual lvalueness.
408ImplicitConversionSequence
409Sema::TryImplicitConversion(Expr* From, QualType ToType,
410 bool SuppressUserConversions,
411 bool AllowExplicit, bool ForceRValue)
412{
413 ImplicitConversionSequence ICS;
414 if (IsStandardConversion(From, ToType, ICS.Standard))
415 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
416 else if (getLangOptions().CPlusPlus &&
417 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
418 !SuppressUserConversions, AllowExplicit,
419 ForceRValue)) {
420 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
421 // C++ [over.ics.user]p4:
422 // A conversion of an expression of class type to the same class
423 // type is given Exact Match rank, and a conversion of an
424 // expression of class type to a base class of that type is
425 // given Conversion rank, in spite of the fact that a copy
426 // constructor (i.e., a user-defined conversion function) is
427 // called for those cases.
428 if (CXXConstructorDecl *Constructor
429 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
430 QualType FromCanon
431 = Context.getCanonicalType(From->getType().getUnqualifiedType());
432 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
433 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
434 // Turn this into a "standard" conversion sequence, so that it
435 // gets ranked with standard conversion sequences.
436 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
437 ICS.Standard.setAsIdentityConversion();
438 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
439 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
440 ICS.Standard.CopyConstructor = Constructor;
441 if (ToCanon != FromCanon)
442 ICS.Standard.Second = ICK_Derived_To_Base;
443 }
444 }
445
446 // C++ [over.best.ics]p4:
447 // However, when considering the argument of a user-defined
448 // conversion function that is a candidate by 13.3.1.3 when
449 // invoked for the copying of the temporary in the second step
450 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
451 // 13.3.1.6 in all cases, only standard conversion sequences and
452 // ellipsis conversion sequences are allowed.
453 if (SuppressUserConversions &&
454 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
455 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
456 } else
457 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
458
459 return ICS;
460}
461
462/// IsStandardConversion - Determines whether there is a standard
463/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
464/// expression From to the type ToType. Standard conversion sequences
465/// only consider non-class types; for conversions that involve class
466/// types, use TryImplicitConversion. If a conversion exists, SCS will
467/// contain the standard conversion sequence required to perform this
468/// conversion and this routine will return true. Otherwise, this
469/// routine will return false and the value of SCS is unspecified.
470bool
471Sema::IsStandardConversion(Expr* From, QualType ToType,
472 StandardConversionSequence &SCS)
473{
474 QualType FromType = From->getType();
475
476 // Standard conversions (C++ [conv])
477 SCS.setAsIdentityConversion();
478 SCS.Deprecated = false;
479 SCS.IncompatibleObjC = false;
480 SCS.FromTypePtr = FromType.getAsOpaquePtr();
481 SCS.CopyConstructor = 0;
482
483 // There are no standard conversions for class types in C++, so
484 // abort early. When overloading in C, however, we do permit
485 if (FromType->isRecordType() || ToType->isRecordType()) {
486 if (getLangOptions().CPlusPlus)
487 return false;
488
489 // When we're overloading in C, we allow, as standard conversions,
490 }
491
492 // The first conversion can be an lvalue-to-rvalue conversion,
493 // array-to-pointer conversion, or function-to-pointer conversion
494 // (C++ 4p1).
495
496 // Lvalue-to-rvalue conversion (C++ 4.1):
497 // An lvalue (3.10) of a non-function, non-array type T can be
498 // converted to an rvalue.
499 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
500 if (argIsLvalue == Expr::LV_Valid &&
501 !FromType->isFunctionType() && !FromType->isArrayType() &&
502 Context.getCanonicalType(FromType) != Context.OverloadTy) {
503 SCS.First = ICK_Lvalue_To_Rvalue;
504
505 // If T is a non-class type, the type of the rvalue is the
506 // cv-unqualified version of T. Otherwise, the type of the rvalue
507 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
508 // just strip the qualifiers because they don't matter.
509
510 // FIXME: Doesn't see through to qualifiers behind a typedef!
511 FromType = FromType.getUnqualifiedType();
512 }
513 // Array-to-pointer conversion (C++ 4.2)
514 else if (FromType->isArrayType()) {
515 SCS.First = ICK_Array_To_Pointer;
516
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).
524 SCS.Deprecated = true;
525
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)
530 SCS.Second = ICK_Identity;
531 SCS.Third = ICK_Qualification;
532 SCS.ToTypePtr = ToType.getAsOpaquePtr();
533 return true;
534 }
535 }
536 // Function-to-pointer conversion (C++ 4.3).
537 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
538 SCS.First = ICK_Function_To_Pointer;
539
540 // An lvalue of function type T can be converted to an rvalue of
541 // type "pointer to T." The result is a pointer to the
542 // function. (C++ 4.3p1).
543 FromType = Context.getPointerType(FromType);
544 }
545 // Address of overloaded function (C++ [over.over]).
546 else if (FunctionDecl *Fn
547 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
548 SCS.First = ICK_Function_To_Pointer;
549
550 // We were able to resolve the address of the overloaded function,
551 // so we can convert to the type of that function.
552 FromType = Fn->getType();
553 if (ToType->isLValueReferenceType())
554 FromType = Context.getLValueReferenceType(FromType);
555 else if (ToType->isRValueReferenceType())
556 FromType = Context.getRValueReferenceType(FromType);
557 else if (ToType->isMemberPointerType()) {
558 // Resolve address only succeeds if both sides are member pointers,
559 // but it doesn't have to be the same class. See DR 247.
560 // Note that this means that the type of &Derived::fn can be
561 // Ret (Base::*)(Args) if the fn overload actually found is from the
562 // base class, even if it was brought into the derived class via a
563 // using declaration. The standard isn't clear on this issue at all.
564 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
565 FromType = Context.getMemberPointerType(FromType,
566 Context.getTypeDeclType(M->getParent()).getTypePtr());
567 } else
568 FromType = Context.getPointerType(FromType);
569 }
570 // We don't require any conversions for the first step.
571 else {
572 SCS.First = ICK_Identity;
573 }
574
575 // The second conversion can be an integral promotion, floating
576 // point promotion, integral conversion, floating point conversion,
577 // floating-integral conversion, pointer conversion,
578 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
579 // For overloading in C, this can also be a "compatible-type"
580 // conversion.
581 bool IncompatibleObjC = false;
582 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
583 // The unqualified versions of the types are the same: there's no
584 // conversion to do.
585 SCS.Second = ICK_Identity;
586 }
587 // Integral promotion (C++ 4.5).
588 else if (IsIntegralPromotion(From, FromType, ToType)) {
589 SCS.Second = ICK_Integral_Promotion;
590 FromType = ToType.getUnqualifiedType();
591 }
592 // Floating point promotion (C++ 4.6).
593 else if (IsFloatingPointPromotion(FromType, ToType)) {
594 SCS.Second = ICK_Floating_Promotion;
595 FromType = ToType.getUnqualifiedType();
596 }
597 // Complex promotion (Clang extension)
598 else if (IsComplexPromotion(FromType, ToType)) {
599 SCS.Second = ICK_Complex_Promotion;
600 FromType = ToType.getUnqualifiedType();
601 }
602 // Integral conversions (C++ 4.7).
603 // FIXME: isIntegralType shouldn't be true for enums in C++.
604 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
605 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
606 SCS.Second = ICK_Integral_Conversion;
607 FromType = ToType.getUnqualifiedType();
608 }
609 // Floating point conversions (C++ 4.8).
610 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
611 SCS.Second = ICK_Floating_Conversion;
612 FromType = ToType.getUnqualifiedType();
613 }
614 // Complex conversions (C99 6.3.1.6)
615 else if (FromType->isComplexType() && ToType->isComplexType()) {
616 SCS.Second = ICK_Complex_Conversion;
617 FromType = ToType.getUnqualifiedType();
618 }
619 // Floating-integral conversions (C++ 4.9).
620 // FIXME: isIntegralType shouldn't be true for enums in C++.
621 else if ((FromType->isFloatingType() &&
622 ToType->isIntegralType() && !ToType->isBooleanType() &&
623 !ToType->isEnumeralType()) ||
624 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
625 ToType->isFloatingType())) {
626 SCS.Second = ICK_Floating_Integral;
627 FromType = ToType.getUnqualifiedType();
628 }
629 // Complex-real conversions (C99 6.3.1.7)
630 else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
631 (ToType->isComplexType() && FromType->isArithmeticType())) {
632 SCS.Second = ICK_Complex_Real;
633 FromType = ToType.getUnqualifiedType();
634 }
635 // Pointer conversions (C++ 4.10).
636 else if (IsPointerConversion(From, FromType, ToType, FromType,
637 IncompatibleObjC)) {
638 SCS.Second = ICK_Pointer_Conversion;
639 SCS.IncompatibleObjC = IncompatibleObjC;
640 }
641 // Pointer to member conversions (4.11).
642 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
643 SCS.Second = ICK_Pointer_Member;
644 }
645 // Boolean conversions (C++ 4.12).
646 else if (ToType->isBooleanType() &&
647 (FromType->isArithmeticType() ||
648 FromType->isEnumeralType() ||
649 FromType->isPointerType() ||
650 FromType->isBlockPointerType() ||
651 FromType->isMemberPointerType() ||
652 FromType->isNullPtrType())) {
653 SCS.Second = ICK_Boolean_Conversion;
654 FromType = Context.BoolTy;
655 }
656 // Compatible conversions (Clang extension for C function overloading)
657 else if (!getLangOptions().CPlusPlus &&
658 Context.typesAreCompatible(ToType, FromType)) {
659 SCS.Second = ICK_Compatible_Conversion;
660 } else {
661 // No second conversion required.
662 SCS.Second = ICK_Identity;
663 }
664
665 QualType CanonFrom;
666 QualType CanonTo;
667 // The third conversion can be a qualification conversion (C++ 4p1).
668 if (IsQualificationConversion(FromType, ToType)) {
669 SCS.Third = ICK_Qualification;
670 FromType = ToType;
671 CanonFrom = Context.getCanonicalType(FromType);
672 CanonTo = Context.getCanonicalType(ToType);
673 } else {
674 // No conversion required
675 SCS.Third = ICK_Identity;
676
677 // C++ [over.best.ics]p6:
678 // [...] Any difference in top-level cv-qualification is
679 // subsumed by the initialization itself and does not constitute
680 // a conversion. [...]
681 CanonFrom = Context.getCanonicalType(FromType);
682 CanonTo = Context.getCanonicalType(ToType);
683 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
684 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
685 FromType = ToType;
686 CanonFrom = CanonTo;
687 }
688 }
689
690 // If we have not converted the argument type to the parameter type,
691 // this is a bad conversion sequence.
692 if (CanonFrom != CanonTo)
693 return false;
694
695 SCS.ToTypePtr = FromType.getAsOpaquePtr();
696 return true;
697}
698
699/// IsIntegralPromotion - Determines whether the conversion from the
700/// expression From (whose potentially-adjusted type is FromType) to
701/// ToType is an integral promotion (C++ 4.5). If so, returns true and
702/// sets PromotedType to the promoted type.
703bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
704{
705 const BuiltinType *To = ToType->getAsBuiltinType();
706 // All integers are built-in.
707 if (!To) {
708 return false;
709 }
710
711 // An rvalue of type char, signed char, unsigned char, short int, or
712 // unsigned short int can be converted to an rvalue of type int if
713 // int can represent all the values of the source type; otherwise,
714 // the source rvalue can be converted to an rvalue of type unsigned
715 // int (C++ 4.5p1).
716 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
717 if (// We can promote any signed, promotable integer type to an int
718 (FromType->isSignedIntegerType() ||
719 // We can promote any unsigned integer type whose size is
720 // less than int to an int.
721 (!FromType->isSignedIntegerType() &&
722 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
723 return To->getKind() == BuiltinType::Int;
724 }
725
726 return To->getKind() == BuiltinType::UInt;
727 }
728
729 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
730 // can be converted to an rvalue of the first of the following types
731 // that can represent all the values of its underlying type: int,
732 // unsigned int, long, or unsigned long (C++ 4.5p2).
733 if ((FromType->isEnumeralType() || FromType->isWideCharType())
734 && ToType->isIntegerType()) {
735 // Determine whether the type we're converting from is signed or
736 // unsigned.
737 bool FromIsSigned;
738 uint64_t FromSize = Context.getTypeSize(FromType);
739 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
740 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
741 FromIsSigned = UnderlyingType->isSignedIntegerType();
742 } else {
743 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
744 FromIsSigned = true;
745 }
746
747 // The types we'll try to promote to, in the appropriate
748 // order. Try each of these types.
749 QualType PromoteTypes[6] = {
750 Context.IntTy, Context.UnsignedIntTy,
751 Context.LongTy, Context.UnsignedLongTy ,
752 Context.LongLongTy, Context.UnsignedLongLongTy
753 };
754 for (int Idx = 0; Idx < 6; ++Idx) {
755 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
756 if (FromSize < ToSize ||
757 (FromSize == ToSize &&
758 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
759 // We found the type that we can promote to. If this is the
760 // type we wanted, we have a promotion. Otherwise, no
761 // promotion.
762 return Context.getCanonicalType(ToType).getUnqualifiedType()
763 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
764 }
765 }
766 }
767
768 // An rvalue for an integral bit-field (9.6) can be converted to an
769 // rvalue of type int if int can represent all the values of the
770 // bit-field; otherwise, it can be converted to unsigned int if
771 // unsigned int can represent all the values of the bit-field. If
772 // the bit-field is larger yet, no integral promotion applies to
773 // it. If the bit-field has an enumerated type, it is treated as any
774 // other value of that type for promotion purposes (C++ 4.5p3).
775 // FIXME: We should delay checking of bit-fields until we actually perform the
776 // conversion.
777 using llvm::APSInt;
778 if (From)
779 if (FieldDecl *MemberDecl = From->getBitField()) {
780 APSInt BitWidth;
781 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
782 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
783 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
784 ToSize = Context.getTypeSize(ToType);
785
786 // Are we promoting to an int from a bitfield that fits in an int?
787 if (BitWidth < ToSize ||
788 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
789 return To->getKind() == BuiltinType::Int;
790 }
791
792 // Are we promoting to an unsigned int from an unsigned bitfield
793 // that fits into an unsigned int?
794 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
795 return To->getKind() == BuiltinType::UInt;
796 }
797
798 return false;
799 }
800 }
801
802 // An rvalue of type bool can be converted to an rvalue of type int,
803 // with false becoming zero and true becoming one (C++ 4.5p4).
804 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
805 return true;
806 }
807
808 return false;
809}
810
811/// IsFloatingPointPromotion - Determines whether the conversion from
812/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
813/// returns true and sets PromotedType to the promoted type.
814bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
815{
816 /// An rvalue of type float can be converted to an rvalue of type
817 /// double. (C++ 4.6p1).
818 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
819 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
820 if (FromBuiltin->getKind() == BuiltinType::Float &&
821 ToBuiltin->getKind() == BuiltinType::Double)
822 return true;
823
824 // C99 6.3.1.5p1:
825 // When a float is promoted to double or long double, or a
826 // double is promoted to long double [...].
827 if (!getLangOptions().CPlusPlus &&
828 (FromBuiltin->getKind() == BuiltinType::Float ||
829 FromBuiltin->getKind() == BuiltinType::Double) &&
830 (ToBuiltin->getKind() == BuiltinType::LongDouble))
831 return true;
832 }
833
834 return false;
835}
836
837/// \brief Determine if a conversion is a complex promotion.
838///
839/// A complex promotion is defined as a complex -> complex conversion
840/// where the conversion between the underlying real types is a
841/// floating-point or integral promotion.
842bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
843 const ComplexType *FromComplex = FromType->getAsComplexType();
844 if (!FromComplex)
845 return false;
846
847 const ComplexType *ToComplex = ToType->getAsComplexType();
848 if (!ToComplex)
849 return false;
850
851 return IsFloatingPointPromotion(FromComplex->getElementType(),
852 ToComplex->getElementType()) ||
853 IsIntegralPromotion(0, FromComplex->getElementType(),
854 ToComplex->getElementType());
855}
856
857/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
858/// the pointer type FromPtr to a pointer to type ToPointee, with the
859/// same type qualifiers as FromPtr has on its pointee type. ToType,
860/// if non-empty, will be a pointer to ToType that may or may not have
861/// the right set of qualifiers on its pointee.
862static QualType
863BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
864 QualType ToPointee, QualType ToType,
865 ASTContext &Context) {
866 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
867 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
868 unsigned Quals = CanonFromPointee.getCVRQualifiers();
869
870 // Exact qualifier match -> return the pointer type we're converting to.
871 if (CanonToPointee.getCVRQualifiers() == Quals) {
872 // ToType is exactly what we need. Return it.
873 if (ToType.getTypePtr())
874 return ToType;
875
876 // Build a pointer to ToPointee. It has the right qualifiers
877 // already.
878 return Context.getPointerType(ToPointee);
879 }
880
881 // Just build a canonical type that has the right qualifiers.
882 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
883}
884
885/// IsPointerConversion - Determines whether the conversion of the
886/// expression From, which has the (possibly adjusted) type FromType,
887/// can be converted to the type ToType via a pointer conversion (C++
888/// 4.10). If so, returns true and places the converted type (that
889/// might differ from ToType in its cv-qualifiers at some level) into
890/// ConvertedType.
891///
892/// This routine also supports conversions to and from block pointers
893/// and conversions with Objective-C's 'id', 'id<protocols...>', and
894/// pointers to interfaces. FIXME: Once we've determined the
895/// appropriate overloading rules for Objective-C, we may want to
896/// split the Objective-C checks into a different routine; however,
897/// GCC seems to consider all of these conversions to be pointer
898/// conversions, so for now they live here. IncompatibleObjC will be
899/// set if the conversion is an allowed Objective-C conversion that
900/// should result in a warning.
901bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
902 QualType& ConvertedType,
903 bool &IncompatibleObjC)
904{
905 IncompatibleObjC = false;
906 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
907 return true;
908
909 // Conversion from a null pointer constant to any Objective-C pointer type.
910 if (Context.isObjCObjectPointerType(ToType) &&
911 From->isNullPointerConstant(Context)) {
912 ConvertedType = ToType;
913 return true;
914 }
915
916 // Blocks: Block pointers can be converted to void*.
917 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
918 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
919 ConvertedType = ToType;
920 return true;
921 }
922 // Blocks: A null pointer constant can be converted to a block
923 // pointer type.
924 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
925 ConvertedType = ToType;
926 return true;
927 }
928
929 // If the left-hand-side is nullptr_t, the right side can be a null
930 // pointer constant.
931 if (ToType->isNullPtrType() && From->isNullPointerConstant(Context)) {
932 ConvertedType = ToType;
933 return true;
934 }
935
936 const PointerType* ToTypePtr = ToType->getAsPointerType();
937 if (!ToTypePtr)
938 return false;
939
940 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
941 if (From->isNullPointerConstant(Context)) {
942 ConvertedType = ToType;
943 return true;
944 }
945
946 // Beyond this point, both types need to be pointers.
947 const PointerType *FromTypePtr = FromType->getAsPointerType();
948 if (!FromTypePtr)
949 return false;
950
951 QualType FromPointeeType = FromTypePtr->getPointeeType();
952 QualType ToPointeeType = ToTypePtr->getPointeeType();
953
954 // An rvalue of type "pointer to cv T," where T is an object type,
955 // can be converted to an rvalue of type "pointer to cv void" (C++
956 // 4.10p2).
957 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
958 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
959 ToPointeeType,
960 ToType, Context);
961 return true;
962 }
963
964 // When we're overloading in C, we allow a special kind of pointer
965 // conversion for compatible-but-not-identical pointee types.
966 if (!getLangOptions().CPlusPlus &&
967 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
968 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
969 ToPointeeType,
970 ToType, Context);
971 return true;
972 }
973
974 // C++ [conv.ptr]p3:
975 //
976 // An rvalue of type "pointer to cv D," where D is a class type,
977 // can be converted to an rvalue of type "pointer to cv B," where
978 // B is a base class (clause 10) of D. If B is an inaccessible
979 // (clause 11) or ambiguous (10.2) base class of D, a program that
980 // necessitates this conversion is ill-formed. The result of the
981 // conversion is a pointer to the base class sub-object of the
982 // derived class object. The null pointer value is converted to
983 // the null pointer value of the destination type.
984 //
985 // Note that we do not check for ambiguity or inaccessibility
986 // here. That is handled by CheckPointerConversion.
987 if (getLangOptions().CPlusPlus &&
988 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
989 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
990 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
991 ToPointeeType,
992 ToType, Context);
993 return true;
994 }
995
996 return false;
997}
998
999/// isObjCPointerConversion - Determines whether this is an
1000/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1001/// with the same arguments and return values.
1002bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1003 QualType& ConvertedType,
1004 bool &IncompatibleObjC) {
1005 if (!getLangOptions().ObjC1)
1006 return false;
1007
1008 // Conversions with Objective-C's id<...>.
1009 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
1010 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
1011 ConvertedType = ToType;
1012 return true;
1013 }
1014
1015 // Beyond this point, both types need to be pointers or block pointers.
1016 QualType ToPointeeType;
1017 const PointerType* ToTypePtr = ToType->getAsPointerType();
1018 if (ToTypePtr)
1019 ToPointeeType = ToTypePtr->getPointeeType();
1020 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
1021 ToPointeeType = ToBlockPtr->getPointeeType();
1022 else
1023 return false;
1024
1025 QualType FromPointeeType;
1026 const PointerType *FromTypePtr = FromType->getAsPointerType();
1027 if (FromTypePtr)
1028 FromPointeeType = FromTypePtr->getPointeeType();
1029 else if (const BlockPointerType *FromBlockPtr
1030 = FromType->getAsBlockPointerType())
1031 FromPointeeType = FromBlockPtr->getPointeeType();
1032 else
1033 return false;
1034
1035 // Objective C++: We're able to convert from a pointer to an
1036 // interface to a pointer to a different interface.
1037 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
1038 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
1039 if (FromIface && ToIface &&
1040 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
1041 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1042 ToPointeeType,
1043 ToType, Context);
1044 return true;
1045 }
1046
1047 if (FromIface && ToIface &&
1048 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
1049 // Okay: this is some kind of implicit downcast of Objective-C
1050 // interfaces, which is permitted. However, we're going to
1051 // complain about it.
1052 IncompatibleObjC = true;
1053 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1054 ToPointeeType,
1055 ToType, Context);
1056 return true;
1057 }
1058
1059 // Objective C++: We're able to convert between "id" and a pointer
1060 // to any interface (in both directions).
1061 if ((FromIface && Context.isObjCIdStructType(ToPointeeType))
1062 || (ToIface && Context.isObjCIdStructType(FromPointeeType))) {
1063 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1064 ToPointeeType,
1065 ToType, Context);
1066 return true;
1067 }
1068
1069 // Objective C++: Allow conversions between the Objective-C "id" and
1070 // "Class", in either direction.
1071 if ((Context.isObjCIdStructType(FromPointeeType) &&
1072 Context.isObjCClassStructType(ToPointeeType)) ||
1073 (Context.isObjCClassStructType(FromPointeeType) &&
1074 Context.isObjCIdStructType(ToPointeeType))) {
1075 ConvertedType = ToType;
1076 return true;
1077 }
1078
1079 // If we have pointers to pointers, recursively check whether this
1080 // is an Objective-C conversion.
1081 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1082 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1083 IncompatibleObjC)) {
1084 // We always complain about this conversion.
1085 IncompatibleObjC = true;
1086 ConvertedType = ToType;
1087 return true;
1088 }
1089
1090 // If we have pointers to functions or blocks, check whether the only
1091 // differences in the argument and result types are in Objective-C
1092 // pointer conversions. If so, we permit the conversion (but
1093 // complain about it).
1094 const FunctionProtoType *FromFunctionType
1095 = FromPointeeType->getAsFunctionProtoType();
1096 const FunctionProtoType *ToFunctionType
1097 = ToPointeeType->getAsFunctionProtoType();
1098 if (FromFunctionType && ToFunctionType) {
1099 // If the function types are exactly the same, this isn't an
1100 // Objective-C pointer conversion.
1101 if (Context.getCanonicalType(FromPointeeType)
1102 == Context.getCanonicalType(ToPointeeType))
1103 return false;
1104
1105 // Perform the quick checks that will tell us whether these
1106 // function types are obviously different.
1107 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1108 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1109 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1110 return false;
1111
1112 bool HasObjCConversion = false;
1113 if (Context.getCanonicalType(FromFunctionType->getResultType())
1114 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1115 // Okay, the types match exactly. Nothing to do.
1116 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1117 ToFunctionType->getResultType(),
1118 ConvertedType, IncompatibleObjC)) {
1119 // Okay, we have an Objective-C pointer conversion.
1120 HasObjCConversion = true;
1121 } else {
1122 // Function types are too different. Abort.
1123 return false;
1124 }
1125
1126 // Check argument types.
1127 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1128 ArgIdx != NumArgs; ++ArgIdx) {
1129 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1130 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1131 if (Context.getCanonicalType(FromArgType)
1132 == Context.getCanonicalType(ToArgType)) {
1133 // Okay, the types match exactly. Nothing to do.
1134 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1135 ConvertedType, IncompatibleObjC)) {
1136 // Okay, we have an Objective-C pointer conversion.
1137 HasObjCConversion = true;
1138 } else {
1139 // Argument types are too different. Abort.
1140 return false;
1141 }
1142 }
1143
1144 if (HasObjCConversion) {
1145 // We had an Objective-C conversion. Allow this pointer
1146 // conversion, but complain about it.
1147 ConvertedType = ToType;
1148 IncompatibleObjC = true;
1149 return true;
1150 }
1151 }
1152
1153 return false;
1154}
1155
1156/// CheckPointerConversion - Check the pointer conversion from the
1157/// expression From to the type ToType. This routine checks for
1158/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1159/// conversions for which IsPointerConversion has already returned
1160/// true. It returns true and produces a diagnostic if there was an
1161/// error, or returns false otherwise.
1162bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1163 QualType FromType = From->getType();
1164
1165 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1166 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
1167 QualType FromPointeeType = FromPtrType->getPointeeType(),
1168 ToPointeeType = ToPtrType->getPointeeType();
1169
1170 // Objective-C++ conversions are always okay.
1171 // FIXME: We should have a different class of conversions for the
1172 // Objective-C++ implicit conversions.
1173 if (Context.isObjCIdStructType(FromPointeeType) ||
1174 Context.isObjCIdStructType(ToPointeeType) ||
1175 Context.isObjCClassStructType(FromPointeeType) ||
1176 Context.isObjCClassStructType(ToPointeeType))
1177 return false;
1178
1179 if (FromPointeeType->isRecordType() &&
1180 ToPointeeType->isRecordType()) {
1181 // We must have a derived-to-base conversion. Check an
1182 // ambiguous or inaccessible conversion.
1183 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1184 From->getExprLoc(),
1185 From->getSourceRange());
1186 }
1187 }
1188
1189 return false;
1190}
1191
1192/// IsMemberPointerConversion - Determines whether the conversion of the
1193/// expression From, which has the (possibly adjusted) type FromType, can be
1194/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1195/// If so, returns true and places the converted type (that might differ from
1196/// ToType in its cv-qualifiers at some level) into ConvertedType.
1197bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1198 QualType ToType, QualType &ConvertedType)
1199{
1200 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1201 if (!ToTypePtr)
1202 return false;
1203
1204 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1205 if (From->isNullPointerConstant(Context)) {
1206 ConvertedType = ToType;
1207 return true;
1208 }
1209
1210 // Otherwise, both types have to be member pointers.
1211 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1212 if (!FromTypePtr)
1213 return false;
1214
1215 // A pointer to member of B can be converted to a pointer to member of D,
1216 // where D is derived from B (C++ 4.11p2).
1217 QualType FromClass(FromTypePtr->getClass(), 0);
1218 QualType ToClass(ToTypePtr->getClass(), 0);
1219 // FIXME: What happens when these are dependent? Is this function even called?
1220
1221 if (IsDerivedFrom(ToClass, FromClass)) {
1222 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1223 ToClass.getTypePtr());
1224 return true;
1225 }
1226
1227 return false;
1228}
1229
1230/// CheckMemberPointerConversion - Check the member pointer conversion from the
1231/// expression From to the type ToType. This routine checks for ambiguous or
1232/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1233/// for which IsMemberPointerConversion has already returned true. It returns
1234/// true and produces a diagnostic if there was an error, or returns false
1235/// otherwise.
1236bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1237 QualType FromType = From->getType();
1238 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1239 if (!FromPtrType)
1240 return false;
1241
1242 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1243 assert(ToPtrType && "No member pointer cast has a target type "
1244 "that is not a member pointer.");
1245
1246 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1247 QualType ToClass = QualType(ToPtrType->getClass(), 0);
1248
1249 // FIXME: What about dependent types?
1250 assert(FromClass->isRecordType() && "Pointer into non-class.");
1251 assert(ToClass->isRecordType() && "Pointer into non-class.");
1252
1253 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1254 /*DetectVirtual=*/true);
1255 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1256 assert(DerivationOkay &&
1257 "Should not have been called if derivation isn't OK.");
1258 (void)DerivationOkay;
1259
1260 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1261 getUnqualifiedType())) {
1262 // Derivation is ambiguous. Redo the check to find the exact paths.
1263 Paths.clear();
1264 Paths.setRecordingPaths(true);
1265 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1266 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1267 (void)StillOkay;
1268
1269 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1270 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1271 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1272 return true;
1273 }
1274
1275 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1276 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1277 << FromClass << ToClass << QualType(VBase, 0)
1278 << From->getSourceRange();
1279 return true;
1280 }
1281
1282 return false;
1283}
1284
1285/// IsQualificationConversion - Determines whether the conversion from
1286/// an rvalue of type FromType to ToType is a qualification conversion
1287/// (C++ 4.4).
1288bool
1289Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1290{
1291 FromType = Context.getCanonicalType(FromType);
1292 ToType = Context.getCanonicalType(ToType);
1293
1294 // If FromType and ToType are the same type, this is not a
1295 // qualification conversion.
1296 if (FromType == ToType)
1297 return false;
1298
1299 // (C++ 4.4p4):
1300 // A conversion can add cv-qualifiers at levels other than the first
1301 // in multi-level pointers, subject to the following rules: [...]
1302 bool PreviousToQualsIncludeConst = true;
1303 bool UnwrappedAnyPointer = false;
1304 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
1305 // Within each iteration of the loop, we check the qualifiers to
1306 // determine if this still looks like a qualification
1307 // conversion. Then, if all is well, we unwrap one more level of
1308 // pointers or pointers-to-members and do it all again
1309 // until there are no more pointers or pointers-to-members left to
1310 // unwrap.
1311 UnwrappedAnyPointer = true;
1312
1313 // -- for every j > 0, if const is in cv 1,j then const is in cv
1314 // 2,j, and similarly for volatile.
1315 if (!ToType.isAtLeastAsQualifiedAs(FromType))
1316 return false;
1317
1318 // -- if the cv 1,j and cv 2,j are different, then const is in
1319 // every cv for 0 < k < j.
1320 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
1321 && !PreviousToQualsIncludeConst)
1322 return false;
1323
1324 // Keep track of whether all prior cv-qualifiers in the "to" type
1325 // include const.
1326 PreviousToQualsIncludeConst
1327 = PreviousToQualsIncludeConst && ToType.isConstQualified();
1328 }
1329
1330 // We are left with FromType and ToType being the pointee types
1331 // after unwrapping the original FromType and ToType the same number
1332 // of types. If we unwrapped any pointers, and if FromType and
1333 // ToType have the same unqualified type (since we checked
1334 // qualifiers above), then this is a qualification conversion.
1335 return UnwrappedAnyPointer &&
1336 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1337}
1338
1339/// Determines whether there is a user-defined conversion sequence
1340/// (C++ [over.ics.user]) that converts expression From to the type
1341/// ToType. If such a conversion exists, User will contain the
1342/// user-defined conversion sequence that performs such a conversion
1343/// and this routine will return true. Otherwise, this routine returns
1344/// false and User is unspecified.
1345///
1346/// \param AllowConversionFunctions true if the conversion should
1347/// consider conversion functions at all. If false, only constructors
1348/// will be considered.
1349///
1350/// \param AllowExplicit true if the conversion should consider C++0x
1351/// "explicit" conversion functions as well as non-explicit conversion
1352/// functions (C++0x [class.conv.fct]p2).
1353///
1354/// \param ForceRValue true if the expression should be treated as an rvalue
1355/// for overload resolution.
1356bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1357 UserDefinedConversionSequence& User,
1358 bool AllowConversionFunctions,
1359 bool AllowExplicit, bool ForceRValue)
1360{
1361 OverloadCandidateSet CandidateSet;
1362 if (const RecordType *ToRecordType = ToType->getAsRecordType()) {
1363 if (CXXRecordDecl *ToRecordDecl
1364 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1365 // C++ [over.match.ctor]p1:
1366 // When objects of class type are direct-initialized (8.5), or
1367 // copy-initialized from an expression of the same or a
1368 // derived class type (8.5), overload resolution selects the
1369 // constructor. [...] For copy-initialization, the candidate
1370 // functions are all the converting constructors (12.3.1) of
1371 // that class. The argument list is the expression-list within
1372 // the parentheses of the initializer.
1373 DeclarationName ConstructorName
1374 = Context.DeclarationNames.getCXXConstructorName(
1375 Context.getCanonicalType(ToType).getUnqualifiedType());
1376 DeclContext::lookup_iterator Con, ConEnd;
1377 for (llvm::tie(Con, ConEnd)
1378 = ToRecordDecl->lookup(Context, ConstructorName);
1378 = ToRecordDecl->lookup(ConstructorName);
1379 Con != ConEnd; ++Con) {
1380 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1381 if (Constructor->isConvertingConstructor())
1382 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1383 /*SuppressUserConversions=*/true, ForceRValue);
1384 }
1385 }
1386 }
1387
1388 if (!AllowConversionFunctions) {
1389 // Don't allow any conversion functions to enter the overload set.
1390 } else if (const RecordType *FromRecordType
1391 = From->getType()->getAsRecordType()) {
1392 if (CXXRecordDecl *FromRecordDecl
1393 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1394 // Add all of the conversion functions as candidates.
1395 // FIXME: Look for conversions in base classes!
1396 OverloadedFunctionDecl *Conversions
1397 = FromRecordDecl->getConversionFunctions();
1398 for (OverloadedFunctionDecl::function_iterator Func
1399 = Conversions->function_begin();
1400 Func != Conversions->function_end(); ++Func) {
1401 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1402 if (AllowExplicit || !Conv->isExplicit())
1403 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1404 }
1405 }
1406 }
1407
1408 OverloadCandidateSet::iterator Best;
1409 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
1410 case OR_Success:
1411 // Record the standard conversion we used and the conversion function.
1412 if (CXXConstructorDecl *Constructor
1413 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1414 // C++ [over.ics.user]p1:
1415 // If the user-defined conversion is specified by a
1416 // constructor (12.3.1), the initial standard conversion
1417 // sequence converts the source type to the type required by
1418 // the argument of the constructor.
1419 //
1420 // FIXME: What about ellipsis conversions?
1421 QualType ThisType = Constructor->getThisType(Context);
1422 User.Before = Best->Conversions[0].Standard;
1423 User.ConversionFunction = Constructor;
1424 User.After.setAsIdentityConversion();
1425 User.After.FromTypePtr
1426 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1427 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1428 return true;
1429 } else if (CXXConversionDecl *Conversion
1430 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1431 // C++ [over.ics.user]p1:
1432 //
1433 // [...] If the user-defined conversion is specified by a
1434 // conversion function (12.3.2), the initial standard
1435 // conversion sequence converts the source type to the
1436 // implicit object parameter of the conversion function.
1437 User.Before = Best->Conversions[0].Standard;
1438 User.ConversionFunction = Conversion;
1439
1440 // C++ [over.ics.user]p2:
1441 // The second standard conversion sequence converts the
1442 // result of the user-defined conversion to the target type
1443 // for the sequence. Since an implicit conversion sequence
1444 // is an initialization, the special rules for
1445 // initialization by user-defined conversion apply when
1446 // selecting the best user-defined conversion for a
1447 // user-defined conversion sequence (see 13.3.3 and
1448 // 13.3.3.1).
1449 User.After = Best->FinalConversion;
1450 return true;
1451 } else {
1452 assert(false && "Not a constructor or conversion function?");
1453 return false;
1454 }
1455
1456 case OR_No_Viable_Function:
1457 case OR_Deleted:
1458 // No conversion here! We're done.
1459 return false;
1460
1461 case OR_Ambiguous:
1462 // FIXME: See C++ [over.best.ics]p10 for the handling of
1463 // ambiguous conversion sequences.
1464 return false;
1465 }
1466
1467 return false;
1468}
1469
1470/// CompareImplicitConversionSequences - Compare two implicit
1471/// conversion sequences to determine whether one is better than the
1472/// other or if they are indistinguishable (C++ 13.3.3.2).
1473ImplicitConversionSequence::CompareKind
1474Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1475 const ImplicitConversionSequence& ICS2)
1476{
1477 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1478 // conversion sequences (as defined in 13.3.3.1)
1479 // -- a standard conversion sequence (13.3.3.1.1) is a better
1480 // conversion sequence than a user-defined conversion sequence or
1481 // an ellipsis conversion sequence, and
1482 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1483 // conversion sequence than an ellipsis conversion sequence
1484 // (13.3.3.1.3).
1485 //
1486 if (ICS1.ConversionKind < ICS2.ConversionKind)
1487 return ImplicitConversionSequence::Better;
1488 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1489 return ImplicitConversionSequence::Worse;
1490
1491 // Two implicit conversion sequences of the same form are
1492 // indistinguishable conversion sequences unless one of the
1493 // following rules apply: (C++ 13.3.3.2p3):
1494 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1495 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1496 else if (ICS1.ConversionKind ==
1497 ImplicitConversionSequence::UserDefinedConversion) {
1498 // User-defined conversion sequence U1 is a better conversion
1499 // sequence than another user-defined conversion sequence U2 if
1500 // they contain the same user-defined conversion function or
1501 // constructor and if the second standard conversion sequence of
1502 // U1 is better than the second standard conversion sequence of
1503 // U2 (C++ 13.3.3.2p3).
1504 if (ICS1.UserDefined.ConversionFunction ==
1505 ICS2.UserDefined.ConversionFunction)
1506 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1507 ICS2.UserDefined.After);
1508 }
1509
1510 return ImplicitConversionSequence::Indistinguishable;
1511}
1512
1513/// CompareStandardConversionSequences - Compare two standard
1514/// conversion sequences to determine whether one is better than the
1515/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1516ImplicitConversionSequence::CompareKind
1517Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1518 const StandardConversionSequence& SCS2)
1519{
1520 // Standard conversion sequence S1 is a better conversion sequence
1521 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1522
1523 // -- S1 is a proper subsequence of S2 (comparing the conversion
1524 // sequences in the canonical form defined by 13.3.3.1.1,
1525 // excluding any Lvalue Transformation; the identity conversion
1526 // sequence is considered to be a subsequence of any
1527 // non-identity conversion sequence) or, if not that,
1528 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1529 // Neither is a proper subsequence of the other. Do nothing.
1530 ;
1531 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1532 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1533 (SCS1.Second == ICK_Identity &&
1534 SCS1.Third == ICK_Identity))
1535 // SCS1 is a proper subsequence of SCS2.
1536 return ImplicitConversionSequence::Better;
1537 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1538 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1539 (SCS2.Second == ICK_Identity &&
1540 SCS2.Third == ICK_Identity))
1541 // SCS2 is a proper subsequence of SCS1.
1542 return ImplicitConversionSequence::Worse;
1543
1544 // -- the rank of S1 is better than the rank of S2 (by the rules
1545 // defined below), or, if not that,
1546 ImplicitConversionRank Rank1 = SCS1.getRank();
1547 ImplicitConversionRank Rank2 = SCS2.getRank();
1548 if (Rank1 < Rank2)
1549 return ImplicitConversionSequence::Better;
1550 else if (Rank2 < Rank1)
1551 return ImplicitConversionSequence::Worse;
1552
1553 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1554 // are indistinguishable unless one of the following rules
1555 // applies:
1556
1557 // A conversion that is not a conversion of a pointer, or
1558 // pointer to member, to bool is better than another conversion
1559 // that is such a conversion.
1560 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1561 return SCS2.isPointerConversionToBool()
1562 ? ImplicitConversionSequence::Better
1563 : ImplicitConversionSequence::Worse;
1564
1565 // C++ [over.ics.rank]p4b2:
1566 //
1567 // If class B is derived directly or indirectly from class A,
1568 // conversion of B* to A* is better than conversion of B* to
1569 // void*, and conversion of A* to void* is better than conversion
1570 // of B* to void*.
1571 bool SCS1ConvertsToVoid
1572 = SCS1.isPointerConversionToVoidPointer(Context);
1573 bool SCS2ConvertsToVoid
1574 = SCS2.isPointerConversionToVoidPointer(Context);
1575 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1576 // Exactly one of the conversion sequences is a conversion to
1577 // a void pointer; it's the worse conversion.
1578 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1579 : ImplicitConversionSequence::Worse;
1580 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1581 // Neither conversion sequence converts to a void pointer; compare
1582 // their derived-to-base conversions.
1583 if (ImplicitConversionSequence::CompareKind DerivedCK
1584 = CompareDerivedToBaseConversions(SCS1, SCS2))
1585 return DerivedCK;
1586 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1587 // Both conversion sequences are conversions to void
1588 // pointers. Compare the source types to determine if there's an
1589 // inheritance relationship in their sources.
1590 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1591 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1592
1593 // Adjust the types we're converting from via the array-to-pointer
1594 // conversion, if we need to.
1595 if (SCS1.First == ICK_Array_To_Pointer)
1596 FromType1 = Context.getArrayDecayedType(FromType1);
1597 if (SCS2.First == ICK_Array_To_Pointer)
1598 FromType2 = Context.getArrayDecayedType(FromType2);
1599
1600 QualType FromPointee1
1601 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1602 QualType FromPointee2
1603 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1604
1605 if (IsDerivedFrom(FromPointee2, FromPointee1))
1606 return ImplicitConversionSequence::Better;
1607 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1608 return ImplicitConversionSequence::Worse;
1609
1610 // Objective-C++: If one interface is more specific than the
1611 // other, it is the better one.
1612 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1613 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1614 if (FromIface1 && FromIface1) {
1615 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1616 return ImplicitConversionSequence::Better;
1617 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1618 return ImplicitConversionSequence::Worse;
1619 }
1620 }
1621
1622 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1623 // bullet 3).
1624 if (ImplicitConversionSequence::CompareKind QualCK
1625 = CompareQualificationConversions(SCS1, SCS2))
1626 return QualCK;
1627
1628 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1629 // C++0x [over.ics.rank]p3b4:
1630 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1631 // implicit object parameter of a non-static member function declared
1632 // without a ref-qualifier, and S1 binds an rvalue reference to an
1633 // rvalue and S2 binds an lvalue reference.
1634 // FIXME: We don't know if we're dealing with the implicit object parameter,
1635 // or if the member function in this case has a ref qualifier.
1636 // (Of course, we don't have ref qualifiers yet.)
1637 if (SCS1.RRefBinding != SCS2.RRefBinding)
1638 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1639 : ImplicitConversionSequence::Worse;
1640
1641 // C++ [over.ics.rank]p3b4:
1642 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1643 // which the references refer are the same type except for
1644 // top-level cv-qualifiers, and the type to which the reference
1645 // initialized by S2 refers is more cv-qualified than the type
1646 // to which the reference initialized by S1 refers.
1647 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1648 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1649 T1 = Context.getCanonicalType(T1);
1650 T2 = Context.getCanonicalType(T2);
1651 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1652 if (T2.isMoreQualifiedThan(T1))
1653 return ImplicitConversionSequence::Better;
1654 else if (T1.isMoreQualifiedThan(T2))
1655 return ImplicitConversionSequence::Worse;
1656 }
1657 }
1658
1659 return ImplicitConversionSequence::Indistinguishable;
1660}
1661
1662/// CompareQualificationConversions - Compares two standard conversion
1663/// sequences to determine whether they can be ranked based on their
1664/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1665ImplicitConversionSequence::CompareKind
1666Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1667 const StandardConversionSequence& SCS2)
1668{
1669 // C++ 13.3.3.2p3:
1670 // -- S1 and S2 differ only in their qualification conversion and
1671 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1672 // cv-qualification signature of type T1 is a proper subset of
1673 // the cv-qualification signature of type T2, and S1 is not the
1674 // deprecated string literal array-to-pointer conversion (4.2).
1675 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1676 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1677 return ImplicitConversionSequence::Indistinguishable;
1678
1679 // FIXME: the example in the standard doesn't use a qualification
1680 // conversion (!)
1681 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1682 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1683 T1 = Context.getCanonicalType(T1);
1684 T2 = Context.getCanonicalType(T2);
1685
1686 // If the types are the same, we won't learn anything by unwrapped
1687 // them.
1688 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1689 return ImplicitConversionSequence::Indistinguishable;
1690
1691 ImplicitConversionSequence::CompareKind Result
1692 = ImplicitConversionSequence::Indistinguishable;
1693 while (UnwrapSimilarPointerTypes(T1, T2)) {
1694 // Within each iteration of the loop, we check the qualifiers to
1695 // determine if this still looks like a qualification
1696 // conversion. Then, if all is well, we unwrap one more level of
1697 // pointers or pointers-to-members and do it all again
1698 // until there are no more pointers or pointers-to-members left
1699 // to unwrap. This essentially mimics what
1700 // IsQualificationConversion does, but here we're checking for a
1701 // strict subset of qualifiers.
1702 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1703 // The qualifiers are the same, so this doesn't tell us anything
1704 // about how the sequences rank.
1705 ;
1706 else if (T2.isMoreQualifiedThan(T1)) {
1707 // T1 has fewer qualifiers, so it could be the better sequence.
1708 if (Result == ImplicitConversionSequence::Worse)
1709 // Neither has qualifiers that are a subset of the other's
1710 // qualifiers.
1711 return ImplicitConversionSequence::Indistinguishable;
1712
1713 Result = ImplicitConversionSequence::Better;
1714 } else if (T1.isMoreQualifiedThan(T2)) {
1715 // T2 has fewer qualifiers, so it could be the better sequence.
1716 if (Result == ImplicitConversionSequence::Better)
1717 // Neither has qualifiers that are a subset of the other's
1718 // qualifiers.
1719 return ImplicitConversionSequence::Indistinguishable;
1720
1721 Result = ImplicitConversionSequence::Worse;
1722 } else {
1723 // Qualifiers are disjoint.
1724 return ImplicitConversionSequence::Indistinguishable;
1725 }
1726
1727 // If the types after this point are equivalent, we're done.
1728 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1729 break;
1730 }
1731
1732 // Check that the winning standard conversion sequence isn't using
1733 // the deprecated string literal array to pointer conversion.
1734 switch (Result) {
1735 case ImplicitConversionSequence::Better:
1736 if (SCS1.Deprecated)
1737 Result = ImplicitConversionSequence::Indistinguishable;
1738 break;
1739
1740 case ImplicitConversionSequence::Indistinguishable:
1741 break;
1742
1743 case ImplicitConversionSequence::Worse:
1744 if (SCS2.Deprecated)
1745 Result = ImplicitConversionSequence::Indistinguishable;
1746 break;
1747 }
1748
1749 return Result;
1750}
1751
1752/// CompareDerivedToBaseConversions - Compares two standard conversion
1753/// sequences to determine whether they can be ranked based on their
1754/// various kinds of derived-to-base conversions (C++
1755/// [over.ics.rank]p4b3). As part of these checks, we also look at
1756/// conversions between Objective-C interface types.
1757ImplicitConversionSequence::CompareKind
1758Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1759 const StandardConversionSequence& SCS2) {
1760 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1761 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1762 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1763 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1764
1765 // Adjust the types we're converting from via the array-to-pointer
1766 // conversion, if we need to.
1767 if (SCS1.First == ICK_Array_To_Pointer)
1768 FromType1 = Context.getArrayDecayedType(FromType1);
1769 if (SCS2.First == ICK_Array_To_Pointer)
1770 FromType2 = Context.getArrayDecayedType(FromType2);
1771
1772 // Canonicalize all of the types.
1773 FromType1 = Context.getCanonicalType(FromType1);
1774 ToType1 = Context.getCanonicalType(ToType1);
1775 FromType2 = Context.getCanonicalType(FromType2);
1776 ToType2 = Context.getCanonicalType(ToType2);
1777
1778 // C++ [over.ics.rank]p4b3:
1779 //
1780 // If class B is derived directly or indirectly from class A and
1781 // class C is derived directly or indirectly from B,
1782 //
1783 // For Objective-C, we let A, B, and C also be Objective-C
1784 // interfaces.
1785
1786 // Compare based on pointer conversions.
1787 if (SCS1.Second == ICK_Pointer_Conversion &&
1788 SCS2.Second == ICK_Pointer_Conversion &&
1789 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1790 FromType1->isPointerType() && FromType2->isPointerType() &&
1791 ToType1->isPointerType() && ToType2->isPointerType()) {
1792 QualType FromPointee1
1793 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1794 QualType ToPointee1
1795 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1796 QualType FromPointee2
1797 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1798 QualType ToPointee2
1799 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1800
1801 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1802 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1803 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1804 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1805
1806 // -- conversion of C* to B* is better than conversion of C* to A*,
1807 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1808 if (IsDerivedFrom(ToPointee1, ToPointee2))
1809 return ImplicitConversionSequence::Better;
1810 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1811 return ImplicitConversionSequence::Worse;
1812
1813 if (ToIface1 && ToIface2) {
1814 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1815 return ImplicitConversionSequence::Better;
1816 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1817 return ImplicitConversionSequence::Worse;
1818 }
1819 }
1820
1821 // -- conversion of B* to A* is better than conversion of C* to A*,
1822 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1823 if (IsDerivedFrom(FromPointee2, FromPointee1))
1824 return ImplicitConversionSequence::Better;
1825 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1826 return ImplicitConversionSequence::Worse;
1827
1828 if (FromIface1 && FromIface2) {
1829 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1830 return ImplicitConversionSequence::Better;
1831 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1832 return ImplicitConversionSequence::Worse;
1833 }
1834 }
1835 }
1836
1837 // Compare based on reference bindings.
1838 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1839 SCS1.Second == ICK_Derived_To_Base) {
1840 // -- binding of an expression of type C to a reference of type
1841 // B& is better than binding an expression of type C to a
1842 // reference of type A&,
1843 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1844 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1845 if (IsDerivedFrom(ToType1, ToType2))
1846 return ImplicitConversionSequence::Better;
1847 else if (IsDerivedFrom(ToType2, ToType1))
1848 return ImplicitConversionSequence::Worse;
1849 }
1850
1851 // -- binding of an expression of type B to a reference of type
1852 // A& is better than binding an expression of type C to a
1853 // reference of type A&,
1854 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1855 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1856 if (IsDerivedFrom(FromType2, FromType1))
1857 return ImplicitConversionSequence::Better;
1858 else if (IsDerivedFrom(FromType1, FromType2))
1859 return ImplicitConversionSequence::Worse;
1860 }
1861 }
1862
1863
1864 // FIXME: conversion of A::* to B::* is better than conversion of
1865 // A::* to C::*,
1866
1867 // FIXME: conversion of B::* to C::* is better than conversion of
1868 // A::* to C::*, and
1869
1870 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1871 SCS1.Second == ICK_Derived_To_Base) {
1872 // -- conversion of C to B is better than conversion of C to A,
1873 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1874 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1875 if (IsDerivedFrom(ToType1, ToType2))
1876 return ImplicitConversionSequence::Better;
1877 else if (IsDerivedFrom(ToType2, ToType1))
1878 return ImplicitConversionSequence::Worse;
1879 }
1880
1881 // -- conversion of B to A is better than conversion of C to A.
1882 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1883 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1884 if (IsDerivedFrom(FromType2, FromType1))
1885 return ImplicitConversionSequence::Better;
1886 else if (IsDerivedFrom(FromType1, FromType2))
1887 return ImplicitConversionSequence::Worse;
1888 }
1889 }
1890
1891 return ImplicitConversionSequence::Indistinguishable;
1892}
1893
1894/// TryCopyInitialization - Try to copy-initialize a value of type
1895/// ToType from the expression From. Return the implicit conversion
1896/// sequence required to pass this argument, which may be a bad
1897/// conversion sequence (meaning that the argument cannot be passed to
1898/// a parameter of this type). If @p SuppressUserConversions, then we
1899/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1900/// then we treat @p From as an rvalue, even if it is an lvalue.
1901ImplicitConversionSequence
1902Sema::TryCopyInitialization(Expr *From, QualType ToType,
1903 bool SuppressUserConversions, bool ForceRValue) {
1904 if (ToType->isReferenceType()) {
1905 ImplicitConversionSequence ICS;
1906 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions,
1907 /*AllowExplicit=*/false, ForceRValue);
1908 return ICS;
1909 } else {
1910 return TryImplicitConversion(From, ToType, SuppressUserConversions,
1911 ForceRValue);
1912 }
1913}
1914
1915/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1916/// the expression @p From. Returns true (and emits a diagnostic) if there was
1917/// an error, returns false if the initialization succeeded. Elidable should
1918/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1919/// differently in C++0x for this case.
1920bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1921 const char* Flavor, bool Elidable) {
1922 if (!getLangOptions().CPlusPlus) {
1923 // In C, argument passing is the same as performing an assignment.
1924 QualType FromType = From->getType();
1925
1926 AssignConvertType ConvTy =
1927 CheckSingleAssignmentConstraints(ToType, From);
1928 if (ConvTy != Compatible &&
1929 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1930 ConvTy = Compatible;
1931
1932 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1933 FromType, From, Flavor);
1934 }
1935
1936 if (ToType->isReferenceType())
1937 return CheckReferenceInit(From, ToType);
1938
1939 if (!PerformImplicitConversion(From, ToType, Flavor,
1940 /*AllowExplicit=*/false, Elidable))
1941 return false;
1942
1943 return Diag(From->getSourceRange().getBegin(),
1944 diag::err_typecheck_convert_incompatible)
1945 << ToType << From->getType() << Flavor << From->getSourceRange();
1946}
1947
1948/// TryObjectArgumentInitialization - Try to initialize the object
1949/// parameter of the given member function (@c Method) from the
1950/// expression @p From.
1951ImplicitConversionSequence
1952Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1953 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1954 unsigned MethodQuals = Method->getTypeQualifiers();
1955 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1956
1957 // Set up the conversion sequence as a "bad" conversion, to allow us
1958 // to exit early.
1959 ImplicitConversionSequence ICS;
1960 ICS.Standard.setAsIdentityConversion();
1961 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1962
1963 // We need to have an object of class type.
1964 QualType FromType = From->getType();
1965 if (const PointerType *PT = FromType->getAsPointerType())
1966 FromType = PT->getPointeeType();
1967
1968 assert(FromType->isRecordType());
1969
1970 // The implicit object parmeter is has the type "reference to cv X",
1971 // where X is the class of which the function is a member
1972 // (C++ [over.match.funcs]p4). However, when finding an implicit
1973 // conversion sequence for the argument, we are not allowed to
1974 // create temporaries or perform user-defined conversions
1975 // (C++ [over.match.funcs]p5). We perform a simplified version of
1976 // reference binding here, that allows class rvalues to bind to
1977 // non-constant references.
1978
1979 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1980 // with the implicit object parameter (C++ [over.match.funcs]p5).
1981 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1982 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1983 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1984 return ICS;
1985
1986 // Check that we have either the same type or a derived type. It
1987 // affects the conversion rank.
1988 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1989 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1990 ICS.Standard.Second = ICK_Identity;
1991 else if (IsDerivedFrom(FromType, ClassType))
1992 ICS.Standard.Second = ICK_Derived_To_Base;
1993 else
1994 return ICS;
1995
1996 // Success. Mark this as a reference binding.
1997 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1998 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1999 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2000 ICS.Standard.ReferenceBinding = true;
2001 ICS.Standard.DirectBinding = true;
2002 ICS.Standard.RRefBinding = false;
2003 return ICS;
2004}
2005
2006/// PerformObjectArgumentInitialization - Perform initialization of
2007/// the implicit object parameter for the given Method with the given
2008/// expression.
2009bool
2010Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
2011 QualType FromRecordType, DestType;
2012 QualType ImplicitParamRecordType =
2013 Method->getThisType(Context)->getAsPointerType()->getPointeeType();
2014
2015 if (const PointerType *PT = From->getType()->getAsPointerType()) {
2016 FromRecordType = PT->getPointeeType();
2017 DestType = Method->getThisType(Context);
2018 } else {
2019 FromRecordType = From->getType();
2020 DestType = ImplicitParamRecordType;
2021 }
2022
2023 ImplicitConversionSequence ICS
2024 = TryObjectArgumentInitialization(From, Method);
2025 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2026 return Diag(From->getSourceRange().getBegin(),
2027 diag::err_implicit_object_parameter_init)
2028 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2029
2030 if (ICS.Standard.Second == ICK_Derived_To_Base &&
2031 CheckDerivedToBaseConversion(FromRecordType,
2032 ImplicitParamRecordType,
2033 From->getSourceRange().getBegin(),
2034 From->getSourceRange()))
2035 return true;
2036
2037 ImpCastExprToType(From, DestType, /*isLvalue=*/true);
2038 return false;
2039}
2040
2041/// TryContextuallyConvertToBool - Attempt to contextually convert the
2042/// expression From to bool (C++0x [conv]p3).
2043ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2044 return TryImplicitConversion(From, Context.BoolTy, false, true);
2045}
2046
2047/// PerformContextuallyConvertToBool - Perform a contextual conversion
2048/// of the expression From to bool (C++0x [conv]p3).
2049bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2050 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2051 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2052 return false;
2053
2054 return Diag(From->getSourceRange().getBegin(),
2055 diag::err_typecheck_bool_condition)
2056 << From->getType() << From->getSourceRange();
2057}
2058
2059/// AddOverloadCandidate - Adds the given function to the set of
2060/// candidate functions, using the given function call arguments. If
2061/// @p SuppressUserConversions, then don't allow user-defined
2062/// conversions via constructors or conversion operators.
2063/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2064/// hacky way to implement the overloading rules for elidable copy
2065/// initialization in C++0x (C++0x 12.8p15).
2066void
2067Sema::AddOverloadCandidate(FunctionDecl *Function,
2068 Expr **Args, unsigned NumArgs,
2069 OverloadCandidateSet& CandidateSet,
2070 bool SuppressUserConversions,
2071 bool ForceRValue)
2072{
2073 const FunctionProtoType* Proto
2074 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
2075 assert(Proto && "Functions without a prototype cannot be overloaded");
2076 assert(!isa<CXXConversionDecl>(Function) &&
2077 "Use AddConversionCandidate for conversion functions");
2078 assert(!Function->getDescribedFunctionTemplate() &&
2079 "Use AddTemplateOverloadCandidate for function templates");
2080
2081 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2082 if (!isa<CXXConstructorDecl>(Method)) {
2083 // If we get here, it's because we're calling a member function
2084 // that is named without a member access expression (e.g.,
2085 // "this->f") that was either written explicitly or created
2086 // implicitly. This can happen with a qualified call to a member
2087 // function, e.g., X::f(). We use a NULL object as the implied
2088 // object argument (C++ [over.call.func]p3).
2089 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2090 SuppressUserConversions, ForceRValue);
2091 return;
2092 }
2093 // We treat a constructor like a non-member function, since its object
2094 // argument doesn't participate in overload resolution.
2095 }
2096
2097
2098 // Add this candidate
2099 CandidateSet.push_back(OverloadCandidate());
2100 OverloadCandidate& Candidate = CandidateSet.back();
2101 Candidate.Function = Function;
2102 Candidate.Viable = true;
2103 Candidate.IsSurrogate = false;
2104 Candidate.IgnoreObjectArgument = false;
2105
2106 unsigned NumArgsInProto = Proto->getNumArgs();
2107
2108 // (C++ 13.3.2p2): A candidate function having fewer than m
2109 // parameters is viable only if it has an ellipsis in its parameter
2110 // list (8.3.5).
2111 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2112 Candidate.Viable = false;
2113 return;
2114 }
2115
2116 // (C++ 13.3.2p2): A candidate function having more than m parameters
2117 // is viable only if the (m+1)st parameter has a default argument
2118 // (8.3.6). For the purposes of overload resolution, the
2119 // parameter list is truncated on the right, so that there are
2120 // exactly m parameters.
2121 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2122 if (NumArgs < MinRequiredArgs) {
2123 // Not enough arguments.
2124 Candidate.Viable = false;
2125 return;
2126 }
2127
2128 // Determine the implicit conversion sequences for each of the
2129 // arguments.
2130 Candidate.Conversions.resize(NumArgs);
2131 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2132 if (ArgIdx < NumArgsInProto) {
2133 // (C++ 13.3.2p3): for F to be a viable function, there shall
2134 // exist for each argument an implicit conversion sequence
2135 // (13.3.3.1) that converts that argument to the corresponding
2136 // parameter of F.
2137 QualType ParamType = Proto->getArgType(ArgIdx);
2138 Candidate.Conversions[ArgIdx]
2139 = TryCopyInitialization(Args[ArgIdx], ParamType,
2140 SuppressUserConversions, ForceRValue);
2141 if (Candidate.Conversions[ArgIdx].ConversionKind
2142 == ImplicitConversionSequence::BadConversion) {
2143 Candidate.Viable = false;
2144 break;
2145 }
2146 } else {
2147 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2148 // argument for which there is no corresponding parameter is
2149 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2150 Candidate.Conversions[ArgIdx].ConversionKind
2151 = ImplicitConversionSequence::EllipsisConversion;
2152 }
2153 }
2154}
2155
2156/// \brief Add all of the function declarations in the given function set to
2157/// the overload canddiate set.
2158void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2159 Expr **Args, unsigned NumArgs,
2160 OverloadCandidateSet& CandidateSet,
2161 bool SuppressUserConversions) {
2162 for (FunctionSet::const_iterator F = Functions.begin(),
2163 FEnd = Functions.end();
1379 Con != ConEnd; ++Con) {
1380 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1381 if (Constructor->isConvertingConstructor())
1382 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1383 /*SuppressUserConversions=*/true, ForceRValue);
1384 }
1385 }
1386 }
1387
1388 if (!AllowConversionFunctions) {
1389 // Don't allow any conversion functions to enter the overload set.
1390 } else if (const RecordType *FromRecordType
1391 = From->getType()->getAsRecordType()) {
1392 if (CXXRecordDecl *FromRecordDecl
1393 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1394 // Add all of the conversion functions as candidates.
1395 // FIXME: Look for conversions in base classes!
1396 OverloadedFunctionDecl *Conversions
1397 = FromRecordDecl->getConversionFunctions();
1398 for (OverloadedFunctionDecl::function_iterator Func
1399 = Conversions->function_begin();
1400 Func != Conversions->function_end(); ++Func) {
1401 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1402 if (AllowExplicit || !Conv->isExplicit())
1403 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1404 }
1405 }
1406 }
1407
1408 OverloadCandidateSet::iterator Best;
1409 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
1410 case OR_Success:
1411 // Record the standard conversion we used and the conversion function.
1412 if (CXXConstructorDecl *Constructor
1413 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1414 // C++ [over.ics.user]p1:
1415 // If the user-defined conversion is specified by a
1416 // constructor (12.3.1), the initial standard conversion
1417 // sequence converts the source type to the type required by
1418 // the argument of the constructor.
1419 //
1420 // FIXME: What about ellipsis conversions?
1421 QualType ThisType = Constructor->getThisType(Context);
1422 User.Before = Best->Conversions[0].Standard;
1423 User.ConversionFunction = Constructor;
1424 User.After.setAsIdentityConversion();
1425 User.After.FromTypePtr
1426 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1427 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1428 return true;
1429 } else if (CXXConversionDecl *Conversion
1430 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1431 // C++ [over.ics.user]p1:
1432 //
1433 // [...] If the user-defined conversion is specified by a
1434 // conversion function (12.3.2), the initial standard
1435 // conversion sequence converts the source type to the
1436 // implicit object parameter of the conversion function.
1437 User.Before = Best->Conversions[0].Standard;
1438 User.ConversionFunction = Conversion;
1439
1440 // C++ [over.ics.user]p2:
1441 // The second standard conversion sequence converts the
1442 // result of the user-defined conversion to the target type
1443 // for the sequence. Since an implicit conversion sequence
1444 // is an initialization, the special rules for
1445 // initialization by user-defined conversion apply when
1446 // selecting the best user-defined conversion for a
1447 // user-defined conversion sequence (see 13.3.3 and
1448 // 13.3.3.1).
1449 User.After = Best->FinalConversion;
1450 return true;
1451 } else {
1452 assert(false && "Not a constructor or conversion function?");
1453 return false;
1454 }
1455
1456 case OR_No_Viable_Function:
1457 case OR_Deleted:
1458 // No conversion here! We're done.
1459 return false;
1460
1461 case OR_Ambiguous:
1462 // FIXME: See C++ [over.best.ics]p10 for the handling of
1463 // ambiguous conversion sequences.
1464 return false;
1465 }
1466
1467 return false;
1468}
1469
1470/// CompareImplicitConversionSequences - Compare two implicit
1471/// conversion sequences to determine whether one is better than the
1472/// other or if they are indistinguishable (C++ 13.3.3.2).
1473ImplicitConversionSequence::CompareKind
1474Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1475 const ImplicitConversionSequence& ICS2)
1476{
1477 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1478 // conversion sequences (as defined in 13.3.3.1)
1479 // -- a standard conversion sequence (13.3.3.1.1) is a better
1480 // conversion sequence than a user-defined conversion sequence or
1481 // an ellipsis conversion sequence, and
1482 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1483 // conversion sequence than an ellipsis conversion sequence
1484 // (13.3.3.1.3).
1485 //
1486 if (ICS1.ConversionKind < ICS2.ConversionKind)
1487 return ImplicitConversionSequence::Better;
1488 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1489 return ImplicitConversionSequence::Worse;
1490
1491 // Two implicit conversion sequences of the same form are
1492 // indistinguishable conversion sequences unless one of the
1493 // following rules apply: (C++ 13.3.3.2p3):
1494 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1495 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1496 else if (ICS1.ConversionKind ==
1497 ImplicitConversionSequence::UserDefinedConversion) {
1498 // User-defined conversion sequence U1 is a better conversion
1499 // sequence than another user-defined conversion sequence U2 if
1500 // they contain the same user-defined conversion function or
1501 // constructor and if the second standard conversion sequence of
1502 // U1 is better than the second standard conversion sequence of
1503 // U2 (C++ 13.3.3.2p3).
1504 if (ICS1.UserDefined.ConversionFunction ==
1505 ICS2.UserDefined.ConversionFunction)
1506 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1507 ICS2.UserDefined.After);
1508 }
1509
1510 return ImplicitConversionSequence::Indistinguishable;
1511}
1512
1513/// CompareStandardConversionSequences - Compare two standard
1514/// conversion sequences to determine whether one is better than the
1515/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1516ImplicitConversionSequence::CompareKind
1517Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1518 const StandardConversionSequence& SCS2)
1519{
1520 // Standard conversion sequence S1 is a better conversion sequence
1521 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1522
1523 // -- S1 is a proper subsequence of S2 (comparing the conversion
1524 // sequences in the canonical form defined by 13.3.3.1.1,
1525 // excluding any Lvalue Transformation; the identity conversion
1526 // sequence is considered to be a subsequence of any
1527 // non-identity conversion sequence) or, if not that,
1528 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1529 // Neither is a proper subsequence of the other. Do nothing.
1530 ;
1531 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1532 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1533 (SCS1.Second == ICK_Identity &&
1534 SCS1.Third == ICK_Identity))
1535 // SCS1 is a proper subsequence of SCS2.
1536 return ImplicitConversionSequence::Better;
1537 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1538 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1539 (SCS2.Second == ICK_Identity &&
1540 SCS2.Third == ICK_Identity))
1541 // SCS2 is a proper subsequence of SCS1.
1542 return ImplicitConversionSequence::Worse;
1543
1544 // -- the rank of S1 is better than the rank of S2 (by the rules
1545 // defined below), or, if not that,
1546 ImplicitConversionRank Rank1 = SCS1.getRank();
1547 ImplicitConversionRank Rank2 = SCS2.getRank();
1548 if (Rank1 < Rank2)
1549 return ImplicitConversionSequence::Better;
1550 else if (Rank2 < Rank1)
1551 return ImplicitConversionSequence::Worse;
1552
1553 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1554 // are indistinguishable unless one of the following rules
1555 // applies:
1556
1557 // A conversion that is not a conversion of a pointer, or
1558 // pointer to member, to bool is better than another conversion
1559 // that is such a conversion.
1560 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1561 return SCS2.isPointerConversionToBool()
1562 ? ImplicitConversionSequence::Better
1563 : ImplicitConversionSequence::Worse;
1564
1565 // C++ [over.ics.rank]p4b2:
1566 //
1567 // If class B is derived directly or indirectly from class A,
1568 // conversion of B* to A* is better than conversion of B* to
1569 // void*, and conversion of A* to void* is better than conversion
1570 // of B* to void*.
1571 bool SCS1ConvertsToVoid
1572 = SCS1.isPointerConversionToVoidPointer(Context);
1573 bool SCS2ConvertsToVoid
1574 = SCS2.isPointerConversionToVoidPointer(Context);
1575 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1576 // Exactly one of the conversion sequences is a conversion to
1577 // a void pointer; it's the worse conversion.
1578 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1579 : ImplicitConversionSequence::Worse;
1580 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1581 // Neither conversion sequence converts to a void pointer; compare
1582 // their derived-to-base conversions.
1583 if (ImplicitConversionSequence::CompareKind DerivedCK
1584 = CompareDerivedToBaseConversions(SCS1, SCS2))
1585 return DerivedCK;
1586 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1587 // Both conversion sequences are conversions to void
1588 // pointers. Compare the source types to determine if there's an
1589 // inheritance relationship in their sources.
1590 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1591 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1592
1593 // Adjust the types we're converting from via the array-to-pointer
1594 // conversion, if we need to.
1595 if (SCS1.First == ICK_Array_To_Pointer)
1596 FromType1 = Context.getArrayDecayedType(FromType1);
1597 if (SCS2.First == ICK_Array_To_Pointer)
1598 FromType2 = Context.getArrayDecayedType(FromType2);
1599
1600 QualType FromPointee1
1601 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1602 QualType FromPointee2
1603 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1604
1605 if (IsDerivedFrom(FromPointee2, FromPointee1))
1606 return ImplicitConversionSequence::Better;
1607 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1608 return ImplicitConversionSequence::Worse;
1609
1610 // Objective-C++: If one interface is more specific than the
1611 // other, it is the better one.
1612 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1613 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1614 if (FromIface1 && FromIface1) {
1615 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1616 return ImplicitConversionSequence::Better;
1617 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1618 return ImplicitConversionSequence::Worse;
1619 }
1620 }
1621
1622 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1623 // bullet 3).
1624 if (ImplicitConversionSequence::CompareKind QualCK
1625 = CompareQualificationConversions(SCS1, SCS2))
1626 return QualCK;
1627
1628 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1629 // C++0x [over.ics.rank]p3b4:
1630 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1631 // implicit object parameter of a non-static member function declared
1632 // without a ref-qualifier, and S1 binds an rvalue reference to an
1633 // rvalue and S2 binds an lvalue reference.
1634 // FIXME: We don't know if we're dealing with the implicit object parameter,
1635 // or if the member function in this case has a ref qualifier.
1636 // (Of course, we don't have ref qualifiers yet.)
1637 if (SCS1.RRefBinding != SCS2.RRefBinding)
1638 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1639 : ImplicitConversionSequence::Worse;
1640
1641 // C++ [over.ics.rank]p3b4:
1642 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1643 // which the references refer are the same type except for
1644 // top-level cv-qualifiers, and the type to which the reference
1645 // initialized by S2 refers is more cv-qualified than the type
1646 // to which the reference initialized by S1 refers.
1647 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1648 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1649 T1 = Context.getCanonicalType(T1);
1650 T2 = Context.getCanonicalType(T2);
1651 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1652 if (T2.isMoreQualifiedThan(T1))
1653 return ImplicitConversionSequence::Better;
1654 else if (T1.isMoreQualifiedThan(T2))
1655 return ImplicitConversionSequence::Worse;
1656 }
1657 }
1658
1659 return ImplicitConversionSequence::Indistinguishable;
1660}
1661
1662/// CompareQualificationConversions - Compares two standard conversion
1663/// sequences to determine whether they can be ranked based on their
1664/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1665ImplicitConversionSequence::CompareKind
1666Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1667 const StandardConversionSequence& SCS2)
1668{
1669 // C++ 13.3.3.2p3:
1670 // -- S1 and S2 differ only in their qualification conversion and
1671 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1672 // cv-qualification signature of type T1 is a proper subset of
1673 // the cv-qualification signature of type T2, and S1 is not the
1674 // deprecated string literal array-to-pointer conversion (4.2).
1675 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1676 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1677 return ImplicitConversionSequence::Indistinguishable;
1678
1679 // FIXME: the example in the standard doesn't use a qualification
1680 // conversion (!)
1681 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1682 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1683 T1 = Context.getCanonicalType(T1);
1684 T2 = Context.getCanonicalType(T2);
1685
1686 // If the types are the same, we won't learn anything by unwrapped
1687 // them.
1688 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1689 return ImplicitConversionSequence::Indistinguishable;
1690
1691 ImplicitConversionSequence::CompareKind Result
1692 = ImplicitConversionSequence::Indistinguishable;
1693 while (UnwrapSimilarPointerTypes(T1, T2)) {
1694 // Within each iteration of the loop, we check the qualifiers to
1695 // determine if this still looks like a qualification
1696 // conversion. Then, if all is well, we unwrap one more level of
1697 // pointers or pointers-to-members and do it all again
1698 // until there are no more pointers or pointers-to-members left
1699 // to unwrap. This essentially mimics what
1700 // IsQualificationConversion does, but here we're checking for a
1701 // strict subset of qualifiers.
1702 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1703 // The qualifiers are the same, so this doesn't tell us anything
1704 // about how the sequences rank.
1705 ;
1706 else if (T2.isMoreQualifiedThan(T1)) {
1707 // T1 has fewer qualifiers, so it could be the better sequence.
1708 if (Result == ImplicitConversionSequence::Worse)
1709 // Neither has qualifiers that are a subset of the other's
1710 // qualifiers.
1711 return ImplicitConversionSequence::Indistinguishable;
1712
1713 Result = ImplicitConversionSequence::Better;
1714 } else if (T1.isMoreQualifiedThan(T2)) {
1715 // T2 has fewer qualifiers, so it could be the better sequence.
1716 if (Result == ImplicitConversionSequence::Better)
1717 // Neither has qualifiers that are a subset of the other's
1718 // qualifiers.
1719 return ImplicitConversionSequence::Indistinguishable;
1720
1721 Result = ImplicitConversionSequence::Worse;
1722 } else {
1723 // Qualifiers are disjoint.
1724 return ImplicitConversionSequence::Indistinguishable;
1725 }
1726
1727 // If the types after this point are equivalent, we're done.
1728 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1729 break;
1730 }
1731
1732 // Check that the winning standard conversion sequence isn't using
1733 // the deprecated string literal array to pointer conversion.
1734 switch (Result) {
1735 case ImplicitConversionSequence::Better:
1736 if (SCS1.Deprecated)
1737 Result = ImplicitConversionSequence::Indistinguishable;
1738 break;
1739
1740 case ImplicitConversionSequence::Indistinguishable:
1741 break;
1742
1743 case ImplicitConversionSequence::Worse:
1744 if (SCS2.Deprecated)
1745 Result = ImplicitConversionSequence::Indistinguishable;
1746 break;
1747 }
1748
1749 return Result;
1750}
1751
1752/// CompareDerivedToBaseConversions - Compares two standard conversion
1753/// sequences to determine whether they can be ranked based on their
1754/// various kinds of derived-to-base conversions (C++
1755/// [over.ics.rank]p4b3). As part of these checks, we also look at
1756/// conversions between Objective-C interface types.
1757ImplicitConversionSequence::CompareKind
1758Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1759 const StandardConversionSequence& SCS2) {
1760 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1761 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1762 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1763 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1764
1765 // Adjust the types we're converting from via the array-to-pointer
1766 // conversion, if we need to.
1767 if (SCS1.First == ICK_Array_To_Pointer)
1768 FromType1 = Context.getArrayDecayedType(FromType1);
1769 if (SCS2.First == ICK_Array_To_Pointer)
1770 FromType2 = Context.getArrayDecayedType(FromType2);
1771
1772 // Canonicalize all of the types.
1773 FromType1 = Context.getCanonicalType(FromType1);
1774 ToType1 = Context.getCanonicalType(ToType1);
1775 FromType2 = Context.getCanonicalType(FromType2);
1776 ToType2 = Context.getCanonicalType(ToType2);
1777
1778 // C++ [over.ics.rank]p4b3:
1779 //
1780 // If class B is derived directly or indirectly from class A and
1781 // class C is derived directly or indirectly from B,
1782 //
1783 // For Objective-C, we let A, B, and C also be Objective-C
1784 // interfaces.
1785
1786 // Compare based on pointer conversions.
1787 if (SCS1.Second == ICK_Pointer_Conversion &&
1788 SCS2.Second == ICK_Pointer_Conversion &&
1789 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1790 FromType1->isPointerType() && FromType2->isPointerType() &&
1791 ToType1->isPointerType() && ToType2->isPointerType()) {
1792 QualType FromPointee1
1793 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1794 QualType ToPointee1
1795 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1796 QualType FromPointee2
1797 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1798 QualType ToPointee2
1799 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1800
1801 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1802 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1803 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1804 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1805
1806 // -- conversion of C* to B* is better than conversion of C* to A*,
1807 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1808 if (IsDerivedFrom(ToPointee1, ToPointee2))
1809 return ImplicitConversionSequence::Better;
1810 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1811 return ImplicitConversionSequence::Worse;
1812
1813 if (ToIface1 && ToIface2) {
1814 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1815 return ImplicitConversionSequence::Better;
1816 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1817 return ImplicitConversionSequence::Worse;
1818 }
1819 }
1820
1821 // -- conversion of B* to A* is better than conversion of C* to A*,
1822 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1823 if (IsDerivedFrom(FromPointee2, FromPointee1))
1824 return ImplicitConversionSequence::Better;
1825 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1826 return ImplicitConversionSequence::Worse;
1827
1828 if (FromIface1 && FromIface2) {
1829 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1830 return ImplicitConversionSequence::Better;
1831 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1832 return ImplicitConversionSequence::Worse;
1833 }
1834 }
1835 }
1836
1837 // Compare based on reference bindings.
1838 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1839 SCS1.Second == ICK_Derived_To_Base) {
1840 // -- binding of an expression of type C to a reference of type
1841 // B& is better than binding an expression of type C to a
1842 // reference of type A&,
1843 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1844 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1845 if (IsDerivedFrom(ToType1, ToType2))
1846 return ImplicitConversionSequence::Better;
1847 else if (IsDerivedFrom(ToType2, ToType1))
1848 return ImplicitConversionSequence::Worse;
1849 }
1850
1851 // -- binding of an expression of type B to a reference of type
1852 // A& is better than binding an expression of type C to a
1853 // reference of type A&,
1854 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1855 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1856 if (IsDerivedFrom(FromType2, FromType1))
1857 return ImplicitConversionSequence::Better;
1858 else if (IsDerivedFrom(FromType1, FromType2))
1859 return ImplicitConversionSequence::Worse;
1860 }
1861 }
1862
1863
1864 // FIXME: conversion of A::* to B::* is better than conversion of
1865 // A::* to C::*,
1866
1867 // FIXME: conversion of B::* to C::* is better than conversion of
1868 // A::* to C::*, and
1869
1870 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1871 SCS1.Second == ICK_Derived_To_Base) {
1872 // -- conversion of C to B is better than conversion of C to A,
1873 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1874 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1875 if (IsDerivedFrom(ToType1, ToType2))
1876 return ImplicitConversionSequence::Better;
1877 else if (IsDerivedFrom(ToType2, ToType1))
1878 return ImplicitConversionSequence::Worse;
1879 }
1880
1881 // -- conversion of B to A is better than conversion of C to A.
1882 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1883 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1884 if (IsDerivedFrom(FromType2, FromType1))
1885 return ImplicitConversionSequence::Better;
1886 else if (IsDerivedFrom(FromType1, FromType2))
1887 return ImplicitConversionSequence::Worse;
1888 }
1889 }
1890
1891 return ImplicitConversionSequence::Indistinguishable;
1892}
1893
1894/// TryCopyInitialization - Try to copy-initialize a value of type
1895/// ToType from the expression From. Return the implicit conversion
1896/// sequence required to pass this argument, which may be a bad
1897/// conversion sequence (meaning that the argument cannot be passed to
1898/// a parameter of this type). If @p SuppressUserConversions, then we
1899/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1900/// then we treat @p From as an rvalue, even if it is an lvalue.
1901ImplicitConversionSequence
1902Sema::TryCopyInitialization(Expr *From, QualType ToType,
1903 bool SuppressUserConversions, bool ForceRValue) {
1904 if (ToType->isReferenceType()) {
1905 ImplicitConversionSequence ICS;
1906 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions,
1907 /*AllowExplicit=*/false, ForceRValue);
1908 return ICS;
1909 } else {
1910 return TryImplicitConversion(From, ToType, SuppressUserConversions,
1911 ForceRValue);
1912 }
1913}
1914
1915/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1916/// the expression @p From. Returns true (and emits a diagnostic) if there was
1917/// an error, returns false if the initialization succeeded. Elidable should
1918/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1919/// differently in C++0x for this case.
1920bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1921 const char* Flavor, bool Elidable) {
1922 if (!getLangOptions().CPlusPlus) {
1923 // In C, argument passing is the same as performing an assignment.
1924 QualType FromType = From->getType();
1925
1926 AssignConvertType ConvTy =
1927 CheckSingleAssignmentConstraints(ToType, From);
1928 if (ConvTy != Compatible &&
1929 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1930 ConvTy = Compatible;
1931
1932 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1933 FromType, From, Flavor);
1934 }
1935
1936 if (ToType->isReferenceType())
1937 return CheckReferenceInit(From, ToType);
1938
1939 if (!PerformImplicitConversion(From, ToType, Flavor,
1940 /*AllowExplicit=*/false, Elidable))
1941 return false;
1942
1943 return Diag(From->getSourceRange().getBegin(),
1944 diag::err_typecheck_convert_incompatible)
1945 << ToType << From->getType() << Flavor << From->getSourceRange();
1946}
1947
1948/// TryObjectArgumentInitialization - Try to initialize the object
1949/// parameter of the given member function (@c Method) from the
1950/// expression @p From.
1951ImplicitConversionSequence
1952Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1953 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1954 unsigned MethodQuals = Method->getTypeQualifiers();
1955 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1956
1957 // Set up the conversion sequence as a "bad" conversion, to allow us
1958 // to exit early.
1959 ImplicitConversionSequence ICS;
1960 ICS.Standard.setAsIdentityConversion();
1961 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1962
1963 // We need to have an object of class type.
1964 QualType FromType = From->getType();
1965 if (const PointerType *PT = FromType->getAsPointerType())
1966 FromType = PT->getPointeeType();
1967
1968 assert(FromType->isRecordType());
1969
1970 // The implicit object parmeter is has the type "reference to cv X",
1971 // where X is the class of which the function is a member
1972 // (C++ [over.match.funcs]p4). However, when finding an implicit
1973 // conversion sequence for the argument, we are not allowed to
1974 // create temporaries or perform user-defined conversions
1975 // (C++ [over.match.funcs]p5). We perform a simplified version of
1976 // reference binding here, that allows class rvalues to bind to
1977 // non-constant references.
1978
1979 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1980 // with the implicit object parameter (C++ [over.match.funcs]p5).
1981 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1982 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1983 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1984 return ICS;
1985
1986 // Check that we have either the same type or a derived type. It
1987 // affects the conversion rank.
1988 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1989 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1990 ICS.Standard.Second = ICK_Identity;
1991 else if (IsDerivedFrom(FromType, ClassType))
1992 ICS.Standard.Second = ICK_Derived_To_Base;
1993 else
1994 return ICS;
1995
1996 // Success. Mark this as a reference binding.
1997 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1998 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1999 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2000 ICS.Standard.ReferenceBinding = true;
2001 ICS.Standard.DirectBinding = true;
2002 ICS.Standard.RRefBinding = false;
2003 return ICS;
2004}
2005
2006/// PerformObjectArgumentInitialization - Perform initialization of
2007/// the implicit object parameter for the given Method with the given
2008/// expression.
2009bool
2010Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
2011 QualType FromRecordType, DestType;
2012 QualType ImplicitParamRecordType =
2013 Method->getThisType(Context)->getAsPointerType()->getPointeeType();
2014
2015 if (const PointerType *PT = From->getType()->getAsPointerType()) {
2016 FromRecordType = PT->getPointeeType();
2017 DestType = Method->getThisType(Context);
2018 } else {
2019 FromRecordType = From->getType();
2020 DestType = ImplicitParamRecordType;
2021 }
2022
2023 ImplicitConversionSequence ICS
2024 = TryObjectArgumentInitialization(From, Method);
2025 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2026 return Diag(From->getSourceRange().getBegin(),
2027 diag::err_implicit_object_parameter_init)
2028 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2029
2030 if (ICS.Standard.Second == ICK_Derived_To_Base &&
2031 CheckDerivedToBaseConversion(FromRecordType,
2032 ImplicitParamRecordType,
2033 From->getSourceRange().getBegin(),
2034 From->getSourceRange()))
2035 return true;
2036
2037 ImpCastExprToType(From, DestType, /*isLvalue=*/true);
2038 return false;
2039}
2040
2041/// TryContextuallyConvertToBool - Attempt to contextually convert the
2042/// expression From to bool (C++0x [conv]p3).
2043ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2044 return TryImplicitConversion(From, Context.BoolTy, false, true);
2045}
2046
2047/// PerformContextuallyConvertToBool - Perform a contextual conversion
2048/// of the expression From to bool (C++0x [conv]p3).
2049bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2050 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2051 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2052 return false;
2053
2054 return Diag(From->getSourceRange().getBegin(),
2055 diag::err_typecheck_bool_condition)
2056 << From->getType() << From->getSourceRange();
2057}
2058
2059/// AddOverloadCandidate - Adds the given function to the set of
2060/// candidate functions, using the given function call arguments. If
2061/// @p SuppressUserConversions, then don't allow user-defined
2062/// conversions via constructors or conversion operators.
2063/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2064/// hacky way to implement the overloading rules for elidable copy
2065/// initialization in C++0x (C++0x 12.8p15).
2066void
2067Sema::AddOverloadCandidate(FunctionDecl *Function,
2068 Expr **Args, unsigned NumArgs,
2069 OverloadCandidateSet& CandidateSet,
2070 bool SuppressUserConversions,
2071 bool ForceRValue)
2072{
2073 const FunctionProtoType* Proto
2074 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
2075 assert(Proto && "Functions without a prototype cannot be overloaded");
2076 assert(!isa<CXXConversionDecl>(Function) &&
2077 "Use AddConversionCandidate for conversion functions");
2078 assert(!Function->getDescribedFunctionTemplate() &&
2079 "Use AddTemplateOverloadCandidate for function templates");
2080
2081 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2082 if (!isa<CXXConstructorDecl>(Method)) {
2083 // If we get here, it's because we're calling a member function
2084 // that is named without a member access expression (e.g.,
2085 // "this->f") that was either written explicitly or created
2086 // implicitly. This can happen with a qualified call to a member
2087 // function, e.g., X::f(). We use a NULL object as the implied
2088 // object argument (C++ [over.call.func]p3).
2089 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2090 SuppressUserConversions, ForceRValue);
2091 return;
2092 }
2093 // We treat a constructor like a non-member function, since its object
2094 // argument doesn't participate in overload resolution.
2095 }
2096
2097
2098 // Add this candidate
2099 CandidateSet.push_back(OverloadCandidate());
2100 OverloadCandidate& Candidate = CandidateSet.back();
2101 Candidate.Function = Function;
2102 Candidate.Viable = true;
2103 Candidate.IsSurrogate = false;
2104 Candidate.IgnoreObjectArgument = false;
2105
2106 unsigned NumArgsInProto = Proto->getNumArgs();
2107
2108 // (C++ 13.3.2p2): A candidate function having fewer than m
2109 // parameters is viable only if it has an ellipsis in its parameter
2110 // list (8.3.5).
2111 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2112 Candidate.Viable = false;
2113 return;
2114 }
2115
2116 // (C++ 13.3.2p2): A candidate function having more than m parameters
2117 // is viable only if the (m+1)st parameter has a default argument
2118 // (8.3.6). For the purposes of overload resolution, the
2119 // parameter list is truncated on the right, so that there are
2120 // exactly m parameters.
2121 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2122 if (NumArgs < MinRequiredArgs) {
2123 // Not enough arguments.
2124 Candidate.Viable = false;
2125 return;
2126 }
2127
2128 // Determine the implicit conversion sequences for each of the
2129 // arguments.
2130 Candidate.Conversions.resize(NumArgs);
2131 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2132 if (ArgIdx < NumArgsInProto) {
2133 // (C++ 13.3.2p3): for F to be a viable function, there shall
2134 // exist for each argument an implicit conversion sequence
2135 // (13.3.3.1) that converts that argument to the corresponding
2136 // parameter of F.
2137 QualType ParamType = Proto->getArgType(ArgIdx);
2138 Candidate.Conversions[ArgIdx]
2139 = TryCopyInitialization(Args[ArgIdx], ParamType,
2140 SuppressUserConversions, ForceRValue);
2141 if (Candidate.Conversions[ArgIdx].ConversionKind
2142 == ImplicitConversionSequence::BadConversion) {
2143 Candidate.Viable = false;
2144 break;
2145 }
2146 } else {
2147 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2148 // argument for which there is no corresponding parameter is
2149 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2150 Candidate.Conversions[ArgIdx].ConversionKind
2151 = ImplicitConversionSequence::EllipsisConversion;
2152 }
2153 }
2154}
2155
2156/// \brief Add all of the function declarations in the given function set to
2157/// the overload canddiate set.
2158void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2159 Expr **Args, unsigned NumArgs,
2160 OverloadCandidateSet& CandidateSet,
2161 bool SuppressUserConversions) {
2162 for (FunctionSet::const_iterator F = Functions.begin(),
2163 FEnd = Functions.end();
2164 F != FEnd; ++F)
2165 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
2166 SuppressUserConversions);
2164 F != FEnd; ++F) {
2165 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
2166 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2167 SuppressUserConversions);
2168 else
2169 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2170 /*FIXME: explicit args */false, 0, 0,
2171 Args, NumArgs, CandidateSet,
2172 SuppressUserConversions);
2173 }
2167}
2168
2169/// AddMethodCandidate - Adds the given C++ member function to the set
2170/// of candidate functions, using the given function call arguments
2171/// and the object argument (@c Object). For example, in a call
2172/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2173/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2174/// allow user-defined conversions via constructors or conversion
2175/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2176/// a slightly hacky way to implement the overloading rules for elidable copy
2177/// initialization in C++0x (C++0x 12.8p15).
2178void
2179Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2180 Expr **Args, unsigned NumArgs,
2181 OverloadCandidateSet& CandidateSet,
2182 bool SuppressUserConversions, bool ForceRValue)
2183{
2184 const FunctionProtoType* Proto
2185 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
2186 assert(Proto && "Methods without a prototype cannot be overloaded");
2187 assert(!isa<CXXConversionDecl>(Method) &&
2188 "Use AddConversionCandidate for conversion functions");
2189 assert(!isa<CXXConstructorDecl>(Method) &&
2190 "Use AddOverloadCandidate for constructors");
2191
2192 // Add this candidate
2193 CandidateSet.push_back(OverloadCandidate());
2194 OverloadCandidate& Candidate = CandidateSet.back();
2195 Candidate.Function = Method;
2196 Candidate.IsSurrogate = false;
2197 Candidate.IgnoreObjectArgument = false;
2198
2199 unsigned NumArgsInProto = Proto->getNumArgs();
2200
2201 // (C++ 13.3.2p2): A candidate function having fewer than m
2202 // parameters is viable only if it has an ellipsis in its parameter
2203 // list (8.3.5).
2204 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2205 Candidate.Viable = false;
2206 return;
2207 }
2208
2209 // (C++ 13.3.2p2): A candidate function having more than m parameters
2210 // is viable only if the (m+1)st parameter has a default argument
2211 // (8.3.6). For the purposes of overload resolution, the
2212 // parameter list is truncated on the right, so that there are
2213 // exactly m parameters.
2214 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2215 if (NumArgs < MinRequiredArgs) {
2216 // Not enough arguments.
2217 Candidate.Viable = false;
2218 return;
2219 }
2220
2221 Candidate.Viable = true;
2222 Candidate.Conversions.resize(NumArgs + 1);
2223
2224 if (Method->isStatic() || !Object)
2225 // The implicit object argument is ignored.
2226 Candidate.IgnoreObjectArgument = true;
2227 else {
2228 // Determine the implicit conversion sequence for the object
2229 // parameter.
2230 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2231 if (Candidate.Conversions[0].ConversionKind
2232 == ImplicitConversionSequence::BadConversion) {
2233 Candidate.Viable = false;
2234 return;
2235 }
2236 }
2237
2238 // Determine the implicit conversion sequences for each of the
2239 // arguments.
2240 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2241 if (ArgIdx < NumArgsInProto) {
2242 // (C++ 13.3.2p3): for F to be a viable function, there shall
2243 // exist for each argument an implicit conversion sequence
2244 // (13.3.3.1) that converts that argument to the corresponding
2245 // parameter of F.
2246 QualType ParamType = Proto->getArgType(ArgIdx);
2247 Candidate.Conversions[ArgIdx + 1]
2248 = TryCopyInitialization(Args[ArgIdx], ParamType,
2249 SuppressUserConversions, ForceRValue);
2250 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2251 == ImplicitConversionSequence::BadConversion) {
2252 Candidate.Viable = false;
2253 break;
2254 }
2255 } else {
2256 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2257 // argument for which there is no corresponding parameter is
2258 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2259 Candidate.Conversions[ArgIdx + 1].ConversionKind
2260 = ImplicitConversionSequence::EllipsisConversion;
2261 }
2262 }
2263}
2264
2265/// \brief Add a C++ function template as a candidate in the candidate set,
2266/// using template argument deduction to produce an appropriate function
2267/// template specialization.
2268void
2269Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2174}
2175
2176/// AddMethodCandidate - Adds the given C++ member function to the set
2177/// of candidate functions, using the given function call arguments
2178/// and the object argument (@c Object). For example, in a call
2179/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2180/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2181/// allow user-defined conversions via constructors or conversion
2182/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2183/// a slightly hacky way to implement the overloading rules for elidable copy
2184/// initialization in C++0x (C++0x 12.8p15).
2185void
2186Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2187 Expr **Args, unsigned NumArgs,
2188 OverloadCandidateSet& CandidateSet,
2189 bool SuppressUserConversions, bool ForceRValue)
2190{
2191 const FunctionProtoType* Proto
2192 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
2193 assert(Proto && "Methods without a prototype cannot be overloaded");
2194 assert(!isa<CXXConversionDecl>(Method) &&
2195 "Use AddConversionCandidate for conversion functions");
2196 assert(!isa<CXXConstructorDecl>(Method) &&
2197 "Use AddOverloadCandidate for constructors");
2198
2199 // Add this candidate
2200 CandidateSet.push_back(OverloadCandidate());
2201 OverloadCandidate& Candidate = CandidateSet.back();
2202 Candidate.Function = Method;
2203 Candidate.IsSurrogate = false;
2204 Candidate.IgnoreObjectArgument = false;
2205
2206 unsigned NumArgsInProto = Proto->getNumArgs();
2207
2208 // (C++ 13.3.2p2): A candidate function having fewer than m
2209 // parameters is viable only if it has an ellipsis in its parameter
2210 // list (8.3.5).
2211 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2212 Candidate.Viable = false;
2213 return;
2214 }
2215
2216 // (C++ 13.3.2p2): A candidate function having more than m parameters
2217 // is viable only if the (m+1)st parameter has a default argument
2218 // (8.3.6). For the purposes of overload resolution, the
2219 // parameter list is truncated on the right, so that there are
2220 // exactly m parameters.
2221 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2222 if (NumArgs < MinRequiredArgs) {
2223 // Not enough arguments.
2224 Candidate.Viable = false;
2225 return;
2226 }
2227
2228 Candidate.Viable = true;
2229 Candidate.Conversions.resize(NumArgs + 1);
2230
2231 if (Method->isStatic() || !Object)
2232 // The implicit object argument is ignored.
2233 Candidate.IgnoreObjectArgument = true;
2234 else {
2235 // Determine the implicit conversion sequence for the object
2236 // parameter.
2237 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2238 if (Candidate.Conversions[0].ConversionKind
2239 == ImplicitConversionSequence::BadConversion) {
2240 Candidate.Viable = false;
2241 return;
2242 }
2243 }
2244
2245 // Determine the implicit conversion sequences for each of the
2246 // arguments.
2247 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2248 if (ArgIdx < NumArgsInProto) {
2249 // (C++ 13.3.2p3): for F to be a viable function, there shall
2250 // exist for each argument an implicit conversion sequence
2251 // (13.3.3.1) that converts that argument to the corresponding
2252 // parameter of F.
2253 QualType ParamType = Proto->getArgType(ArgIdx);
2254 Candidate.Conversions[ArgIdx + 1]
2255 = TryCopyInitialization(Args[ArgIdx], ParamType,
2256 SuppressUserConversions, ForceRValue);
2257 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2258 == ImplicitConversionSequence::BadConversion) {
2259 Candidate.Viable = false;
2260 break;
2261 }
2262 } else {
2263 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2264 // argument for which there is no corresponding parameter is
2265 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2266 Candidate.Conversions[ArgIdx + 1].ConversionKind
2267 = ImplicitConversionSequence::EllipsisConversion;
2268 }
2269 }
2270}
2271
2272/// \brief Add a C++ function template as a candidate in the candidate set,
2273/// using template argument deduction to produce an appropriate function
2274/// template specialization.
2275void
2276Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2277 bool HasExplicitTemplateArgs,
2278 const TemplateArgument *ExplicitTemplateArgs,
2279 unsigned NumExplicitTemplateArgs,
2270 Expr **Args, unsigned NumArgs,
2271 OverloadCandidateSet& CandidateSet,
2272 bool SuppressUserConversions,
2273 bool ForceRValue) {
2274 // C++ [over.match.funcs]p7:
2275 // In each case where a candidate is a function template, candidate
2276 // function template specializations are generated using template argument
2277 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2278 // candidate functions in the usual way.113) A given name can refer to one
2279 // or more function templates and also to a set of overloaded non-template
2280 // functions. In such a case, the candidate functions generated from each
2281 // function template are combined with the set of non-template candidate
2282 // functions.
2283 TemplateDeductionInfo Info(Context);
2284 FunctionDecl *Specialization = 0;
2285 if (TemplateDeductionResult Result
2280 Expr **Args, unsigned NumArgs,
2281 OverloadCandidateSet& CandidateSet,
2282 bool SuppressUserConversions,
2283 bool ForceRValue) {
2284 // C++ [over.match.funcs]p7:
2285 // In each case where a candidate is a function template, candidate
2286 // function template specializations are generated using template argument
2287 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2288 // candidate functions in the usual way.113) A given name can refer to one
2289 // or more function templates and also to a set of overloaded non-template
2290 // functions. In such a case, the candidate functions generated from each
2291 // function template are combined with the set of non-template candidate
2292 // functions.
2293 TemplateDeductionInfo Info(Context);
2294 FunctionDecl *Specialization = 0;
2295 if (TemplateDeductionResult Result
2286 = DeduceTemplateArguments(FunctionTemplate, Args, NumArgs,
2287 Specialization, Info)) {
2296 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2297 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2298 Args, NumArgs, Specialization, Info)) {
2288 // FIXME: Record what happened with template argument deduction, so
2289 // that we can give the user a beautiful diagnostic.
2290 (void)Result;
2291 return;
2292 }
2293
2294 // Add the function template specialization produced by template argument
2295 // deduction as a candidate.
2296 assert(Specialization && "Missing function template specialization?");
2297 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2298 SuppressUserConversions, ForceRValue);
2299}
2300
2301/// AddConversionCandidate - Add a C++ conversion function as a
2302/// candidate in the candidate set (C++ [over.match.conv],
2303/// C++ [over.match.copy]). From is the expression we're converting from,
2304/// and ToType is the type that we're eventually trying to convert to
2305/// (which may or may not be the same type as the type that the
2306/// conversion function produces).
2307void
2308Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2309 Expr *From, QualType ToType,
2310 OverloadCandidateSet& CandidateSet) {
2311 // Add this candidate
2312 CandidateSet.push_back(OverloadCandidate());
2313 OverloadCandidate& Candidate = CandidateSet.back();
2314 Candidate.Function = Conversion;
2315 Candidate.IsSurrogate = false;
2316 Candidate.IgnoreObjectArgument = false;
2317 Candidate.FinalConversion.setAsIdentityConversion();
2318 Candidate.FinalConversion.FromTypePtr
2319 = Conversion->getConversionType().getAsOpaquePtr();
2320 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2321
2322 // Determine the implicit conversion sequence for the implicit
2323 // object parameter.
2324 Candidate.Viable = true;
2325 Candidate.Conversions.resize(1);
2326 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
2327
2328 if (Candidate.Conversions[0].ConversionKind
2329 == ImplicitConversionSequence::BadConversion) {
2330 Candidate.Viable = false;
2331 return;
2332 }
2333
2334 // To determine what the conversion from the result of calling the
2335 // conversion function to the type we're eventually trying to
2336 // convert to (ToType), we need to synthesize a call to the
2337 // conversion function and attempt copy initialization from it. This
2338 // makes sure that we get the right semantics with respect to
2339 // lvalues/rvalues and the type. Fortunately, we can allocate this
2340 // call on the stack and we don't need its arguments to be
2341 // well-formed.
2342 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2343 SourceLocation());
2344 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
2345 &ConversionRef, false);
2346
2347 // Note that it is safe to allocate CallExpr on the stack here because
2348 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2349 // allocator).
2350 CallExpr Call(Context, &ConversionFn, 0, 0,
2351 Conversion->getConversionType().getNonReferenceType(),
2352 SourceLocation());
2353 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2354 switch (ICS.ConversionKind) {
2355 case ImplicitConversionSequence::StandardConversion:
2356 Candidate.FinalConversion = ICS.Standard;
2357 break;
2358
2359 case ImplicitConversionSequence::BadConversion:
2360 Candidate.Viable = false;
2361 break;
2362
2363 default:
2364 assert(false &&
2365 "Can only end up with a standard conversion sequence or failure");
2366 }
2367}
2368
2369/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2370/// converts the given @c Object to a function pointer via the
2371/// conversion function @c Conversion, and then attempts to call it
2372/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2373/// the type of function that we'll eventually be calling.
2374void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2375 const FunctionProtoType *Proto,
2376 Expr *Object, Expr **Args, unsigned NumArgs,
2377 OverloadCandidateSet& CandidateSet) {
2378 CandidateSet.push_back(OverloadCandidate());
2379 OverloadCandidate& Candidate = CandidateSet.back();
2380 Candidate.Function = 0;
2381 Candidate.Surrogate = Conversion;
2382 Candidate.Viable = true;
2383 Candidate.IsSurrogate = true;
2384 Candidate.IgnoreObjectArgument = false;
2385 Candidate.Conversions.resize(NumArgs + 1);
2386
2387 // Determine the implicit conversion sequence for the implicit
2388 // object parameter.
2389 ImplicitConversionSequence ObjectInit
2390 = TryObjectArgumentInitialization(Object, Conversion);
2391 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2392 Candidate.Viable = false;
2393 return;
2394 }
2395
2396 // The first conversion is actually a user-defined conversion whose
2397 // first conversion is ObjectInit's standard conversion (which is
2398 // effectively a reference binding). Record it as such.
2399 Candidate.Conversions[0].ConversionKind
2400 = ImplicitConversionSequence::UserDefinedConversion;
2401 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2402 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2403 Candidate.Conversions[0].UserDefined.After
2404 = Candidate.Conversions[0].UserDefined.Before;
2405 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2406
2407 // Find the
2408 unsigned NumArgsInProto = Proto->getNumArgs();
2409
2410 // (C++ 13.3.2p2): A candidate function having fewer than m
2411 // parameters is viable only if it has an ellipsis in its parameter
2412 // list (8.3.5).
2413 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2414 Candidate.Viable = false;
2415 return;
2416 }
2417
2418 // Function types don't have any default arguments, so just check if
2419 // we have enough arguments.
2420 if (NumArgs < NumArgsInProto) {
2421 // Not enough arguments.
2422 Candidate.Viable = false;
2423 return;
2424 }
2425
2426 // Determine the implicit conversion sequences for each of the
2427 // arguments.
2428 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2429 if (ArgIdx < NumArgsInProto) {
2430 // (C++ 13.3.2p3): for F to be a viable function, there shall
2431 // exist for each argument an implicit conversion sequence
2432 // (13.3.3.1) that converts that argument to the corresponding
2433 // parameter of F.
2434 QualType ParamType = Proto->getArgType(ArgIdx);
2435 Candidate.Conversions[ArgIdx + 1]
2436 = TryCopyInitialization(Args[ArgIdx], ParamType,
2437 /*SuppressUserConversions=*/false);
2438 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2439 == ImplicitConversionSequence::BadConversion) {
2440 Candidate.Viable = false;
2441 break;
2442 }
2443 } else {
2444 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2445 // argument for which there is no corresponding parameter is
2446 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2447 Candidate.Conversions[ArgIdx + 1].ConversionKind
2448 = ImplicitConversionSequence::EllipsisConversion;
2449 }
2450 }
2451}
2452
2453// FIXME: This will eventually be removed, once we've migrated all of the
2454// operator overloading logic over to the scheme used by binary operators, which
2455// works for template instantiation.
2456void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2457 SourceLocation OpLoc,
2458 Expr **Args, unsigned NumArgs,
2459 OverloadCandidateSet& CandidateSet,
2460 SourceRange OpRange) {
2461
2462 FunctionSet Functions;
2463
2464 QualType T1 = Args[0]->getType();
2465 QualType T2;
2466 if (NumArgs > 1)
2467 T2 = Args[1]->getType();
2468
2469 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2470 if (S)
2471 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2472 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2473 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2474 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2475 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2476}
2477
2478/// \brief Add overload candidates for overloaded operators that are
2479/// member functions.
2480///
2481/// Add the overloaded operator candidates that are member functions
2482/// for the operator Op that was used in an operator expression such
2483/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2484/// CandidateSet will store the added overload candidates. (C++
2485/// [over.match.oper]).
2486void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2487 SourceLocation OpLoc,
2488 Expr **Args, unsigned NumArgs,
2489 OverloadCandidateSet& CandidateSet,
2490 SourceRange OpRange) {
2491 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2492
2493 // C++ [over.match.oper]p3:
2494 // For a unary operator @ with an operand of a type whose
2495 // cv-unqualified version is T1, and for a binary operator @ with
2496 // a left operand of a type whose cv-unqualified version is T1 and
2497 // a right operand of a type whose cv-unqualified version is T2,
2498 // three sets of candidate functions, designated member
2499 // candidates, non-member candidates and built-in candidates, are
2500 // constructed as follows:
2501 QualType T1 = Args[0]->getType();
2502 QualType T2;
2503 if (NumArgs > 1)
2504 T2 = Args[1]->getType();
2505
2506 // -- If T1 is a class type, the set of member candidates is the
2507 // result of the qualified lookup of T1::operator@
2508 // (13.3.1.1.1); otherwise, the set of member candidates is
2509 // empty.
2510 // FIXME: Lookup in base classes, too!
2511 if (const RecordType *T1Rec = T1->getAsRecordType()) {
2512 DeclContext::lookup_const_iterator Oper, OperEnd;
2299 // FIXME: Record what happened with template argument deduction, so
2300 // that we can give the user a beautiful diagnostic.
2301 (void)Result;
2302 return;
2303 }
2304
2305 // Add the function template specialization produced by template argument
2306 // deduction as a candidate.
2307 assert(Specialization && "Missing function template specialization?");
2308 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2309 SuppressUserConversions, ForceRValue);
2310}
2311
2312/// AddConversionCandidate - Add a C++ conversion function as a
2313/// candidate in the candidate set (C++ [over.match.conv],
2314/// C++ [over.match.copy]). From is the expression we're converting from,
2315/// and ToType is the type that we're eventually trying to convert to
2316/// (which may or may not be the same type as the type that the
2317/// conversion function produces).
2318void
2319Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2320 Expr *From, QualType ToType,
2321 OverloadCandidateSet& CandidateSet) {
2322 // Add this candidate
2323 CandidateSet.push_back(OverloadCandidate());
2324 OverloadCandidate& Candidate = CandidateSet.back();
2325 Candidate.Function = Conversion;
2326 Candidate.IsSurrogate = false;
2327 Candidate.IgnoreObjectArgument = false;
2328 Candidate.FinalConversion.setAsIdentityConversion();
2329 Candidate.FinalConversion.FromTypePtr
2330 = Conversion->getConversionType().getAsOpaquePtr();
2331 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2332
2333 // Determine the implicit conversion sequence for the implicit
2334 // object parameter.
2335 Candidate.Viable = true;
2336 Candidate.Conversions.resize(1);
2337 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
2338
2339 if (Candidate.Conversions[0].ConversionKind
2340 == ImplicitConversionSequence::BadConversion) {
2341 Candidate.Viable = false;
2342 return;
2343 }
2344
2345 // To determine what the conversion from the result of calling the
2346 // conversion function to the type we're eventually trying to
2347 // convert to (ToType), we need to synthesize a call to the
2348 // conversion function and attempt copy initialization from it. This
2349 // makes sure that we get the right semantics with respect to
2350 // lvalues/rvalues and the type. Fortunately, we can allocate this
2351 // call on the stack and we don't need its arguments to be
2352 // well-formed.
2353 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2354 SourceLocation());
2355 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
2356 &ConversionRef, false);
2357
2358 // Note that it is safe to allocate CallExpr on the stack here because
2359 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2360 // allocator).
2361 CallExpr Call(Context, &ConversionFn, 0, 0,
2362 Conversion->getConversionType().getNonReferenceType(),
2363 SourceLocation());
2364 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2365 switch (ICS.ConversionKind) {
2366 case ImplicitConversionSequence::StandardConversion:
2367 Candidate.FinalConversion = ICS.Standard;
2368 break;
2369
2370 case ImplicitConversionSequence::BadConversion:
2371 Candidate.Viable = false;
2372 break;
2373
2374 default:
2375 assert(false &&
2376 "Can only end up with a standard conversion sequence or failure");
2377 }
2378}
2379
2380/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2381/// converts the given @c Object to a function pointer via the
2382/// conversion function @c Conversion, and then attempts to call it
2383/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2384/// the type of function that we'll eventually be calling.
2385void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2386 const FunctionProtoType *Proto,
2387 Expr *Object, Expr **Args, unsigned NumArgs,
2388 OverloadCandidateSet& CandidateSet) {
2389 CandidateSet.push_back(OverloadCandidate());
2390 OverloadCandidate& Candidate = CandidateSet.back();
2391 Candidate.Function = 0;
2392 Candidate.Surrogate = Conversion;
2393 Candidate.Viable = true;
2394 Candidate.IsSurrogate = true;
2395 Candidate.IgnoreObjectArgument = false;
2396 Candidate.Conversions.resize(NumArgs + 1);
2397
2398 // Determine the implicit conversion sequence for the implicit
2399 // object parameter.
2400 ImplicitConversionSequence ObjectInit
2401 = TryObjectArgumentInitialization(Object, Conversion);
2402 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2403 Candidate.Viable = false;
2404 return;
2405 }
2406
2407 // The first conversion is actually a user-defined conversion whose
2408 // first conversion is ObjectInit's standard conversion (which is
2409 // effectively a reference binding). Record it as such.
2410 Candidate.Conversions[0].ConversionKind
2411 = ImplicitConversionSequence::UserDefinedConversion;
2412 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2413 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2414 Candidate.Conversions[0].UserDefined.After
2415 = Candidate.Conversions[0].UserDefined.Before;
2416 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2417
2418 // Find the
2419 unsigned NumArgsInProto = Proto->getNumArgs();
2420
2421 // (C++ 13.3.2p2): A candidate function having fewer than m
2422 // parameters is viable only if it has an ellipsis in its parameter
2423 // list (8.3.5).
2424 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2425 Candidate.Viable = false;
2426 return;
2427 }
2428
2429 // Function types don't have any default arguments, so just check if
2430 // we have enough arguments.
2431 if (NumArgs < NumArgsInProto) {
2432 // Not enough arguments.
2433 Candidate.Viable = false;
2434 return;
2435 }
2436
2437 // Determine the implicit conversion sequences for each of the
2438 // arguments.
2439 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2440 if (ArgIdx < NumArgsInProto) {
2441 // (C++ 13.3.2p3): for F to be a viable function, there shall
2442 // exist for each argument an implicit conversion sequence
2443 // (13.3.3.1) that converts that argument to the corresponding
2444 // parameter of F.
2445 QualType ParamType = Proto->getArgType(ArgIdx);
2446 Candidate.Conversions[ArgIdx + 1]
2447 = TryCopyInitialization(Args[ArgIdx], ParamType,
2448 /*SuppressUserConversions=*/false);
2449 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2450 == ImplicitConversionSequence::BadConversion) {
2451 Candidate.Viable = false;
2452 break;
2453 }
2454 } else {
2455 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2456 // argument for which there is no corresponding parameter is
2457 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2458 Candidate.Conversions[ArgIdx + 1].ConversionKind
2459 = ImplicitConversionSequence::EllipsisConversion;
2460 }
2461 }
2462}
2463
2464// FIXME: This will eventually be removed, once we've migrated all of the
2465// operator overloading logic over to the scheme used by binary operators, which
2466// works for template instantiation.
2467void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2468 SourceLocation OpLoc,
2469 Expr **Args, unsigned NumArgs,
2470 OverloadCandidateSet& CandidateSet,
2471 SourceRange OpRange) {
2472
2473 FunctionSet Functions;
2474
2475 QualType T1 = Args[0]->getType();
2476 QualType T2;
2477 if (NumArgs > 1)
2478 T2 = Args[1]->getType();
2479
2480 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2481 if (S)
2482 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2483 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2484 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2485 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2486 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2487}
2488
2489/// \brief Add overload candidates for overloaded operators that are
2490/// member functions.
2491///
2492/// Add the overloaded operator candidates that are member functions
2493/// for the operator Op that was used in an operator expression such
2494/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2495/// CandidateSet will store the added overload candidates. (C++
2496/// [over.match.oper]).
2497void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2498 SourceLocation OpLoc,
2499 Expr **Args, unsigned NumArgs,
2500 OverloadCandidateSet& CandidateSet,
2501 SourceRange OpRange) {
2502 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2503
2504 // C++ [over.match.oper]p3:
2505 // For a unary operator @ with an operand of a type whose
2506 // cv-unqualified version is T1, and for a binary operator @ with
2507 // a left operand of a type whose cv-unqualified version is T1 and
2508 // a right operand of a type whose cv-unqualified version is T2,
2509 // three sets of candidate functions, designated member
2510 // candidates, non-member candidates and built-in candidates, are
2511 // constructed as follows:
2512 QualType T1 = Args[0]->getType();
2513 QualType T2;
2514 if (NumArgs > 1)
2515 T2 = Args[1]->getType();
2516
2517 // -- If T1 is a class type, the set of member candidates is the
2518 // result of the qualified lookup of T1::operator@
2519 // (13.3.1.1.1); otherwise, the set of member candidates is
2520 // empty.
2521 // FIXME: Lookup in base classes, too!
2522 if (const RecordType *T1Rec = T1->getAsRecordType()) {
2523 DeclContext::lookup_const_iterator Oper, OperEnd;
2513 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(Context, OpName);
2524 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
2514 Oper != OperEnd; ++Oper)
2515 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2516 Args+1, NumArgs - 1, CandidateSet,
2517 /*SuppressUserConversions=*/false);
2518 }
2519}
2520
2521/// AddBuiltinCandidate - Add a candidate for a built-in
2522/// operator. ResultTy and ParamTys are the result and parameter types
2523/// of the built-in candidate, respectively. Args and NumArgs are the
2524/// arguments being passed to the candidate. IsAssignmentOperator
2525/// should be true when this built-in candidate is an assignment
2526/// operator. NumContextualBoolArguments is the number of arguments
2527/// (at the beginning of the argument list) that will be contextually
2528/// converted to bool.
2529void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2530 Expr **Args, unsigned NumArgs,
2531 OverloadCandidateSet& CandidateSet,
2532 bool IsAssignmentOperator,
2533 unsigned NumContextualBoolArguments) {
2534 // Add this candidate
2535 CandidateSet.push_back(OverloadCandidate());
2536 OverloadCandidate& Candidate = CandidateSet.back();
2537 Candidate.Function = 0;
2538 Candidate.IsSurrogate = false;
2539 Candidate.IgnoreObjectArgument = false;
2540 Candidate.BuiltinTypes.ResultTy = ResultTy;
2541 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2542 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2543
2544 // Determine the implicit conversion sequences for each of the
2545 // arguments.
2546 Candidate.Viable = true;
2547 Candidate.Conversions.resize(NumArgs);
2548 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2549 // C++ [over.match.oper]p4:
2550 // For the built-in assignment operators, conversions of the
2551 // left operand are restricted as follows:
2552 // -- no temporaries are introduced to hold the left operand, and
2553 // -- no user-defined conversions are applied to the left
2554 // operand to achieve a type match with the left-most
2555 // parameter of a built-in candidate.
2556 //
2557 // We block these conversions by turning off user-defined
2558 // conversions, since that is the only way that initialization of
2559 // a reference to a non-class type can occur from something that
2560 // is not of the same type.
2561 if (ArgIdx < NumContextualBoolArguments) {
2562 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2563 "Contextual conversion to bool requires bool type");
2564 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2565 } else {
2566 Candidate.Conversions[ArgIdx]
2567 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2568 ArgIdx == 0 && IsAssignmentOperator);
2569 }
2570 if (Candidate.Conversions[ArgIdx].ConversionKind
2571 == ImplicitConversionSequence::BadConversion) {
2572 Candidate.Viable = false;
2573 break;
2574 }
2575 }
2576}
2577
2578/// BuiltinCandidateTypeSet - A set of types that will be used for the
2579/// candidate operator functions for built-in operators (C++
2580/// [over.built]). The types are separated into pointer types and
2581/// enumeration types.
2582class BuiltinCandidateTypeSet {
2583 /// TypeSet - A set of types.
2584 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
2585
2586 /// PointerTypes - The set of pointer types that will be used in the
2587 /// built-in candidates.
2588 TypeSet PointerTypes;
2589
2590 /// MemberPointerTypes - The set of member pointer types that will be
2591 /// used in the built-in candidates.
2592 TypeSet MemberPointerTypes;
2593
2594 /// EnumerationTypes - The set of enumeration types that will be
2595 /// used in the built-in candidates.
2596 TypeSet EnumerationTypes;
2597
2598 /// Context - The AST context in which we will build the type sets.
2599 ASTContext &Context;
2600
2601 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2602 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
2603
2604public:
2605 /// iterator - Iterates through the types that are part of the set.
2606 typedef TypeSet::iterator iterator;
2607
2608 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2609
2610 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2611 bool AllowExplicitConversions);
2612
2613 /// pointer_begin - First pointer type found;
2614 iterator pointer_begin() { return PointerTypes.begin(); }
2615
2616 /// pointer_end - Past the last pointer type found;
2617 iterator pointer_end() { return PointerTypes.end(); }
2618
2619 /// member_pointer_begin - First member pointer type found;
2620 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2621
2622 /// member_pointer_end - Past the last member pointer type found;
2623 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2624
2625 /// enumeration_begin - First enumeration type found;
2626 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2627
2628 /// enumeration_end - Past the last enumeration type found;
2629 iterator enumeration_end() { return EnumerationTypes.end(); }
2630};
2631
2632/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2633/// the set of pointer types along with any more-qualified variants of
2634/// that type. For example, if @p Ty is "int const *", this routine
2635/// will add "int const *", "int const volatile *", "int const
2636/// restrict *", and "int const volatile restrict *" to the set of
2637/// pointer types. Returns true if the add of @p Ty itself succeeded,
2638/// false otherwise.
2639bool
2640BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
2641 // Insert this type.
2642 if (!PointerTypes.insert(Ty))
2643 return false;
2644
2645 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2646 QualType PointeeTy = PointerTy->getPointeeType();
2647 // FIXME: Optimize this so that we don't keep trying to add the same types.
2648
2649 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2650 // pointer conversions that don't cast away constness?
2651 if (!PointeeTy.isConstQualified())
2652 AddPointerWithMoreQualifiedTypeVariants
2653 (Context.getPointerType(PointeeTy.withConst()));
2654 if (!PointeeTy.isVolatileQualified())
2655 AddPointerWithMoreQualifiedTypeVariants
2656 (Context.getPointerType(PointeeTy.withVolatile()));
2657 if (!PointeeTy.isRestrictQualified())
2658 AddPointerWithMoreQualifiedTypeVariants
2659 (Context.getPointerType(PointeeTy.withRestrict()));
2660 }
2661
2662 return true;
2663}
2664
2665/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2666/// to the set of pointer types along with any more-qualified variants of
2667/// that type. For example, if @p Ty is "int const *", this routine
2668/// will add "int const *", "int const volatile *", "int const
2669/// restrict *", and "int const volatile restrict *" to the set of
2670/// pointer types. Returns true if the add of @p Ty itself succeeded,
2671/// false otherwise.
2672bool
2673BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2674 QualType Ty) {
2675 // Insert this type.
2676 if (!MemberPointerTypes.insert(Ty))
2677 return false;
2678
2679 if (const MemberPointerType *PointerTy = Ty->getAsMemberPointerType()) {
2680 QualType PointeeTy = PointerTy->getPointeeType();
2681 const Type *ClassTy = PointerTy->getClass();
2682 // FIXME: Optimize this so that we don't keep trying to add the same types.
2683
2684 if (!PointeeTy.isConstQualified())
2685 AddMemberPointerWithMoreQualifiedTypeVariants
2686 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2687 if (!PointeeTy.isVolatileQualified())
2688 AddMemberPointerWithMoreQualifiedTypeVariants
2689 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2690 if (!PointeeTy.isRestrictQualified())
2691 AddMemberPointerWithMoreQualifiedTypeVariants
2692 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2693 }
2694
2695 return true;
2696}
2697
2698/// AddTypesConvertedFrom - Add each of the types to which the type @p
2699/// Ty can be implicit converted to the given set of @p Types. We're
2700/// primarily interested in pointer types and enumeration types. We also
2701/// take member pointer types, for the conditional operator.
2702/// AllowUserConversions is true if we should look at the conversion
2703/// functions of a class type, and AllowExplicitConversions if we
2704/// should also include the explicit conversion functions of a class
2705/// type.
2706void
2707BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2708 bool AllowUserConversions,
2709 bool AllowExplicitConversions) {
2710 // Only deal with canonical types.
2711 Ty = Context.getCanonicalType(Ty);
2712
2713 // Look through reference types; they aren't part of the type of an
2714 // expression for the purposes of conversions.
2715 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2716 Ty = RefTy->getPointeeType();
2717
2718 // We don't care about qualifiers on the type.
2719 Ty = Ty.getUnqualifiedType();
2720
2721 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2722 QualType PointeeTy = PointerTy->getPointeeType();
2723
2724 // Insert our type, and its more-qualified variants, into the set
2725 // of types.
2726 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
2727 return;
2728
2729 // Add 'cv void*' to our set of types.
2730 if (!Ty->isVoidType()) {
2731 QualType QualVoid
2732 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2733 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2734 }
2735
2736 // If this is a pointer to a class type, add pointers to its bases
2737 // (with the same level of cv-qualification as the original
2738 // derived class, of course).
2739 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2740 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2741 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2742 Base != ClassDecl->bases_end(); ++Base) {
2743 QualType BaseTy = Context.getCanonicalType(Base->getType());
2744 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2745
2746 // Add the pointer type, recursively, so that we get all of
2747 // the indirect base classes, too.
2748 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
2749 }
2750 }
2751 } else if (Ty->isMemberPointerType()) {
2752 // Member pointers are far easier, since the pointee can't be converted.
2753 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2754 return;
2755 } else if (Ty->isEnumeralType()) {
2756 EnumerationTypes.insert(Ty);
2757 } else if (AllowUserConversions) {
2758 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2759 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2760 // FIXME: Visit conversion functions in the base classes, too.
2761 OverloadedFunctionDecl *Conversions
2762 = ClassDecl->getConversionFunctions();
2763 for (OverloadedFunctionDecl::function_iterator Func
2764 = Conversions->function_begin();
2765 Func != Conversions->function_end(); ++Func) {
2766 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2767 if (AllowExplicitConversions || !Conv->isExplicit())
2768 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
2769 }
2770 }
2771 }
2772}
2773
2774/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2775/// operator overloads to the candidate set (C++ [over.built]), based
2776/// on the operator @p Op and the arguments given. For example, if the
2777/// operator is a binary '+', this routine might add "int
2778/// operator+(int, int)" to cover integer addition.
2779void
2780Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2781 Expr **Args, unsigned NumArgs,
2782 OverloadCandidateSet& CandidateSet) {
2783 // The set of "promoted arithmetic types", which are the arithmetic
2784 // types are that preserved by promotion (C++ [over.built]p2). Note
2785 // that the first few of these types are the promoted integral
2786 // types; these types need to be first.
2787 // FIXME: What about complex?
2788 const unsigned FirstIntegralType = 0;
2789 const unsigned LastIntegralType = 13;
2790 const unsigned FirstPromotedIntegralType = 7,
2791 LastPromotedIntegralType = 13;
2792 const unsigned FirstPromotedArithmeticType = 7,
2793 LastPromotedArithmeticType = 16;
2794 const unsigned NumArithmeticTypes = 16;
2795 QualType ArithmeticTypes[NumArithmeticTypes] = {
2796 Context.BoolTy, Context.CharTy, Context.WCharTy,
2797 Context.SignedCharTy, Context.ShortTy,
2798 Context.UnsignedCharTy, Context.UnsignedShortTy,
2799 Context.IntTy, Context.LongTy, Context.LongLongTy,
2800 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2801 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2802 };
2803
2804 // Find all of the types that the arguments can convert to, but only
2805 // if the operator we're looking at has built-in operator candidates
2806 // that make use of these types.
2807 BuiltinCandidateTypeSet CandidateTypes(Context);
2808 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2809 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
2810 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
2811 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
2812 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2813 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
2814 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2815 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2816 true,
2817 (Op == OO_Exclaim ||
2818 Op == OO_AmpAmp ||
2819 Op == OO_PipePipe));
2820 }
2821
2822 bool isComparison = false;
2823 switch (Op) {
2824 case OO_None:
2825 case NUM_OVERLOADED_OPERATORS:
2826 assert(false && "Expected an overloaded operator");
2827 break;
2828
2829 case OO_Star: // '*' is either unary or binary
2830 if (NumArgs == 1)
2831 goto UnaryStar;
2832 else
2833 goto BinaryStar;
2834 break;
2835
2836 case OO_Plus: // '+' is either unary or binary
2837 if (NumArgs == 1)
2838 goto UnaryPlus;
2839 else
2840 goto BinaryPlus;
2841 break;
2842
2843 case OO_Minus: // '-' is either unary or binary
2844 if (NumArgs == 1)
2845 goto UnaryMinus;
2846 else
2847 goto BinaryMinus;
2848 break;
2849
2850 case OO_Amp: // '&' is either unary or binary
2851 if (NumArgs == 1)
2852 goto UnaryAmp;
2853 else
2854 goto BinaryAmp;
2855
2856 case OO_PlusPlus:
2857 case OO_MinusMinus:
2858 // C++ [over.built]p3:
2859 //
2860 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2861 // is either volatile or empty, there exist candidate operator
2862 // functions of the form
2863 //
2864 // VQ T& operator++(VQ T&);
2865 // T operator++(VQ T&, int);
2866 //
2867 // C++ [over.built]p4:
2868 //
2869 // For every pair (T, VQ), where T is an arithmetic type other
2870 // than bool, and VQ is either volatile or empty, there exist
2871 // candidate operator functions of the form
2872 //
2873 // VQ T& operator--(VQ T&);
2874 // T operator--(VQ T&, int);
2875 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2876 Arith < NumArithmeticTypes; ++Arith) {
2877 QualType ArithTy = ArithmeticTypes[Arith];
2878 QualType ParamTypes[2]
2879 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
2880
2881 // Non-volatile version.
2882 if (NumArgs == 1)
2883 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2884 else
2885 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2886
2887 // Volatile version
2888 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
2889 if (NumArgs == 1)
2890 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2891 else
2892 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2893 }
2894
2895 // C++ [over.built]p5:
2896 //
2897 // For every pair (T, VQ), where T is a cv-qualified or
2898 // cv-unqualified object type, and VQ is either volatile or
2899 // empty, there exist candidate operator functions of the form
2900 //
2901 // T*VQ& operator++(T*VQ&);
2902 // T*VQ& operator--(T*VQ&);
2903 // T* operator++(T*VQ&, int);
2904 // T* operator--(T*VQ&, int);
2905 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2906 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2907 // Skip pointer types that aren't pointers to object types.
2908 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
2909 continue;
2910
2911 QualType ParamTypes[2] = {
2912 Context.getLValueReferenceType(*Ptr), Context.IntTy
2913 };
2914
2915 // Without volatile
2916 if (NumArgs == 1)
2917 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2918 else
2919 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2920
2921 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2922 // With volatile
2923 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
2924 if (NumArgs == 1)
2925 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2926 else
2927 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2928 }
2929 }
2930 break;
2931
2932 UnaryStar:
2933 // C++ [over.built]p6:
2934 // For every cv-qualified or cv-unqualified object type T, there
2935 // exist candidate operator functions of the form
2936 //
2937 // T& operator*(T*);
2938 //
2939 // C++ [over.built]p7:
2940 // For every function type T, there exist candidate operator
2941 // functions of the form
2942 // T& operator*(T*);
2943 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2944 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2945 QualType ParamTy = *Ptr;
2946 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2947 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
2948 &ParamTy, Args, 1, CandidateSet);
2949 }
2950 break;
2951
2952 UnaryPlus:
2953 // C++ [over.built]p8:
2954 // For every type T, there exist candidate operator functions of
2955 // the form
2956 //
2957 // T* operator+(T*);
2958 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2959 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2960 QualType ParamTy = *Ptr;
2961 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2962 }
2963
2964 // Fall through
2965
2966 UnaryMinus:
2967 // C++ [over.built]p9:
2968 // For every promoted arithmetic type T, there exist candidate
2969 // operator functions of the form
2970 //
2971 // T operator+(T);
2972 // T operator-(T);
2973 for (unsigned Arith = FirstPromotedArithmeticType;
2974 Arith < LastPromotedArithmeticType; ++Arith) {
2975 QualType ArithTy = ArithmeticTypes[Arith];
2976 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2977 }
2978 break;
2979
2980 case OO_Tilde:
2981 // C++ [over.built]p10:
2982 // For every promoted integral type T, there exist candidate
2983 // operator functions of the form
2984 //
2985 // T operator~(T);
2986 for (unsigned Int = FirstPromotedIntegralType;
2987 Int < LastPromotedIntegralType; ++Int) {
2988 QualType IntTy = ArithmeticTypes[Int];
2989 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2990 }
2991 break;
2992
2993 case OO_New:
2994 case OO_Delete:
2995 case OO_Array_New:
2996 case OO_Array_Delete:
2997 case OO_Call:
2998 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
2999 break;
3000
3001 case OO_Comma:
3002 UnaryAmp:
3003 case OO_Arrow:
3004 // C++ [over.match.oper]p3:
3005 // -- For the operator ',', the unary operator '&', or the
3006 // operator '->', the built-in candidates set is empty.
3007 break;
3008
3009 case OO_Less:
3010 case OO_Greater:
3011 case OO_LessEqual:
3012 case OO_GreaterEqual:
3013 case OO_EqualEqual:
3014 case OO_ExclaimEqual:
3015 // C++ [over.built]p15:
3016 //
3017 // For every pointer or enumeration type T, there exist
3018 // candidate operator functions of the form
3019 //
3020 // bool operator<(T, T);
3021 // bool operator>(T, T);
3022 // bool operator<=(T, T);
3023 // bool operator>=(T, T);
3024 // bool operator==(T, T);
3025 // bool operator!=(T, T);
3026 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3027 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3028 QualType ParamTypes[2] = { *Ptr, *Ptr };
3029 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3030 }
3031 for (BuiltinCandidateTypeSet::iterator Enum
3032 = CandidateTypes.enumeration_begin();
3033 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3034 QualType ParamTypes[2] = { *Enum, *Enum };
3035 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3036 }
3037
3038 // Fall through.
3039 isComparison = true;
3040
3041 BinaryPlus:
3042 BinaryMinus:
3043 if (!isComparison) {
3044 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3045
3046 // C++ [over.built]p13:
3047 //
3048 // For every cv-qualified or cv-unqualified object type T
3049 // there exist candidate operator functions of the form
3050 //
3051 // T* operator+(T*, ptrdiff_t);
3052 // T& operator[](T*, ptrdiff_t); [BELOW]
3053 // T* operator-(T*, ptrdiff_t);
3054 // T* operator+(ptrdiff_t, T*);
3055 // T& operator[](ptrdiff_t, T*); [BELOW]
3056 //
3057 // C++ [over.built]p14:
3058 //
3059 // For every T, where T is a pointer to object type, there
3060 // exist candidate operator functions of the form
3061 //
3062 // ptrdiff_t operator-(T, T);
3063 for (BuiltinCandidateTypeSet::iterator Ptr
3064 = CandidateTypes.pointer_begin();
3065 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3066 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3067
3068 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3069 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3070
3071 if (Op == OO_Plus) {
3072 // T* operator+(ptrdiff_t, T*);
3073 ParamTypes[0] = ParamTypes[1];
3074 ParamTypes[1] = *Ptr;
3075 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3076 } else {
3077 // ptrdiff_t operator-(T, T);
3078 ParamTypes[1] = *Ptr;
3079 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3080 Args, 2, CandidateSet);
3081 }
3082 }
3083 }
3084 // Fall through
3085
3086 case OO_Slash:
3087 BinaryStar:
3088 Conditional:
3089 // C++ [over.built]p12:
3090 //
3091 // For every pair of promoted arithmetic types L and R, there
3092 // exist candidate operator functions of the form
3093 //
3094 // LR operator*(L, R);
3095 // LR operator/(L, R);
3096 // LR operator+(L, R);
3097 // LR operator-(L, R);
3098 // bool operator<(L, R);
3099 // bool operator>(L, R);
3100 // bool operator<=(L, R);
3101 // bool operator>=(L, R);
3102 // bool operator==(L, R);
3103 // bool operator!=(L, R);
3104 //
3105 // where LR is the result of the usual arithmetic conversions
3106 // between types L and R.
3107 //
3108 // C++ [over.built]p24:
3109 //
3110 // For every pair of promoted arithmetic types L and R, there exist
3111 // candidate operator functions of the form
3112 //
3113 // LR operator?(bool, L, R);
3114 //
3115 // where LR is the result of the usual arithmetic conversions
3116 // between types L and R.
3117 // Our candidates ignore the first parameter.
3118 for (unsigned Left = FirstPromotedArithmeticType;
3119 Left < LastPromotedArithmeticType; ++Left) {
3120 for (unsigned Right = FirstPromotedArithmeticType;
3121 Right < LastPromotedArithmeticType; ++Right) {
3122 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3123 QualType Result
3124 = isComparison? Context.BoolTy
3125 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3126 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3127 }
3128 }
3129 break;
3130
3131 case OO_Percent:
3132 BinaryAmp:
3133 case OO_Caret:
3134 case OO_Pipe:
3135 case OO_LessLess:
3136 case OO_GreaterGreater:
3137 // C++ [over.built]p17:
3138 //
3139 // For every pair of promoted integral types L and R, there
3140 // exist candidate operator functions of the form
3141 //
3142 // LR operator%(L, R);
3143 // LR operator&(L, R);
3144 // LR operator^(L, R);
3145 // LR operator|(L, R);
3146 // L operator<<(L, R);
3147 // L operator>>(L, R);
3148 //
3149 // where LR is the result of the usual arithmetic conversions
3150 // between types L and R.
3151 for (unsigned Left = FirstPromotedIntegralType;
3152 Left < LastPromotedIntegralType; ++Left) {
3153 for (unsigned Right = FirstPromotedIntegralType;
3154 Right < LastPromotedIntegralType; ++Right) {
3155 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3156 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3157 ? LandR[0]
3158 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3159 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3160 }
3161 }
3162 break;
3163
3164 case OO_Equal:
3165 // C++ [over.built]p20:
3166 //
3167 // For every pair (T, VQ), where T is an enumeration or
3168 // (FIXME:) pointer to member type and VQ is either volatile or
3169 // empty, there exist candidate operator functions of the form
3170 //
3171 // VQ T& operator=(VQ T&, T);
3172 for (BuiltinCandidateTypeSet::iterator Enum
3173 = CandidateTypes.enumeration_begin();
3174 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3175 QualType ParamTypes[2];
3176
3177 // T& operator=(T&, T)
3178 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
3179 ParamTypes[1] = *Enum;
3180 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3181 /*IsAssignmentOperator=*/false);
3182
3183 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3184 // volatile T& operator=(volatile T&, T)
3185 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
3186 ParamTypes[1] = *Enum;
3187 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3188 /*IsAssignmentOperator=*/false);
3189 }
3190 }
3191 // Fall through.
3192
3193 case OO_PlusEqual:
3194 case OO_MinusEqual:
3195 // C++ [over.built]p19:
3196 //
3197 // For every pair (T, VQ), where T is any type and VQ is either
3198 // volatile or empty, there exist candidate operator functions
3199 // of the form
3200 //
3201 // T*VQ& operator=(T*VQ&, T*);
3202 //
3203 // C++ [over.built]p21:
3204 //
3205 // For every pair (T, VQ), where T is a cv-qualified or
3206 // cv-unqualified object type and VQ is either volatile or
3207 // empty, there exist candidate operator functions of the form
3208 //
3209 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3210 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3211 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3212 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3213 QualType ParamTypes[2];
3214 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3215
3216 // non-volatile version
3217 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
3218 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3219 /*IsAssigmentOperator=*/Op == OO_Equal);
3220
3221 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3222 // volatile version
3223 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
3224 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3225 /*IsAssigmentOperator=*/Op == OO_Equal);
3226 }
3227 }
3228 // Fall through.
3229
3230 case OO_StarEqual:
3231 case OO_SlashEqual:
3232 // C++ [over.built]p18:
3233 //
3234 // For every triple (L, VQ, R), where L is an arithmetic type,
3235 // VQ is either volatile or empty, and R is a promoted
3236 // arithmetic type, there exist candidate operator functions of
3237 // the form
3238 //
3239 // VQ L& operator=(VQ L&, R);
3240 // VQ L& operator*=(VQ L&, R);
3241 // VQ L& operator/=(VQ L&, R);
3242 // VQ L& operator+=(VQ L&, R);
3243 // VQ L& operator-=(VQ L&, R);
3244 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3245 for (unsigned Right = FirstPromotedArithmeticType;
3246 Right < LastPromotedArithmeticType; ++Right) {
3247 QualType ParamTypes[2];
3248 ParamTypes[1] = ArithmeticTypes[Right];
3249
3250 // Add this built-in operator as a candidate (VQ is empty).
3251 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3252 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3253 /*IsAssigmentOperator=*/Op == OO_Equal);
3254
3255 // Add this built-in operator as a candidate (VQ is 'volatile').
3256 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
3257 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3258 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3259 /*IsAssigmentOperator=*/Op == OO_Equal);
3260 }
3261 }
3262 break;
3263
3264 case OO_PercentEqual:
3265 case OO_LessLessEqual:
3266 case OO_GreaterGreaterEqual:
3267 case OO_AmpEqual:
3268 case OO_CaretEqual:
3269 case OO_PipeEqual:
3270 // C++ [over.built]p22:
3271 //
3272 // For every triple (L, VQ, R), where L is an integral type, VQ
3273 // is either volatile or empty, and R is a promoted integral
3274 // type, there exist candidate operator functions of the form
3275 //
3276 // VQ L& operator%=(VQ L&, R);
3277 // VQ L& operator<<=(VQ L&, R);
3278 // VQ L& operator>>=(VQ L&, R);
3279 // VQ L& operator&=(VQ L&, R);
3280 // VQ L& operator^=(VQ L&, R);
3281 // VQ L& operator|=(VQ L&, R);
3282 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3283 for (unsigned Right = FirstPromotedIntegralType;
3284 Right < LastPromotedIntegralType; ++Right) {
3285 QualType ParamTypes[2];
3286 ParamTypes[1] = ArithmeticTypes[Right];
3287
3288 // Add this built-in operator as a candidate (VQ is empty).
3289 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3290 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3291
3292 // Add this built-in operator as a candidate (VQ is 'volatile').
3293 ParamTypes[0] = ArithmeticTypes[Left];
3294 ParamTypes[0].addVolatile();
3295 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3296 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3297 }
3298 }
3299 break;
3300
3301 case OO_Exclaim: {
3302 // C++ [over.operator]p23:
3303 //
3304 // There also exist candidate operator functions of the form
3305 //
3306 // bool operator!(bool);
3307 // bool operator&&(bool, bool); [BELOW]
3308 // bool operator||(bool, bool); [BELOW]
3309 QualType ParamTy = Context.BoolTy;
3310 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3311 /*IsAssignmentOperator=*/false,
3312 /*NumContextualBoolArguments=*/1);
3313 break;
3314 }
3315
3316 case OO_AmpAmp:
3317 case OO_PipePipe: {
3318 // C++ [over.operator]p23:
3319 //
3320 // There also exist candidate operator functions of the form
3321 //
3322 // bool operator!(bool); [ABOVE]
3323 // bool operator&&(bool, bool);
3324 // bool operator||(bool, bool);
3325 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
3326 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3327 /*IsAssignmentOperator=*/false,
3328 /*NumContextualBoolArguments=*/2);
3329 break;
3330 }
3331
3332 case OO_Subscript:
3333 // C++ [over.built]p13:
3334 //
3335 // For every cv-qualified or cv-unqualified object type T there
3336 // exist candidate operator functions of the form
3337 //
3338 // T* operator+(T*, ptrdiff_t); [ABOVE]
3339 // T& operator[](T*, ptrdiff_t);
3340 // T* operator-(T*, ptrdiff_t); [ABOVE]
3341 // T* operator+(ptrdiff_t, T*); [ABOVE]
3342 // T& operator[](ptrdiff_t, T*);
3343 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3344 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3345 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3346 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
3347 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
3348
3349 // T& operator[](T*, ptrdiff_t)
3350 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3351
3352 // T& operator[](ptrdiff_t, T*);
3353 ParamTypes[0] = ParamTypes[1];
3354 ParamTypes[1] = *Ptr;
3355 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3356 }
3357 break;
3358
3359 case OO_ArrowStar:
3360 // FIXME: No support for pointer-to-members yet.
3361 break;
3362
3363 case OO_Conditional:
3364 // Note that we don't consider the first argument, since it has been
3365 // contextually converted to bool long ago. The candidates below are
3366 // therefore added as binary.
3367 //
3368 // C++ [over.built]p24:
3369 // For every type T, where T is a pointer or pointer-to-member type,
3370 // there exist candidate operator functions of the form
3371 //
3372 // T operator?(bool, T, T);
3373 //
3374 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3375 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3376 QualType ParamTypes[2] = { *Ptr, *Ptr };
3377 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3378 }
3379 for (BuiltinCandidateTypeSet::iterator Ptr =
3380 CandidateTypes.member_pointer_begin(),
3381 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3382 QualType ParamTypes[2] = { *Ptr, *Ptr };
3383 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3384 }
3385 goto Conditional;
3386 }
3387}
3388
3389/// \brief Add function candidates found via argument-dependent lookup
3390/// to the set of overloading candidates.
3391///
3392/// This routine performs argument-dependent name lookup based on the
3393/// given function name (which may also be an operator name) and adds
3394/// all of the overload candidates found by ADL to the overload
3395/// candidate set (C++ [basic.lookup.argdep]).
3396void
3397Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3398 Expr **Args, unsigned NumArgs,
3399 OverloadCandidateSet& CandidateSet) {
3400 FunctionSet Functions;
3401
3402 // Record all of the function candidates that we've already
3403 // added to the overload set, so that we don't add those same
3404 // candidates a second time.
3405 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3406 CandEnd = CandidateSet.end();
3407 Cand != CandEnd; ++Cand)
2525 Oper != OperEnd; ++Oper)
2526 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2527 Args+1, NumArgs - 1, CandidateSet,
2528 /*SuppressUserConversions=*/false);
2529 }
2530}
2531
2532/// AddBuiltinCandidate - Add a candidate for a built-in
2533/// operator. ResultTy and ParamTys are the result and parameter types
2534/// of the built-in candidate, respectively. Args and NumArgs are the
2535/// arguments being passed to the candidate. IsAssignmentOperator
2536/// should be true when this built-in candidate is an assignment
2537/// operator. NumContextualBoolArguments is the number of arguments
2538/// (at the beginning of the argument list) that will be contextually
2539/// converted to bool.
2540void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2541 Expr **Args, unsigned NumArgs,
2542 OverloadCandidateSet& CandidateSet,
2543 bool IsAssignmentOperator,
2544 unsigned NumContextualBoolArguments) {
2545 // Add this candidate
2546 CandidateSet.push_back(OverloadCandidate());
2547 OverloadCandidate& Candidate = CandidateSet.back();
2548 Candidate.Function = 0;
2549 Candidate.IsSurrogate = false;
2550 Candidate.IgnoreObjectArgument = false;
2551 Candidate.BuiltinTypes.ResultTy = ResultTy;
2552 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2553 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2554
2555 // Determine the implicit conversion sequences for each of the
2556 // arguments.
2557 Candidate.Viable = true;
2558 Candidate.Conversions.resize(NumArgs);
2559 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2560 // C++ [over.match.oper]p4:
2561 // For the built-in assignment operators, conversions of the
2562 // left operand are restricted as follows:
2563 // -- no temporaries are introduced to hold the left operand, and
2564 // -- no user-defined conversions are applied to the left
2565 // operand to achieve a type match with the left-most
2566 // parameter of a built-in candidate.
2567 //
2568 // We block these conversions by turning off user-defined
2569 // conversions, since that is the only way that initialization of
2570 // a reference to a non-class type can occur from something that
2571 // is not of the same type.
2572 if (ArgIdx < NumContextualBoolArguments) {
2573 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2574 "Contextual conversion to bool requires bool type");
2575 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2576 } else {
2577 Candidate.Conversions[ArgIdx]
2578 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2579 ArgIdx == 0 && IsAssignmentOperator);
2580 }
2581 if (Candidate.Conversions[ArgIdx].ConversionKind
2582 == ImplicitConversionSequence::BadConversion) {
2583 Candidate.Viable = false;
2584 break;
2585 }
2586 }
2587}
2588
2589/// BuiltinCandidateTypeSet - A set of types that will be used for the
2590/// candidate operator functions for built-in operators (C++
2591/// [over.built]). The types are separated into pointer types and
2592/// enumeration types.
2593class BuiltinCandidateTypeSet {
2594 /// TypeSet - A set of types.
2595 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
2596
2597 /// PointerTypes - The set of pointer types that will be used in the
2598 /// built-in candidates.
2599 TypeSet PointerTypes;
2600
2601 /// MemberPointerTypes - The set of member pointer types that will be
2602 /// used in the built-in candidates.
2603 TypeSet MemberPointerTypes;
2604
2605 /// EnumerationTypes - The set of enumeration types that will be
2606 /// used in the built-in candidates.
2607 TypeSet EnumerationTypes;
2608
2609 /// Context - The AST context in which we will build the type sets.
2610 ASTContext &Context;
2611
2612 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2613 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
2614
2615public:
2616 /// iterator - Iterates through the types that are part of the set.
2617 typedef TypeSet::iterator iterator;
2618
2619 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2620
2621 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2622 bool AllowExplicitConversions);
2623
2624 /// pointer_begin - First pointer type found;
2625 iterator pointer_begin() { return PointerTypes.begin(); }
2626
2627 /// pointer_end - Past the last pointer type found;
2628 iterator pointer_end() { return PointerTypes.end(); }
2629
2630 /// member_pointer_begin - First member pointer type found;
2631 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2632
2633 /// member_pointer_end - Past the last member pointer type found;
2634 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2635
2636 /// enumeration_begin - First enumeration type found;
2637 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2638
2639 /// enumeration_end - Past the last enumeration type found;
2640 iterator enumeration_end() { return EnumerationTypes.end(); }
2641};
2642
2643/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2644/// the set of pointer types along with any more-qualified variants of
2645/// that type. For example, if @p Ty is "int const *", this routine
2646/// will add "int const *", "int const volatile *", "int const
2647/// restrict *", and "int const volatile restrict *" to the set of
2648/// pointer types. Returns true if the add of @p Ty itself succeeded,
2649/// false otherwise.
2650bool
2651BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
2652 // Insert this type.
2653 if (!PointerTypes.insert(Ty))
2654 return false;
2655
2656 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2657 QualType PointeeTy = PointerTy->getPointeeType();
2658 // FIXME: Optimize this so that we don't keep trying to add the same types.
2659
2660 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2661 // pointer conversions that don't cast away constness?
2662 if (!PointeeTy.isConstQualified())
2663 AddPointerWithMoreQualifiedTypeVariants
2664 (Context.getPointerType(PointeeTy.withConst()));
2665 if (!PointeeTy.isVolatileQualified())
2666 AddPointerWithMoreQualifiedTypeVariants
2667 (Context.getPointerType(PointeeTy.withVolatile()));
2668 if (!PointeeTy.isRestrictQualified())
2669 AddPointerWithMoreQualifiedTypeVariants
2670 (Context.getPointerType(PointeeTy.withRestrict()));
2671 }
2672
2673 return true;
2674}
2675
2676/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2677/// to the set of pointer types along with any more-qualified variants of
2678/// that type. For example, if @p Ty is "int const *", this routine
2679/// will add "int const *", "int const volatile *", "int const
2680/// restrict *", and "int const volatile restrict *" to the set of
2681/// pointer types. Returns true if the add of @p Ty itself succeeded,
2682/// false otherwise.
2683bool
2684BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2685 QualType Ty) {
2686 // Insert this type.
2687 if (!MemberPointerTypes.insert(Ty))
2688 return false;
2689
2690 if (const MemberPointerType *PointerTy = Ty->getAsMemberPointerType()) {
2691 QualType PointeeTy = PointerTy->getPointeeType();
2692 const Type *ClassTy = PointerTy->getClass();
2693 // FIXME: Optimize this so that we don't keep trying to add the same types.
2694
2695 if (!PointeeTy.isConstQualified())
2696 AddMemberPointerWithMoreQualifiedTypeVariants
2697 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2698 if (!PointeeTy.isVolatileQualified())
2699 AddMemberPointerWithMoreQualifiedTypeVariants
2700 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2701 if (!PointeeTy.isRestrictQualified())
2702 AddMemberPointerWithMoreQualifiedTypeVariants
2703 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2704 }
2705
2706 return true;
2707}
2708
2709/// AddTypesConvertedFrom - Add each of the types to which the type @p
2710/// Ty can be implicit converted to the given set of @p Types. We're
2711/// primarily interested in pointer types and enumeration types. We also
2712/// take member pointer types, for the conditional operator.
2713/// AllowUserConversions is true if we should look at the conversion
2714/// functions of a class type, and AllowExplicitConversions if we
2715/// should also include the explicit conversion functions of a class
2716/// type.
2717void
2718BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2719 bool AllowUserConversions,
2720 bool AllowExplicitConversions) {
2721 // Only deal with canonical types.
2722 Ty = Context.getCanonicalType(Ty);
2723
2724 // Look through reference types; they aren't part of the type of an
2725 // expression for the purposes of conversions.
2726 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2727 Ty = RefTy->getPointeeType();
2728
2729 // We don't care about qualifiers on the type.
2730 Ty = Ty.getUnqualifiedType();
2731
2732 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2733 QualType PointeeTy = PointerTy->getPointeeType();
2734
2735 // Insert our type, and its more-qualified variants, into the set
2736 // of types.
2737 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
2738 return;
2739
2740 // Add 'cv void*' to our set of types.
2741 if (!Ty->isVoidType()) {
2742 QualType QualVoid
2743 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2744 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2745 }
2746
2747 // If this is a pointer to a class type, add pointers to its bases
2748 // (with the same level of cv-qualification as the original
2749 // derived class, of course).
2750 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2751 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2752 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2753 Base != ClassDecl->bases_end(); ++Base) {
2754 QualType BaseTy = Context.getCanonicalType(Base->getType());
2755 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2756
2757 // Add the pointer type, recursively, so that we get all of
2758 // the indirect base classes, too.
2759 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
2760 }
2761 }
2762 } else if (Ty->isMemberPointerType()) {
2763 // Member pointers are far easier, since the pointee can't be converted.
2764 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2765 return;
2766 } else if (Ty->isEnumeralType()) {
2767 EnumerationTypes.insert(Ty);
2768 } else if (AllowUserConversions) {
2769 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2770 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2771 // FIXME: Visit conversion functions in the base classes, too.
2772 OverloadedFunctionDecl *Conversions
2773 = ClassDecl->getConversionFunctions();
2774 for (OverloadedFunctionDecl::function_iterator Func
2775 = Conversions->function_begin();
2776 Func != Conversions->function_end(); ++Func) {
2777 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2778 if (AllowExplicitConversions || !Conv->isExplicit())
2779 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
2780 }
2781 }
2782 }
2783}
2784
2785/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2786/// operator overloads to the candidate set (C++ [over.built]), based
2787/// on the operator @p Op and the arguments given. For example, if the
2788/// operator is a binary '+', this routine might add "int
2789/// operator+(int, int)" to cover integer addition.
2790void
2791Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2792 Expr **Args, unsigned NumArgs,
2793 OverloadCandidateSet& CandidateSet) {
2794 // The set of "promoted arithmetic types", which are the arithmetic
2795 // types are that preserved by promotion (C++ [over.built]p2). Note
2796 // that the first few of these types are the promoted integral
2797 // types; these types need to be first.
2798 // FIXME: What about complex?
2799 const unsigned FirstIntegralType = 0;
2800 const unsigned LastIntegralType = 13;
2801 const unsigned FirstPromotedIntegralType = 7,
2802 LastPromotedIntegralType = 13;
2803 const unsigned FirstPromotedArithmeticType = 7,
2804 LastPromotedArithmeticType = 16;
2805 const unsigned NumArithmeticTypes = 16;
2806 QualType ArithmeticTypes[NumArithmeticTypes] = {
2807 Context.BoolTy, Context.CharTy, Context.WCharTy,
2808 Context.SignedCharTy, Context.ShortTy,
2809 Context.UnsignedCharTy, Context.UnsignedShortTy,
2810 Context.IntTy, Context.LongTy, Context.LongLongTy,
2811 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2812 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2813 };
2814
2815 // Find all of the types that the arguments can convert to, but only
2816 // if the operator we're looking at has built-in operator candidates
2817 // that make use of these types.
2818 BuiltinCandidateTypeSet CandidateTypes(Context);
2819 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2820 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
2821 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
2822 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
2823 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2824 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
2825 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2826 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2827 true,
2828 (Op == OO_Exclaim ||
2829 Op == OO_AmpAmp ||
2830 Op == OO_PipePipe));
2831 }
2832
2833 bool isComparison = false;
2834 switch (Op) {
2835 case OO_None:
2836 case NUM_OVERLOADED_OPERATORS:
2837 assert(false && "Expected an overloaded operator");
2838 break;
2839
2840 case OO_Star: // '*' is either unary or binary
2841 if (NumArgs == 1)
2842 goto UnaryStar;
2843 else
2844 goto BinaryStar;
2845 break;
2846
2847 case OO_Plus: // '+' is either unary or binary
2848 if (NumArgs == 1)
2849 goto UnaryPlus;
2850 else
2851 goto BinaryPlus;
2852 break;
2853
2854 case OO_Minus: // '-' is either unary or binary
2855 if (NumArgs == 1)
2856 goto UnaryMinus;
2857 else
2858 goto BinaryMinus;
2859 break;
2860
2861 case OO_Amp: // '&' is either unary or binary
2862 if (NumArgs == 1)
2863 goto UnaryAmp;
2864 else
2865 goto BinaryAmp;
2866
2867 case OO_PlusPlus:
2868 case OO_MinusMinus:
2869 // C++ [over.built]p3:
2870 //
2871 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2872 // is either volatile or empty, there exist candidate operator
2873 // functions of the form
2874 //
2875 // VQ T& operator++(VQ T&);
2876 // T operator++(VQ T&, int);
2877 //
2878 // C++ [over.built]p4:
2879 //
2880 // For every pair (T, VQ), where T is an arithmetic type other
2881 // than bool, and VQ is either volatile or empty, there exist
2882 // candidate operator functions of the form
2883 //
2884 // VQ T& operator--(VQ T&);
2885 // T operator--(VQ T&, int);
2886 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2887 Arith < NumArithmeticTypes; ++Arith) {
2888 QualType ArithTy = ArithmeticTypes[Arith];
2889 QualType ParamTypes[2]
2890 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
2891
2892 // Non-volatile version.
2893 if (NumArgs == 1)
2894 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2895 else
2896 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2897
2898 // Volatile version
2899 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
2900 if (NumArgs == 1)
2901 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2902 else
2903 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2904 }
2905
2906 // C++ [over.built]p5:
2907 //
2908 // For every pair (T, VQ), where T is a cv-qualified or
2909 // cv-unqualified object type, and VQ is either volatile or
2910 // empty, there exist candidate operator functions of the form
2911 //
2912 // T*VQ& operator++(T*VQ&);
2913 // T*VQ& operator--(T*VQ&);
2914 // T* operator++(T*VQ&, int);
2915 // T* operator--(T*VQ&, int);
2916 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2917 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2918 // Skip pointer types that aren't pointers to object types.
2919 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
2920 continue;
2921
2922 QualType ParamTypes[2] = {
2923 Context.getLValueReferenceType(*Ptr), Context.IntTy
2924 };
2925
2926 // Without volatile
2927 if (NumArgs == 1)
2928 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2929 else
2930 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2931
2932 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2933 // With volatile
2934 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
2935 if (NumArgs == 1)
2936 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2937 else
2938 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2939 }
2940 }
2941 break;
2942
2943 UnaryStar:
2944 // C++ [over.built]p6:
2945 // For every cv-qualified or cv-unqualified object type T, there
2946 // exist candidate operator functions of the form
2947 //
2948 // T& operator*(T*);
2949 //
2950 // C++ [over.built]p7:
2951 // For every function type T, there exist candidate operator
2952 // functions of the form
2953 // T& operator*(T*);
2954 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2955 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2956 QualType ParamTy = *Ptr;
2957 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2958 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
2959 &ParamTy, Args, 1, CandidateSet);
2960 }
2961 break;
2962
2963 UnaryPlus:
2964 // C++ [over.built]p8:
2965 // For every type T, there exist candidate operator functions of
2966 // the form
2967 //
2968 // T* operator+(T*);
2969 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2970 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2971 QualType ParamTy = *Ptr;
2972 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2973 }
2974
2975 // Fall through
2976
2977 UnaryMinus:
2978 // C++ [over.built]p9:
2979 // For every promoted arithmetic type T, there exist candidate
2980 // operator functions of the form
2981 //
2982 // T operator+(T);
2983 // T operator-(T);
2984 for (unsigned Arith = FirstPromotedArithmeticType;
2985 Arith < LastPromotedArithmeticType; ++Arith) {
2986 QualType ArithTy = ArithmeticTypes[Arith];
2987 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2988 }
2989 break;
2990
2991 case OO_Tilde:
2992 // C++ [over.built]p10:
2993 // For every promoted integral type T, there exist candidate
2994 // operator functions of the form
2995 //
2996 // T operator~(T);
2997 for (unsigned Int = FirstPromotedIntegralType;
2998 Int < LastPromotedIntegralType; ++Int) {
2999 QualType IntTy = ArithmeticTypes[Int];
3000 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3001 }
3002 break;
3003
3004 case OO_New:
3005 case OO_Delete:
3006 case OO_Array_New:
3007 case OO_Array_Delete:
3008 case OO_Call:
3009 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
3010 break;
3011
3012 case OO_Comma:
3013 UnaryAmp:
3014 case OO_Arrow:
3015 // C++ [over.match.oper]p3:
3016 // -- For the operator ',', the unary operator '&', or the
3017 // operator '->', the built-in candidates set is empty.
3018 break;
3019
3020 case OO_Less:
3021 case OO_Greater:
3022 case OO_LessEqual:
3023 case OO_GreaterEqual:
3024 case OO_EqualEqual:
3025 case OO_ExclaimEqual:
3026 // C++ [over.built]p15:
3027 //
3028 // For every pointer or enumeration type T, there exist
3029 // candidate operator functions of the form
3030 //
3031 // bool operator<(T, T);
3032 // bool operator>(T, T);
3033 // bool operator<=(T, T);
3034 // bool operator>=(T, T);
3035 // bool operator==(T, T);
3036 // bool operator!=(T, T);
3037 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3038 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3039 QualType ParamTypes[2] = { *Ptr, *Ptr };
3040 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3041 }
3042 for (BuiltinCandidateTypeSet::iterator Enum
3043 = CandidateTypes.enumeration_begin();
3044 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3045 QualType ParamTypes[2] = { *Enum, *Enum };
3046 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3047 }
3048
3049 // Fall through.
3050 isComparison = true;
3051
3052 BinaryPlus:
3053 BinaryMinus:
3054 if (!isComparison) {
3055 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3056
3057 // C++ [over.built]p13:
3058 //
3059 // For every cv-qualified or cv-unqualified object type T
3060 // there exist candidate operator functions of the form
3061 //
3062 // T* operator+(T*, ptrdiff_t);
3063 // T& operator[](T*, ptrdiff_t); [BELOW]
3064 // T* operator-(T*, ptrdiff_t);
3065 // T* operator+(ptrdiff_t, T*);
3066 // T& operator[](ptrdiff_t, T*); [BELOW]
3067 //
3068 // C++ [over.built]p14:
3069 //
3070 // For every T, where T is a pointer to object type, there
3071 // exist candidate operator functions of the form
3072 //
3073 // ptrdiff_t operator-(T, T);
3074 for (BuiltinCandidateTypeSet::iterator Ptr
3075 = CandidateTypes.pointer_begin();
3076 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3077 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3078
3079 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3080 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3081
3082 if (Op == OO_Plus) {
3083 // T* operator+(ptrdiff_t, T*);
3084 ParamTypes[0] = ParamTypes[1];
3085 ParamTypes[1] = *Ptr;
3086 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3087 } else {
3088 // ptrdiff_t operator-(T, T);
3089 ParamTypes[1] = *Ptr;
3090 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3091 Args, 2, CandidateSet);
3092 }
3093 }
3094 }
3095 // Fall through
3096
3097 case OO_Slash:
3098 BinaryStar:
3099 Conditional:
3100 // C++ [over.built]p12:
3101 //
3102 // For every pair of promoted arithmetic types L and R, there
3103 // exist candidate operator functions of the form
3104 //
3105 // LR operator*(L, R);
3106 // LR operator/(L, R);
3107 // LR operator+(L, R);
3108 // LR operator-(L, R);
3109 // bool operator<(L, R);
3110 // bool operator>(L, R);
3111 // bool operator<=(L, R);
3112 // bool operator>=(L, R);
3113 // bool operator==(L, R);
3114 // bool operator!=(L, R);
3115 //
3116 // where LR is the result of the usual arithmetic conversions
3117 // between types L and R.
3118 //
3119 // C++ [over.built]p24:
3120 //
3121 // For every pair of promoted arithmetic types L and R, there exist
3122 // candidate operator functions of the form
3123 //
3124 // LR operator?(bool, L, R);
3125 //
3126 // where LR is the result of the usual arithmetic conversions
3127 // between types L and R.
3128 // Our candidates ignore the first parameter.
3129 for (unsigned Left = FirstPromotedArithmeticType;
3130 Left < LastPromotedArithmeticType; ++Left) {
3131 for (unsigned Right = FirstPromotedArithmeticType;
3132 Right < LastPromotedArithmeticType; ++Right) {
3133 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3134 QualType Result
3135 = isComparison? Context.BoolTy
3136 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3137 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3138 }
3139 }
3140 break;
3141
3142 case OO_Percent:
3143 BinaryAmp:
3144 case OO_Caret:
3145 case OO_Pipe:
3146 case OO_LessLess:
3147 case OO_GreaterGreater:
3148 // C++ [over.built]p17:
3149 //
3150 // For every pair of promoted integral types L and R, there
3151 // exist candidate operator functions of the form
3152 //
3153 // LR operator%(L, R);
3154 // LR operator&(L, R);
3155 // LR operator^(L, R);
3156 // LR operator|(L, R);
3157 // L operator<<(L, R);
3158 // L operator>>(L, R);
3159 //
3160 // where LR is the result of the usual arithmetic conversions
3161 // between types L and R.
3162 for (unsigned Left = FirstPromotedIntegralType;
3163 Left < LastPromotedIntegralType; ++Left) {
3164 for (unsigned Right = FirstPromotedIntegralType;
3165 Right < LastPromotedIntegralType; ++Right) {
3166 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3167 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3168 ? LandR[0]
3169 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3170 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3171 }
3172 }
3173 break;
3174
3175 case OO_Equal:
3176 // C++ [over.built]p20:
3177 //
3178 // For every pair (T, VQ), where T is an enumeration or
3179 // (FIXME:) pointer to member type and VQ is either volatile or
3180 // empty, there exist candidate operator functions of the form
3181 //
3182 // VQ T& operator=(VQ T&, T);
3183 for (BuiltinCandidateTypeSet::iterator Enum
3184 = CandidateTypes.enumeration_begin();
3185 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3186 QualType ParamTypes[2];
3187
3188 // T& operator=(T&, T)
3189 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
3190 ParamTypes[1] = *Enum;
3191 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3192 /*IsAssignmentOperator=*/false);
3193
3194 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3195 // volatile T& operator=(volatile T&, T)
3196 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
3197 ParamTypes[1] = *Enum;
3198 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3199 /*IsAssignmentOperator=*/false);
3200 }
3201 }
3202 // Fall through.
3203
3204 case OO_PlusEqual:
3205 case OO_MinusEqual:
3206 // C++ [over.built]p19:
3207 //
3208 // For every pair (T, VQ), where T is any type and VQ is either
3209 // volatile or empty, there exist candidate operator functions
3210 // of the form
3211 //
3212 // T*VQ& operator=(T*VQ&, T*);
3213 //
3214 // C++ [over.built]p21:
3215 //
3216 // For every pair (T, VQ), where T is a cv-qualified or
3217 // cv-unqualified object type and VQ is either volatile or
3218 // empty, there exist candidate operator functions of the form
3219 //
3220 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3221 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3222 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3223 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3224 QualType ParamTypes[2];
3225 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3226
3227 // non-volatile version
3228 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
3229 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3230 /*IsAssigmentOperator=*/Op == OO_Equal);
3231
3232 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3233 // volatile version
3234 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
3235 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3236 /*IsAssigmentOperator=*/Op == OO_Equal);
3237 }
3238 }
3239 // Fall through.
3240
3241 case OO_StarEqual:
3242 case OO_SlashEqual:
3243 // C++ [over.built]p18:
3244 //
3245 // For every triple (L, VQ, R), where L is an arithmetic type,
3246 // VQ is either volatile or empty, and R is a promoted
3247 // arithmetic type, there exist candidate operator functions of
3248 // the form
3249 //
3250 // VQ L& operator=(VQ L&, R);
3251 // VQ L& operator*=(VQ L&, R);
3252 // VQ L& operator/=(VQ L&, R);
3253 // VQ L& operator+=(VQ L&, R);
3254 // VQ L& operator-=(VQ L&, R);
3255 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3256 for (unsigned Right = FirstPromotedArithmeticType;
3257 Right < LastPromotedArithmeticType; ++Right) {
3258 QualType ParamTypes[2];
3259 ParamTypes[1] = ArithmeticTypes[Right];
3260
3261 // Add this built-in operator as a candidate (VQ is empty).
3262 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3263 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3264 /*IsAssigmentOperator=*/Op == OO_Equal);
3265
3266 // Add this built-in operator as a candidate (VQ is 'volatile').
3267 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
3268 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3269 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3270 /*IsAssigmentOperator=*/Op == OO_Equal);
3271 }
3272 }
3273 break;
3274
3275 case OO_PercentEqual:
3276 case OO_LessLessEqual:
3277 case OO_GreaterGreaterEqual:
3278 case OO_AmpEqual:
3279 case OO_CaretEqual:
3280 case OO_PipeEqual:
3281 // C++ [over.built]p22:
3282 //
3283 // For every triple (L, VQ, R), where L is an integral type, VQ
3284 // is either volatile or empty, and R is a promoted integral
3285 // type, there exist candidate operator functions of the form
3286 //
3287 // VQ L& operator%=(VQ L&, R);
3288 // VQ L& operator<<=(VQ L&, R);
3289 // VQ L& operator>>=(VQ L&, R);
3290 // VQ L& operator&=(VQ L&, R);
3291 // VQ L& operator^=(VQ L&, R);
3292 // VQ L& operator|=(VQ L&, R);
3293 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3294 for (unsigned Right = FirstPromotedIntegralType;
3295 Right < LastPromotedIntegralType; ++Right) {
3296 QualType ParamTypes[2];
3297 ParamTypes[1] = ArithmeticTypes[Right];
3298
3299 // Add this built-in operator as a candidate (VQ is empty).
3300 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3301 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3302
3303 // Add this built-in operator as a candidate (VQ is 'volatile').
3304 ParamTypes[0] = ArithmeticTypes[Left];
3305 ParamTypes[0].addVolatile();
3306 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3307 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3308 }
3309 }
3310 break;
3311
3312 case OO_Exclaim: {
3313 // C++ [over.operator]p23:
3314 //
3315 // There also exist candidate operator functions of the form
3316 //
3317 // bool operator!(bool);
3318 // bool operator&&(bool, bool); [BELOW]
3319 // bool operator||(bool, bool); [BELOW]
3320 QualType ParamTy = Context.BoolTy;
3321 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3322 /*IsAssignmentOperator=*/false,
3323 /*NumContextualBoolArguments=*/1);
3324 break;
3325 }
3326
3327 case OO_AmpAmp:
3328 case OO_PipePipe: {
3329 // C++ [over.operator]p23:
3330 //
3331 // There also exist candidate operator functions of the form
3332 //
3333 // bool operator!(bool); [ABOVE]
3334 // bool operator&&(bool, bool);
3335 // bool operator||(bool, bool);
3336 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
3337 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3338 /*IsAssignmentOperator=*/false,
3339 /*NumContextualBoolArguments=*/2);
3340 break;
3341 }
3342
3343 case OO_Subscript:
3344 // C++ [over.built]p13:
3345 //
3346 // For every cv-qualified or cv-unqualified object type T there
3347 // exist candidate operator functions of the form
3348 //
3349 // T* operator+(T*, ptrdiff_t); [ABOVE]
3350 // T& operator[](T*, ptrdiff_t);
3351 // T* operator-(T*, ptrdiff_t); [ABOVE]
3352 // T* operator+(ptrdiff_t, T*); [ABOVE]
3353 // T& operator[](ptrdiff_t, T*);
3354 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3355 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3356 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3357 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
3358 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
3359
3360 // T& operator[](T*, ptrdiff_t)
3361 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3362
3363 // T& operator[](ptrdiff_t, T*);
3364 ParamTypes[0] = ParamTypes[1];
3365 ParamTypes[1] = *Ptr;
3366 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3367 }
3368 break;
3369
3370 case OO_ArrowStar:
3371 // FIXME: No support for pointer-to-members yet.
3372 break;
3373
3374 case OO_Conditional:
3375 // Note that we don't consider the first argument, since it has been
3376 // contextually converted to bool long ago. The candidates below are
3377 // therefore added as binary.
3378 //
3379 // C++ [over.built]p24:
3380 // For every type T, where T is a pointer or pointer-to-member type,
3381 // there exist candidate operator functions of the form
3382 //
3383 // T operator?(bool, T, T);
3384 //
3385 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3386 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3387 QualType ParamTypes[2] = { *Ptr, *Ptr };
3388 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3389 }
3390 for (BuiltinCandidateTypeSet::iterator Ptr =
3391 CandidateTypes.member_pointer_begin(),
3392 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3393 QualType ParamTypes[2] = { *Ptr, *Ptr };
3394 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3395 }
3396 goto Conditional;
3397 }
3398}
3399
3400/// \brief Add function candidates found via argument-dependent lookup
3401/// to the set of overloading candidates.
3402///
3403/// This routine performs argument-dependent name lookup based on the
3404/// given function name (which may also be an operator name) and adds
3405/// all of the overload candidates found by ADL to the overload
3406/// candidate set (C++ [basic.lookup.argdep]).
3407void
3408Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3409 Expr **Args, unsigned NumArgs,
3410 OverloadCandidateSet& CandidateSet) {
3411 FunctionSet Functions;
3412
3413 // Record all of the function candidates that we've already
3414 // added to the overload set, so that we don't add those same
3415 // candidates a second time.
3416 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3417 CandEnd = CandidateSet.end();
3418 Cand != CandEnd; ++Cand)
3408 if (Cand->Function)
3419 if (Cand->Function) {
3409 Functions.insert(Cand->Function);
3420 Functions.insert(Cand->Function);
3421 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3422 Functions.insert(FunTmpl);
3423 }
3410
3411 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
3412
3413 // Erase all of the candidates we already knew about.
3414 // FIXME: This is suboptimal. Is there a better way?
3415 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3416 CandEnd = CandidateSet.end();
3417 Cand != CandEnd; ++Cand)
3424
3425 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
3426
3427 // Erase all of the candidates we already knew about.
3428 // FIXME: This is suboptimal. Is there a better way?
3429 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3430 CandEnd = CandidateSet.end();
3431 Cand != CandEnd; ++Cand)
3418 if (Cand->Function)
3432 if (Cand->Function) {
3419 Functions.erase(Cand->Function);
3433 Functions.erase(Cand->Function);
3434 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3435 Functions.erase(FunTmpl);
3436 }
3420
3421 // For each of the ADL candidates we found, add it to the overload
3422 // set.
3423 for (FunctionSet::iterator Func = Functions.begin(),
3424 FuncEnd = Functions.end();
3437
3438 // For each of the ADL candidates we found, add it to the overload
3439 // set.
3440 for (FunctionSet::iterator Func = Functions.begin(),
3441 FuncEnd = Functions.end();
3425 Func != FuncEnd; ++Func)
3426 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
3442 Func != FuncEnd; ++Func) {
3443 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3444 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3445 else
3446 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3447 /*FIXME: explicit args */false, 0, 0,
3448 Args, NumArgs, CandidateSet);
3449 }
3427}
3428
3429/// isBetterOverloadCandidate - Determines whether the first overload
3430/// candidate is a better candidate than the second (C++ 13.3.3p1).
3431bool
3432Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3433 const OverloadCandidate& Cand2)
3434{
3435 // Define viable functions to be better candidates than non-viable
3436 // functions.
3437 if (!Cand2.Viable)
3438 return Cand1.Viable;
3439 else if (!Cand1.Viable)
3440 return false;
3441
3442 // C++ [over.match.best]p1:
3443 //
3444 // -- if F is a static member function, ICS1(F) is defined such
3445 // that ICS1(F) is neither better nor worse than ICS1(G) for
3446 // any function G, and, symmetrically, ICS1(G) is neither
3447 // better nor worse than ICS1(F).
3448 unsigned StartArg = 0;
3449 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3450 StartArg = 1;
3451
3452 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3453 // function than another viable function F2 if for all arguments i,
3454 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3455 // then...
3456 unsigned NumArgs = Cand1.Conversions.size();
3457 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3458 bool HasBetterConversion = false;
3459 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
3460 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3461 Cand2.Conversions[ArgIdx])) {
3462 case ImplicitConversionSequence::Better:
3463 // Cand1 has a better conversion sequence.
3464 HasBetterConversion = true;
3465 break;
3466
3467 case ImplicitConversionSequence::Worse:
3468 // Cand1 can't be better than Cand2.
3469 return false;
3470
3471 case ImplicitConversionSequence::Indistinguishable:
3472 // Do nothing.
3473 break;
3474 }
3475 }
3476
3477 if (HasBetterConversion)
3478 return true;
3479
3480 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3481 // implemented, but they require template support.
3482
3483 // C++ [over.match.best]p1b4:
3484 //
3485 // -- the context is an initialization by user-defined conversion
3486 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3487 // from the return type of F1 to the destination type (i.e.,
3488 // the type of the entity being initialized) is a better
3489 // conversion sequence than the standard conversion sequence
3490 // from the return type of F2 to the destination type.
3491 if (Cand1.Function && Cand2.Function &&
3492 isa<CXXConversionDecl>(Cand1.Function) &&
3493 isa<CXXConversionDecl>(Cand2.Function)) {
3494 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3495 Cand2.FinalConversion)) {
3496 case ImplicitConversionSequence::Better:
3497 // Cand1 has a better conversion sequence.
3498 return true;
3499
3500 case ImplicitConversionSequence::Worse:
3501 // Cand1 can't be better than Cand2.
3502 return false;
3503
3504 case ImplicitConversionSequence::Indistinguishable:
3505 // Do nothing
3506 break;
3507 }
3508 }
3509
3510 return false;
3511}
3512
3513/// \brief Computes the best viable function (C++ 13.3.3)
3514/// within an overload candidate set.
3515///
3516/// \param CandidateSet the set of candidate functions.
3517///
3518/// \param Loc the location of the function name (or operator symbol) for
3519/// which overload resolution occurs.
3520///
3521/// \param Best f overload resolution was successful or found a deleted
3522/// function, Best points to the candidate function found.
3523///
3524/// \returns The result of overload resolution.
3525Sema::OverloadingResult
3526Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3527 SourceLocation Loc,
3528 OverloadCandidateSet::iterator& Best)
3529{
3530 // Find the best viable function.
3531 Best = CandidateSet.end();
3532 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3533 Cand != CandidateSet.end(); ++Cand) {
3534 if (Cand->Viable) {
3535 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3536 Best = Cand;
3537 }
3538 }
3539
3540 // If we didn't find any viable functions, abort.
3541 if (Best == CandidateSet.end())
3542 return OR_No_Viable_Function;
3543
3544 // Make sure that this function is better than every other viable
3545 // function. If not, we have an ambiguity.
3546 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3547 Cand != CandidateSet.end(); ++Cand) {
3548 if (Cand->Viable &&
3549 Cand != Best &&
3550 !isBetterOverloadCandidate(*Best, *Cand)) {
3551 Best = CandidateSet.end();
3552 return OR_Ambiguous;
3553 }
3554 }
3555
3556 // Best is the best viable function.
3557 if (Best->Function &&
3558 (Best->Function->isDeleted() ||
3450}
3451
3452/// isBetterOverloadCandidate - Determines whether the first overload
3453/// candidate is a better candidate than the second (C++ 13.3.3p1).
3454bool
3455Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3456 const OverloadCandidate& Cand2)
3457{
3458 // Define viable functions to be better candidates than non-viable
3459 // functions.
3460 if (!Cand2.Viable)
3461 return Cand1.Viable;
3462 else if (!Cand1.Viable)
3463 return false;
3464
3465 // C++ [over.match.best]p1:
3466 //
3467 // -- if F is a static member function, ICS1(F) is defined such
3468 // that ICS1(F) is neither better nor worse than ICS1(G) for
3469 // any function G, and, symmetrically, ICS1(G) is neither
3470 // better nor worse than ICS1(F).
3471 unsigned StartArg = 0;
3472 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3473 StartArg = 1;
3474
3475 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3476 // function than another viable function F2 if for all arguments i,
3477 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3478 // then...
3479 unsigned NumArgs = Cand1.Conversions.size();
3480 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3481 bool HasBetterConversion = false;
3482 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
3483 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3484 Cand2.Conversions[ArgIdx])) {
3485 case ImplicitConversionSequence::Better:
3486 // Cand1 has a better conversion sequence.
3487 HasBetterConversion = true;
3488 break;
3489
3490 case ImplicitConversionSequence::Worse:
3491 // Cand1 can't be better than Cand2.
3492 return false;
3493
3494 case ImplicitConversionSequence::Indistinguishable:
3495 // Do nothing.
3496 break;
3497 }
3498 }
3499
3500 if (HasBetterConversion)
3501 return true;
3502
3503 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3504 // implemented, but they require template support.
3505
3506 // C++ [over.match.best]p1b4:
3507 //
3508 // -- the context is an initialization by user-defined conversion
3509 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3510 // from the return type of F1 to the destination type (i.e.,
3511 // the type of the entity being initialized) is a better
3512 // conversion sequence than the standard conversion sequence
3513 // from the return type of F2 to the destination type.
3514 if (Cand1.Function && Cand2.Function &&
3515 isa<CXXConversionDecl>(Cand1.Function) &&
3516 isa<CXXConversionDecl>(Cand2.Function)) {
3517 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3518 Cand2.FinalConversion)) {
3519 case ImplicitConversionSequence::Better:
3520 // Cand1 has a better conversion sequence.
3521 return true;
3522
3523 case ImplicitConversionSequence::Worse:
3524 // Cand1 can't be better than Cand2.
3525 return false;
3526
3527 case ImplicitConversionSequence::Indistinguishable:
3528 // Do nothing
3529 break;
3530 }
3531 }
3532
3533 return false;
3534}
3535
3536/// \brief Computes the best viable function (C++ 13.3.3)
3537/// within an overload candidate set.
3538///
3539/// \param CandidateSet the set of candidate functions.
3540///
3541/// \param Loc the location of the function name (or operator symbol) for
3542/// which overload resolution occurs.
3543///
3544/// \param Best f overload resolution was successful or found a deleted
3545/// function, Best points to the candidate function found.
3546///
3547/// \returns The result of overload resolution.
3548Sema::OverloadingResult
3549Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3550 SourceLocation Loc,
3551 OverloadCandidateSet::iterator& Best)
3552{
3553 // Find the best viable function.
3554 Best = CandidateSet.end();
3555 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3556 Cand != CandidateSet.end(); ++Cand) {
3557 if (Cand->Viable) {
3558 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3559 Best = Cand;
3560 }
3561 }
3562
3563 // If we didn't find any viable functions, abort.
3564 if (Best == CandidateSet.end())
3565 return OR_No_Viable_Function;
3566
3567 // Make sure that this function is better than every other viable
3568 // function. If not, we have an ambiguity.
3569 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3570 Cand != CandidateSet.end(); ++Cand) {
3571 if (Cand->Viable &&
3572 Cand != Best &&
3573 !isBetterOverloadCandidate(*Best, *Cand)) {
3574 Best = CandidateSet.end();
3575 return OR_Ambiguous;
3576 }
3577 }
3578
3579 // Best is the best viable function.
3580 if (Best->Function &&
3581 (Best->Function->isDeleted() ||
3559 Best->Function->getAttr<UnavailableAttr>(Context)))
3582 Best->Function->getAttr()))
3560 return OR_Deleted;
3561
3562 // C++ [basic.def.odr]p2:
3563 // An overloaded function is used if it is selected by overload resolution
3564 // when referred to from a potentially-evaluated expression. [Note: this
3565 // covers calls to named functions (5.2.2), operator overloading
3566 // (clause 13), user-defined conversions (12.3.2), allocation function for
3567 // placement new (5.3.4), as well as non-default initialization (8.5).
3568 if (Best->Function)
3569 MarkDeclarationReferenced(Loc, Best->Function);
3570 return OR_Success;
3571}
3572
3573/// PrintOverloadCandidates - When overload resolution fails, prints
3574/// diagnostic messages containing the candidates in the candidate
3575/// set. If OnlyViable is true, only viable candidates will be printed.
3576void
3577Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3578 bool OnlyViable)
3579{
3580 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3581 LastCand = CandidateSet.end();
3582 for (; Cand != LastCand; ++Cand) {
3583 if (Cand->Viable || !OnlyViable) {
3584 if (Cand->Function) {
3585 if (Cand->Function->isDeleted() ||
3583 return OR_Deleted;
3584
3585 // C++ [basic.def.odr]p2:
3586 // An overloaded function is used if it is selected by overload resolution
3587 // when referred to from a potentially-evaluated expression. [Note: this
3588 // covers calls to named functions (5.2.2), operator overloading
3589 // (clause 13), user-defined conversions (12.3.2), allocation function for
3590 // placement new (5.3.4), as well as non-default initialization (8.5).
3591 if (Best->Function)
3592 MarkDeclarationReferenced(Loc, Best->Function);
3593 return OR_Success;
3594}
3595
3596/// PrintOverloadCandidates - When overload resolution fails, prints
3597/// diagnostic messages containing the candidates in the candidate
3598/// set. If OnlyViable is true, only viable candidates will be printed.
3599void
3600Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3601 bool OnlyViable)
3602{
3603 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3604 LastCand = CandidateSet.end();
3605 for (; Cand != LastCand; ++Cand) {
3606 if (Cand->Viable || !OnlyViable) {
3607 if (Cand->Function) {
3608 if (Cand->Function->isDeleted() ||
3586 Cand->Function->getAttr<UnavailableAttr>(Context)) {
3609 Cand->Function->getAttr()) {
3587 // Deleted or "unavailable" function.
3588 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3589 << Cand->Function->isDeleted();
3590 } else {
3591 // Normal function
3592 // FIXME: Give a better reason!
3593 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3594 }
3595 } else if (Cand->IsSurrogate) {
3596 // Desugar the type of the surrogate down to a function type,
3597 // retaining as many typedefs as possible while still showing
3598 // the function type (and, therefore, its parameter types).
3599 QualType FnType = Cand->Surrogate->getConversionType();
3600 bool isLValueReference = false;
3601 bool isRValueReference = false;
3602 bool isPointer = false;
3603 if (const LValueReferenceType *FnTypeRef =
3604 FnType->getAsLValueReferenceType()) {
3605 FnType = FnTypeRef->getPointeeType();
3606 isLValueReference = true;
3607 } else if (const RValueReferenceType *FnTypeRef =
3608 FnType->getAsRValueReferenceType()) {
3609 FnType = FnTypeRef->getPointeeType();
3610 isRValueReference = true;
3611 }
3612 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3613 FnType = FnTypePtr->getPointeeType();
3614 isPointer = true;
3615 }
3616 // Desugar down to a function type.
3617 FnType = QualType(FnType->getAsFunctionType(), 0);
3618 // Reconstruct the pointer/reference as appropriate.
3619 if (isPointer) FnType = Context.getPointerType(FnType);
3620 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3621 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
3622
3623 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
3624 << FnType;
3625 } else {
3626 // FIXME: We need to get the identifier in here
3627 // FIXME: Do we want the error message to point at the operator?
3628 // (built-ins won't have a location)
3629 QualType FnType
3630 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3631 Cand->BuiltinTypes.ParamTypes,
3632 Cand->Conversions.size(),
3633 false, 0);
3634
3635 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
3636 }
3637 }
3638 }
3639}
3640
3641/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3642/// an overloaded function (C++ [over.over]), where @p From is an
3643/// expression with overloaded function type and @p ToType is the type
3644/// we're trying to resolve to. For example:
3645///
3646/// @code
3647/// int f(double);
3648/// int f(int);
3649///
3650/// int (*pfd)(double) = f; // selects f(double)
3651/// @endcode
3652///
3653/// This routine returns the resulting FunctionDecl if it could be
3654/// resolved, and NULL otherwise. When @p Complain is true, this
3655/// routine will emit diagnostics if there is an error.
3656FunctionDecl *
3657Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
3658 bool Complain) {
3659 QualType FunctionType = ToType;
3660 bool IsMember = false;
3661 if (const PointerType *ToTypePtr = ToType->getAsPointerType())
3662 FunctionType = ToTypePtr->getPointeeType();
3663 else if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType())
3664 FunctionType = ToTypeRef->getPointeeType();
3665 else if (const MemberPointerType *MemTypePtr =
3666 ToType->getAsMemberPointerType()) {
3667 FunctionType = MemTypePtr->getPointeeType();
3668 IsMember = true;
3669 }
3670
3671 // We only look at pointers or references to functions.
3672 if (!FunctionType->isFunctionType())
3673 return 0;
3674
3675 // Find the actual overloaded function declaration.
3676 OverloadedFunctionDecl *Ovl = 0;
3677
3678 // C++ [over.over]p1:
3679 // [...] [Note: any redundant set of parentheses surrounding the
3680 // overloaded function name is ignored (5.1). ]
3681 Expr *OvlExpr = From->IgnoreParens();
3682
3683 // C++ [over.over]p1:
3684 // [...] The overloaded function name can be preceded by the &
3685 // operator.
3686 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3687 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3688 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3689 }
3690
3691 // Try to dig out the overloaded function.
3692 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3693 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3694
3695 // If there's no overloaded function declaration, we're done.
3696 if (!Ovl)
3697 return 0;
3698
3699 // Look through all of the overloaded functions, searching for one
3700 // whose type matches exactly.
3701 // FIXME: When templates or using declarations come along, we'll actually
3702 // have to deal with duplicates, partial ordering, etc. For now, we
3703 // can just do a simple search.
3704 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3705 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3706 Fun != Ovl->function_end(); ++Fun) {
3707 // C++ [over.over]p3:
3708 // Non-member functions and static member functions match
3709 // targets of type "pointer-to-function" or "reference-to-function."
3710 // Nonstatic member functions match targets of
3711 // type "pointer-to-member-function."
3712 // Note that according to DR 247, the containing class does not matter.
3713 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3714 // Skip non-static functions when converting to pointer, and static
3715 // when converting to member pointer.
3716 if (Method->isStatic() == IsMember)
3717 continue;
3718 } else if (IsMember)
3719 continue;
3720
3721 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
3722 if (FunctionType == Context.getCanonicalType(FunDecl->getType()))
3723 return FunDecl;
3724 } else {
3725 unsigned DiagID
3726 = PP.getDiagnostics().getCustomDiagID(Diagnostic::Warning,
3727 "Clang does not yet support templated conversion functions");
3728 Diag(From->getLocStart(), DiagID);
3729 }
3730 }
3731
3732 return 0;
3733}
3734
3735/// ResolveOverloadedCallFn - Given the call expression that calls Fn
3736/// (which eventually refers to the declaration Func) and the call
3737/// arguments Args/NumArgs, attempt to resolve the function call down
3738/// to a specific function. If overload resolution succeeds, returns
3739/// the function declaration produced by overload
3740/// resolution. Otherwise, emits diagnostics, deletes all of the
3741/// arguments and Fn, and returns NULL.
3742FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
3743 DeclarationName UnqualifiedName,
3610 // Deleted or "unavailable" function.
3611 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3612 << Cand->Function->isDeleted();
3613 } else {
3614 // Normal function
3615 // FIXME: Give a better reason!
3616 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3617 }
3618 } else if (Cand->IsSurrogate) {
3619 // Desugar the type of the surrogate down to a function type,
3620 // retaining as many typedefs as possible while still showing
3621 // the function type (and, therefore, its parameter types).
3622 QualType FnType = Cand->Surrogate->getConversionType();
3623 bool isLValueReference = false;
3624 bool isRValueReference = false;
3625 bool isPointer = false;
3626 if (const LValueReferenceType *FnTypeRef =
3627 FnType->getAsLValueReferenceType()) {
3628 FnType = FnTypeRef->getPointeeType();
3629 isLValueReference = true;
3630 } else if (const RValueReferenceType *FnTypeRef =
3631 FnType->getAsRValueReferenceType()) {
3632 FnType = FnTypeRef->getPointeeType();
3633 isRValueReference = true;
3634 }
3635 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3636 FnType = FnTypePtr->getPointeeType();
3637 isPointer = true;
3638 }
3639 // Desugar down to a function type.
3640 FnType = QualType(FnType->getAsFunctionType(), 0);
3641 // Reconstruct the pointer/reference as appropriate.
3642 if (isPointer) FnType = Context.getPointerType(FnType);
3643 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3644 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
3645
3646 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
3647 << FnType;
3648 } else {
3649 // FIXME: We need to get the identifier in here
3650 // FIXME: Do we want the error message to point at the operator?
3651 // (built-ins won't have a location)
3652 QualType FnType
3653 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3654 Cand->BuiltinTypes.ParamTypes,
3655 Cand->Conversions.size(),
3656 false, 0);
3657
3658 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
3659 }
3660 }
3661 }
3662}
3663
3664/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3665/// an overloaded function (C++ [over.over]), where @p From is an
3666/// expression with overloaded function type and @p ToType is the type
3667/// we're trying to resolve to. For example:
3668///
3669/// @code
3670/// int f(double);
3671/// int f(int);
3672///
3673/// int (*pfd)(double) = f; // selects f(double)
3674/// @endcode
3675///
3676/// This routine returns the resulting FunctionDecl if it could be
3677/// resolved, and NULL otherwise. When @p Complain is true, this
3678/// routine will emit diagnostics if there is an error.
3679FunctionDecl *
3680Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
3681 bool Complain) {
3682 QualType FunctionType = ToType;
3683 bool IsMember = false;
3684 if (const PointerType *ToTypePtr = ToType->getAsPointerType())
3685 FunctionType = ToTypePtr->getPointeeType();
3686 else if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType())
3687 FunctionType = ToTypeRef->getPointeeType();
3688 else if (const MemberPointerType *MemTypePtr =
3689 ToType->getAsMemberPointerType()) {
3690 FunctionType = MemTypePtr->getPointeeType();
3691 IsMember = true;
3692 }
3693
3694 // We only look at pointers or references to functions.
3695 if (!FunctionType->isFunctionType())
3696 return 0;
3697
3698 // Find the actual overloaded function declaration.
3699 OverloadedFunctionDecl *Ovl = 0;
3700
3701 // C++ [over.over]p1:
3702 // [...] [Note: any redundant set of parentheses surrounding the
3703 // overloaded function name is ignored (5.1). ]
3704 Expr *OvlExpr = From->IgnoreParens();
3705
3706 // C++ [over.over]p1:
3707 // [...] The overloaded function name can be preceded by the &
3708 // operator.
3709 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3710 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3711 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3712 }
3713
3714 // Try to dig out the overloaded function.
3715 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3716 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3717
3718 // If there's no overloaded function declaration, we're done.
3719 if (!Ovl)
3720 return 0;
3721
3722 // Look through all of the overloaded functions, searching for one
3723 // whose type matches exactly.
3724 // FIXME: When templates or using declarations come along, we'll actually
3725 // have to deal with duplicates, partial ordering, etc. For now, we
3726 // can just do a simple search.
3727 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3728 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3729 Fun != Ovl->function_end(); ++Fun) {
3730 // C++ [over.over]p3:
3731 // Non-member functions and static member functions match
3732 // targets of type "pointer-to-function" or "reference-to-function."
3733 // Nonstatic member functions match targets of
3734 // type "pointer-to-member-function."
3735 // Note that according to DR 247, the containing class does not matter.
3736 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3737 // Skip non-static functions when converting to pointer, and static
3738 // when converting to member pointer.
3739 if (Method->isStatic() == IsMember)
3740 continue;
3741 } else if (IsMember)
3742 continue;
3743
3744 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
3745 if (FunctionType == Context.getCanonicalType(FunDecl->getType()))
3746 return FunDecl;
3747 } else {
3748 unsigned DiagID
3749 = PP.getDiagnostics().getCustomDiagID(Diagnostic::Warning,
3750 "Clang does not yet support templated conversion functions");
3751 Diag(From->getLocStart(), DiagID);
3752 }
3753 }
3754
3755 return 0;
3756}
3757
3758/// ResolveOverloadedCallFn - Given the call expression that calls Fn
3759/// (which eventually refers to the declaration Func) and the call
3760/// arguments Args/NumArgs, attempt to resolve the function call down
3761/// to a specific function. If overload resolution succeeds, returns
3762/// the function declaration produced by overload
3763/// resolution. Otherwise, emits diagnostics, deletes all of the
3764/// arguments and Fn, and returns NULL.
3765FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
3766 DeclarationName UnqualifiedName,
3767 bool HasExplicitTemplateArgs,
3768 const TemplateArgument *ExplicitTemplateArgs,
3769 unsigned NumExplicitTemplateArgs,
3744 SourceLocation LParenLoc,
3745 Expr **Args, unsigned NumArgs,
3746 SourceLocation *CommaLocs,
3747 SourceLocation RParenLoc,
3748 bool &ArgumentDependentLookup) {
3749 OverloadCandidateSet CandidateSet;
3750
3751 // Add the functions denoted by Callee to the set of candidate
3752 // functions. While we're doing so, track whether argument-dependent
3753 // lookup still applies, per:
3754 //
3755 // C++0x [basic.lookup.argdep]p3:
3756 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3757 // and let Y be the lookup set produced by argument dependent
3758 // lookup (defined as follows). If X contains
3759 //
3760 // -- a declaration of a class member, or
3761 //
3762 // -- a block-scope function declaration that is not a
3763 // using-declaration, or
3764 //
3765 // -- a declaration that is neither a function or a function
3766 // template
3767 //
3768 // then Y is empty.
3769 if (OverloadedFunctionDecl *Ovl
3770 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3771 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3772 FuncEnd = Ovl->function_end();
3773 Func != FuncEnd; ++Func) {
3774 DeclContext *Ctx = 0;
3775 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
3770 SourceLocation LParenLoc,
3771 Expr **Args, unsigned NumArgs,
3772 SourceLocation *CommaLocs,
3773 SourceLocation RParenLoc,
3774 bool &ArgumentDependentLookup) {
3775 OverloadCandidateSet CandidateSet;
3776
3777 // Add the functions denoted by Callee to the set of candidate
3778 // functions. While we're doing so, track whether argument-dependent
3779 // lookup still applies, per:
3780 //
3781 // C++0x [basic.lookup.argdep]p3:
3782 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3783 // and let Y be the lookup set produced by argument dependent
3784 // lookup (defined as follows). If X contains
3785 //
3786 // -- a declaration of a class member, or
3787 //
3788 // -- a block-scope function declaration that is not a
3789 // using-declaration, or
3790 //
3791 // -- a declaration that is neither a function or a function
3792 // template
3793 //
3794 // then Y is empty.
3795 if (OverloadedFunctionDecl *Ovl
3796 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3797 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3798 FuncEnd = Ovl->function_end();
3799 Func != FuncEnd; ++Func) {
3800 DeclContext *Ctx = 0;
3801 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
3802 if (HasExplicitTemplateArgs)
3803 continue;
3804
3776 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
3777 Ctx = FunDecl->getDeclContext();
3778 } else {
3779 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
3805 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
3806 Ctx = FunDecl->getDeclContext();
3807 } else {
3808 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
3780 AddTemplateOverloadCandidate(FunTmpl, Args, NumArgs, CandidateSet);
3809 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
3810 ExplicitTemplateArgs,
3811 NumExplicitTemplateArgs,
3812 Args, NumArgs, CandidateSet);
3781 Ctx = FunTmpl->getDeclContext();
3782 }
3783
3784
3785 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
3786 ArgumentDependentLookup = false;
3787 }
3788 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3813 Ctx = FunTmpl->getDeclContext();
3814 }
3815
3816
3817 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
3818 ArgumentDependentLookup = false;
3819 }
3820 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3821 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
3789 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3790
3791 if (Func->getDeclContext()->isRecord() ||
3792 Func->getDeclContext()->isFunctionOrMethod())
3793 ArgumentDependentLookup = false;
3794 } else if (FunctionTemplateDecl *FuncTemplate
3795 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
3822 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3823
3824 if (Func->getDeclContext()->isRecord() ||
3825 Func->getDeclContext()->isFunctionOrMethod())
3826 ArgumentDependentLookup = false;
3827 } else if (FunctionTemplateDecl *FuncTemplate
3828 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
3796 AddTemplateOverloadCandidate(FuncTemplate, Args, NumArgs, CandidateSet);
3829 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
3830 ExplicitTemplateArgs,
3831 NumExplicitTemplateArgs,
3832 Args, NumArgs, CandidateSet);
3797
3798 if (FuncTemplate->getDeclContext()->isRecord())
3799 ArgumentDependentLookup = false;
3800 }
3801
3802 if (Callee)
3803 UnqualifiedName = Callee->getDeclName();
3804
3833
3834 if (FuncTemplate->getDeclContext()->isRecord())
3835 ArgumentDependentLookup = false;
3836 }
3837
3838 if (Callee)
3839 UnqualifiedName = Callee->getDeclName();
3840
3841 // FIXME: Pass explicit template arguments through for ADL
3805 if (ArgumentDependentLookup)
3806 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
3807 CandidateSet);
3808
3809 OverloadCandidateSet::iterator Best;
3810 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
3811 case OR_Success:
3812 return Best->Function;
3813
3814 case OR_No_Viable_Function:
3815 Diag(Fn->getSourceRange().getBegin(),
3816 diag::err_ovl_no_viable_function_in_call)
3817 << UnqualifiedName << Fn->getSourceRange();
3818 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3819 break;
3820
3821 case OR_Ambiguous:
3822 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
3823 << UnqualifiedName << Fn->getSourceRange();
3824 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3825 break;
3826
3827 case OR_Deleted:
3828 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
3829 << Best->Function->isDeleted()
3830 << UnqualifiedName
3831 << Fn->getSourceRange();
3832 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3833 break;
3834 }
3835
3836 // Overload resolution failed. Destroy all of the subexpressions and
3837 // return NULL.
3838 Fn->Destroy(Context);
3839 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3840 Args[Arg]->Destroy(Context);
3841 return 0;
3842}
3843
3844/// \brief Create a unary operation that may resolve to an overloaded
3845/// operator.
3846///
3847/// \param OpLoc The location of the operator itself (e.g., '*').
3848///
3849/// \param OpcIn The UnaryOperator::Opcode that describes this
3850/// operator.
3851///
3852/// \param Functions The set of non-member functions that will be
3853/// considered by overload resolution. The caller needs to build this
3854/// set based on the context using, e.g.,
3855/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3856/// set should not contain any member functions; those will be added
3857/// by CreateOverloadedUnaryOp().
3858///
3859/// \param input The input argument.
3860Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
3861 unsigned OpcIn,
3862 FunctionSet &Functions,
3863 ExprArg input) {
3864 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
3865 Expr *Input = (Expr *)input.get();
3866
3867 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
3868 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
3869 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3870
3871 Expr *Args[2] = { Input, 0 };
3872 unsigned NumArgs = 1;
3873
3874 // For post-increment and post-decrement, add the implicit '0' as
3875 // the second argument, so that we know this is a post-increment or
3876 // post-decrement.
3877 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
3878 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
3879 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
3880 SourceLocation());
3881 NumArgs = 2;
3882 }
3883
3884 if (Input->isTypeDependent()) {
3885 OverloadedFunctionDecl *Overloads
3886 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3887 for (FunctionSet::iterator Func = Functions.begin(),
3888 FuncEnd = Functions.end();
3889 Func != FuncEnd; ++Func)
3890 Overloads->addOverload(*Func);
3891
3892 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3893 OpLoc, false, false);
3894
3895 input.release();
3896 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3897 &Args[0], NumArgs,
3898 Context.DependentTy,
3899 OpLoc));
3900 }
3901
3902 // Build an empty overload set.
3903 OverloadCandidateSet CandidateSet;
3904
3905 // Add the candidates from the given function set.
3906 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
3907
3908 // Add operator candidates that are member functions.
3909 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
3910
3911 // Add builtin operator candidates.
3912 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
3913
3914 // Perform overload resolution.
3915 OverloadCandidateSet::iterator Best;
3916 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
3917 case OR_Success: {
3918 // We found a built-in operator or an overloaded operator.
3919 FunctionDecl *FnDecl = Best->Function;
3920
3921 if (FnDecl) {
3922 // We matched an overloaded operator. Build a call to that
3923 // operator.
3924
3925 // Convert the arguments.
3926 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3927 if (PerformObjectArgumentInitialization(Input, Method))
3928 return ExprError();
3929 } else {
3930 // Convert the arguments.
3931 if (PerformCopyInitialization(Input,
3932 FnDecl->getParamDecl(0)->getType(),
3933 "passing"))
3934 return ExprError();
3935 }
3936
3937 // Determine the result type
3938 QualType ResultTy
3939 = FnDecl->getType()->getAsFunctionType()->getResultType();
3940 ResultTy = ResultTy.getNonReferenceType();
3941
3942 // Build the actual expression node.
3943 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3944 SourceLocation());
3945 UsualUnaryConversions(FnExpr);
3946
3947 input.release();
3948 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3949 &Input, 1, ResultTy,
3950 OpLoc));
3951 } else {
3952 // We matched a built-in operator. Convert the arguments, then
3953 // break out so that we will build the appropriate built-in
3954 // operator node.
3955 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3956 Best->Conversions[0], "passing"))
3957 return ExprError();
3958
3959 break;
3960 }
3961 }
3962
3963 case OR_No_Viable_Function:
3964 // No viable function; fall through to handling this as a
3965 // built-in operator, which will produce an error message for us.
3966 break;
3967
3968 case OR_Ambiguous:
3969 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3970 << UnaryOperator::getOpcodeStr(Opc)
3971 << Input->getSourceRange();
3972 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3973 return ExprError();
3974
3975 case OR_Deleted:
3976 Diag(OpLoc, diag::err_ovl_deleted_oper)
3977 << Best->Function->isDeleted()
3978 << UnaryOperator::getOpcodeStr(Opc)
3979 << Input->getSourceRange();
3980 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3981 return ExprError();
3982 }
3983
3984 // Either we found no viable overloaded operator or we matched a
3985 // built-in operator. In either case, fall through to trying to
3986 // build a built-in operation.
3987 input.release();
3988 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
3989}
3990
3991/// \brief Create a binary operation that may resolve to an overloaded
3992/// operator.
3993///
3994/// \param OpLoc The location of the operator itself (e.g., '+').
3995///
3996/// \param OpcIn The BinaryOperator::Opcode that describes this
3997/// operator.
3998///
3999/// \param Functions The set of non-member functions that will be
4000/// considered by overload resolution. The caller needs to build this
4001/// set based on the context using, e.g.,
4002/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4003/// set should not contain any member functions; those will be added
4004/// by CreateOverloadedBinOp().
4005///
4006/// \param LHS Left-hand argument.
4007/// \param RHS Right-hand argument.
4008Sema::OwningExprResult
4009Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4010 unsigned OpcIn,
4011 FunctionSet &Functions,
4012 Expr *LHS, Expr *RHS) {
4013 Expr *Args[2] = { LHS, RHS };
4014
4015 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4016 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4017 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4018
4019 // If either side is type-dependent, create an appropriate dependent
4020 // expression.
4021 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
4022 // .* cannot be overloaded.
4023 if (Opc == BinaryOperator::PtrMemD)
4024 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
4025 Context.DependentTy, OpLoc));
4026
4027 OverloadedFunctionDecl *Overloads
4028 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4029 for (FunctionSet::iterator Func = Functions.begin(),
4030 FuncEnd = Functions.end();
4031 Func != FuncEnd; ++Func)
4032 Overloads->addOverload(*Func);
4033
4034 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4035 OpLoc, false, false);
4036
4037 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4038 Args, 2,
4039 Context.DependentTy,
4040 OpLoc));
4041 }
4042
4043 // If this is the .* operator, which is not overloadable, just
4044 // create a built-in binary operator.
4045 if (Opc == BinaryOperator::PtrMemD)
4046 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4047
4048 // If this is one of the assignment operators, we only perform
4049 // overload resolution if the left-hand side is a class or
4050 // enumeration type (C++ [expr.ass]p3).
4051 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
4052 !LHS->getType()->isOverloadableType())
4053 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4054
4055 // Build an empty overload set.
4056 OverloadCandidateSet CandidateSet;
4057
4058 // Add the candidates from the given function set.
4059 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4060
4061 // Add operator candidates that are member functions.
4062 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4063
4064 // Add builtin operator candidates.
4065 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4066
4067 // Perform overload resolution.
4068 OverloadCandidateSet::iterator Best;
4069 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4070 case OR_Success: {
4071 // We found a built-in operator or an overloaded operator.
4072 FunctionDecl *FnDecl = Best->Function;
4073
4074 if (FnDecl) {
4075 // We matched an overloaded operator. Build a call to that
4076 // operator.
4077
4078 // Convert the arguments.
4079 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4080 if (PerformObjectArgumentInitialization(LHS, Method) ||
4081 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
4082 "passing"))
4083 return ExprError();
4084 } else {
4085 // Convert the arguments.
4086 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
4087 "passing") ||
4088 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
4089 "passing"))
4090 return ExprError();
4091 }
4092
4093 // Determine the result type
4094 QualType ResultTy
4095 = FnDecl->getType()->getAsFunctionType()->getResultType();
4096 ResultTy = ResultTy.getNonReferenceType();
4097
4098 // Build the actual expression node.
4099 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4100 SourceLocation());
4101 UsualUnaryConversions(FnExpr);
4102
4103 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4104 Args, 2, ResultTy,
4105 OpLoc));
4106 } else {
4107 // We matched a built-in operator. Convert the arguments, then
4108 // break out so that we will build the appropriate built-in
4109 // operator node.
4110 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
4111 Best->Conversions[0], "passing") ||
4112 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
4113 Best->Conversions[1], "passing"))
4114 return ExprError();
4115
4116 break;
4117 }
4118 }
4119
4120 case OR_No_Viable_Function:
4121 // For class as left operand for assignment or compound assigment operator
4122 // do not fall through to handling in built-in, but report that no overloaded
4123 // assignment operator found
4124 if (LHS->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4125 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4126 << BinaryOperator::getOpcodeStr(Opc)
4127 << LHS->getSourceRange() << RHS->getSourceRange();
4128 return ExprError();
4129 }
4130 // No viable function; fall through to handling this as a
4131 // built-in operator, which will produce an error message for us.
4132 break;
4133
4134 case OR_Ambiguous:
4135 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4136 << BinaryOperator::getOpcodeStr(Opc)
4137 << LHS->getSourceRange() << RHS->getSourceRange();
4138 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4139 return ExprError();
4140
4141 case OR_Deleted:
4142 Diag(OpLoc, diag::err_ovl_deleted_oper)
4143 << Best->Function->isDeleted()
4144 << BinaryOperator::getOpcodeStr(Opc)
4145 << LHS->getSourceRange() << RHS->getSourceRange();
4146 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4147 return ExprError();
4148 }
4149
4150 // Either we found no viable overloaded operator or we matched a
4151 // built-in operator. In either case, try to build a built-in
4152 // operation.
4153 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4154}
4155
4156/// BuildCallToMemberFunction - Build a call to a member
4157/// function. MemExpr is the expression that refers to the member
4158/// function (and includes the object parameter), Args/NumArgs are the
4159/// arguments to the function call (not including the object
4160/// parameter). The caller needs to validate that the member
4161/// expression refers to a member function or an overloaded member
4162/// function.
4163Sema::ExprResult
4164Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4165 SourceLocation LParenLoc, Expr **Args,
4166 unsigned NumArgs, SourceLocation *CommaLocs,
4167 SourceLocation RParenLoc) {
4168 // Dig out the member expression. This holds both the object
4169 // argument and the member function we're referring to.
4170 MemberExpr *MemExpr = 0;
4171 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4172 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4173 else
4174 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4175 assert(MemExpr && "Building member call without member expression");
4176
4177 // Extract the object argument.
4178 Expr *ObjectArg = MemExpr->getBase();
4179
4180 CXXMethodDecl *Method = 0;
4181 if (OverloadedFunctionDecl *Ovl
4182 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
4183 // Add overload candidates
4184 OverloadCandidateSet CandidateSet;
4185 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4186 FuncEnd = Ovl->function_end();
4187 Func != FuncEnd; ++Func) {
4188 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
4189 Method = cast<CXXMethodDecl>(*Func);
4190 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4191 /*SuppressUserConversions=*/false);
4192 }
4193
4194 OverloadCandidateSet::iterator Best;
4195 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
4196 case OR_Success:
4197 Method = cast<CXXMethodDecl>(Best->Function);
4198 break;
4199
4200 case OR_No_Viable_Function:
4201 Diag(MemExpr->getSourceRange().getBegin(),
4202 diag::err_ovl_no_viable_member_function_in_call)
4203 << Ovl->getDeclName() << MemExprE->getSourceRange();
4204 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4205 // FIXME: Leaking incoming expressions!
4206 return true;
4207
4208 case OR_Ambiguous:
4209 Diag(MemExpr->getSourceRange().getBegin(),
4210 diag::err_ovl_ambiguous_member_call)
4211 << Ovl->getDeclName() << MemExprE->getSourceRange();
4212 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4213 // FIXME: Leaking incoming expressions!
4214 return true;
4215
4216 case OR_Deleted:
4217 Diag(MemExpr->getSourceRange().getBegin(),
4218 diag::err_ovl_deleted_member_call)
4219 << Best->Function->isDeleted()
4220 << Ovl->getDeclName() << MemExprE->getSourceRange();
4221 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4222 // FIXME: Leaking incoming expressions!
4223 return true;
4224 }
4225
4226 FixOverloadedFunctionReference(MemExpr, Method);
4227 } else {
4228 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4229 }
4230
4231 assert(Method && "Member call to something that isn't a method?");
4232 ExprOwningPtr<CXXMemberCallExpr>
4233 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4234 NumArgs,
4235 Method->getResultType().getNonReferenceType(),
4236 RParenLoc));
4237
4238 // Convert the object argument (for a non-static member function call).
4239 if (!Method->isStatic() &&
4240 PerformObjectArgumentInitialization(ObjectArg, Method))
4241 return true;
4242 MemExpr->setBase(ObjectArg);
4243
4244 // Convert the rest of the arguments
4245 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
4246 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4247 RParenLoc))
4248 return true;
4249
4250 return CheckFunctionCall(Method, TheCall.take()).release();
4251}
4252
4253/// BuildCallToObjectOfClassType - Build a call to an object of class
4254/// type (C++ [over.call.object]), which can end up invoking an
4255/// overloaded function call operator (@c operator()) or performing a
4256/// user-defined conversion on the object argument.
4257Sema::ExprResult
4258Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4259 SourceLocation LParenLoc,
4260 Expr **Args, unsigned NumArgs,
4261 SourceLocation *CommaLocs,
4262 SourceLocation RParenLoc) {
4263 assert(Object->getType()->isRecordType() && "Requires object type argument");
4264 const RecordType *Record = Object->getType()->getAsRecordType();
4265
4266 // C++ [over.call.object]p1:
4267 // If the primary-expression E in the function call syntax
4268 // evaluates to a class object of type ���cv T���, then the set of
4269 // candidate functions includes at least the function call
4270 // operators of T. The function call operators of T are obtained by
4271 // ordinary lookup of the name operator() in the context of
4272 // (E).operator().
4273 OverloadCandidateSet CandidateSet;
4274 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
4275 DeclContext::lookup_const_iterator Oper, OperEnd;
3842 if (ArgumentDependentLookup)
3843 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
3844 CandidateSet);
3845
3846 OverloadCandidateSet::iterator Best;
3847 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
3848 case OR_Success:
3849 return Best->Function;
3850
3851 case OR_No_Viable_Function:
3852 Diag(Fn->getSourceRange().getBegin(),
3853 diag::err_ovl_no_viable_function_in_call)
3854 << UnqualifiedName << Fn->getSourceRange();
3855 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3856 break;
3857
3858 case OR_Ambiguous:
3859 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
3860 << UnqualifiedName << Fn->getSourceRange();
3861 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3862 break;
3863
3864 case OR_Deleted:
3865 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
3866 << Best->Function->isDeleted()
3867 << UnqualifiedName
3868 << Fn->getSourceRange();
3869 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3870 break;
3871 }
3872
3873 // Overload resolution failed. Destroy all of the subexpressions and
3874 // return NULL.
3875 Fn->Destroy(Context);
3876 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3877 Args[Arg]->Destroy(Context);
3878 return 0;
3879}
3880
3881/// \brief Create a unary operation that may resolve to an overloaded
3882/// operator.
3883///
3884/// \param OpLoc The location of the operator itself (e.g., '*').
3885///
3886/// \param OpcIn The UnaryOperator::Opcode that describes this
3887/// operator.
3888///
3889/// \param Functions The set of non-member functions that will be
3890/// considered by overload resolution. The caller needs to build this
3891/// set based on the context using, e.g.,
3892/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3893/// set should not contain any member functions; those will be added
3894/// by CreateOverloadedUnaryOp().
3895///
3896/// \param input The input argument.
3897Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
3898 unsigned OpcIn,
3899 FunctionSet &Functions,
3900 ExprArg input) {
3901 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
3902 Expr *Input = (Expr *)input.get();
3903
3904 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
3905 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
3906 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3907
3908 Expr *Args[2] = { Input, 0 };
3909 unsigned NumArgs = 1;
3910
3911 // For post-increment and post-decrement, add the implicit '0' as
3912 // the second argument, so that we know this is a post-increment or
3913 // post-decrement.
3914 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
3915 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
3916 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
3917 SourceLocation());
3918 NumArgs = 2;
3919 }
3920
3921 if (Input->isTypeDependent()) {
3922 OverloadedFunctionDecl *Overloads
3923 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3924 for (FunctionSet::iterator Func = Functions.begin(),
3925 FuncEnd = Functions.end();
3926 Func != FuncEnd; ++Func)
3927 Overloads->addOverload(*Func);
3928
3929 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3930 OpLoc, false, false);
3931
3932 input.release();
3933 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3934 &Args[0], NumArgs,
3935 Context.DependentTy,
3936 OpLoc));
3937 }
3938
3939 // Build an empty overload set.
3940 OverloadCandidateSet CandidateSet;
3941
3942 // Add the candidates from the given function set.
3943 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
3944
3945 // Add operator candidates that are member functions.
3946 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
3947
3948 // Add builtin operator candidates.
3949 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
3950
3951 // Perform overload resolution.
3952 OverloadCandidateSet::iterator Best;
3953 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
3954 case OR_Success: {
3955 // We found a built-in operator or an overloaded operator.
3956 FunctionDecl *FnDecl = Best->Function;
3957
3958 if (FnDecl) {
3959 // We matched an overloaded operator. Build a call to that
3960 // operator.
3961
3962 // Convert the arguments.
3963 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3964 if (PerformObjectArgumentInitialization(Input, Method))
3965 return ExprError();
3966 } else {
3967 // Convert the arguments.
3968 if (PerformCopyInitialization(Input,
3969 FnDecl->getParamDecl(0)->getType(),
3970 "passing"))
3971 return ExprError();
3972 }
3973
3974 // Determine the result type
3975 QualType ResultTy
3976 = FnDecl->getType()->getAsFunctionType()->getResultType();
3977 ResultTy = ResultTy.getNonReferenceType();
3978
3979 // Build the actual expression node.
3980 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3981 SourceLocation());
3982 UsualUnaryConversions(FnExpr);
3983
3984 input.release();
3985 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3986 &Input, 1, ResultTy,
3987 OpLoc));
3988 } else {
3989 // We matched a built-in operator. Convert the arguments, then
3990 // break out so that we will build the appropriate built-in
3991 // operator node.
3992 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3993 Best->Conversions[0], "passing"))
3994 return ExprError();
3995
3996 break;
3997 }
3998 }
3999
4000 case OR_No_Viable_Function:
4001 // No viable function; fall through to handling this as a
4002 // built-in operator, which will produce an error message for us.
4003 break;
4004
4005 case OR_Ambiguous:
4006 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4007 << UnaryOperator::getOpcodeStr(Opc)
4008 << Input->getSourceRange();
4009 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4010 return ExprError();
4011
4012 case OR_Deleted:
4013 Diag(OpLoc, diag::err_ovl_deleted_oper)
4014 << Best->Function->isDeleted()
4015 << UnaryOperator::getOpcodeStr(Opc)
4016 << Input->getSourceRange();
4017 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4018 return ExprError();
4019 }
4020
4021 // Either we found no viable overloaded operator or we matched a
4022 // built-in operator. In either case, fall through to trying to
4023 // build a built-in operation.
4024 input.release();
4025 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4026}
4027
4028/// \brief Create a binary operation that may resolve to an overloaded
4029/// operator.
4030///
4031/// \param OpLoc The location of the operator itself (e.g., '+').
4032///
4033/// \param OpcIn The BinaryOperator::Opcode that describes this
4034/// operator.
4035///
4036/// \param Functions The set of non-member functions that will be
4037/// considered by overload resolution. The caller needs to build this
4038/// set based on the context using, e.g.,
4039/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4040/// set should not contain any member functions; those will be added
4041/// by CreateOverloadedBinOp().
4042///
4043/// \param LHS Left-hand argument.
4044/// \param RHS Right-hand argument.
4045Sema::OwningExprResult
4046Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4047 unsigned OpcIn,
4048 FunctionSet &Functions,
4049 Expr *LHS, Expr *RHS) {
4050 Expr *Args[2] = { LHS, RHS };
4051
4052 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4053 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4054 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4055
4056 // If either side is type-dependent, create an appropriate dependent
4057 // expression.
4058 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
4059 // .* cannot be overloaded.
4060 if (Opc == BinaryOperator::PtrMemD)
4061 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
4062 Context.DependentTy, OpLoc));
4063
4064 OverloadedFunctionDecl *Overloads
4065 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4066 for (FunctionSet::iterator Func = Functions.begin(),
4067 FuncEnd = Functions.end();
4068 Func != FuncEnd; ++Func)
4069 Overloads->addOverload(*Func);
4070
4071 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4072 OpLoc, false, false);
4073
4074 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4075 Args, 2,
4076 Context.DependentTy,
4077 OpLoc));
4078 }
4079
4080 // If this is the .* operator, which is not overloadable, just
4081 // create a built-in binary operator.
4082 if (Opc == BinaryOperator::PtrMemD)
4083 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4084
4085 // If this is one of the assignment operators, we only perform
4086 // overload resolution if the left-hand side is a class or
4087 // enumeration type (C++ [expr.ass]p3).
4088 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
4089 !LHS->getType()->isOverloadableType())
4090 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4091
4092 // Build an empty overload set.
4093 OverloadCandidateSet CandidateSet;
4094
4095 // Add the candidates from the given function set.
4096 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4097
4098 // Add operator candidates that are member functions.
4099 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4100
4101 // Add builtin operator candidates.
4102 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4103
4104 // Perform overload resolution.
4105 OverloadCandidateSet::iterator Best;
4106 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4107 case OR_Success: {
4108 // We found a built-in operator or an overloaded operator.
4109 FunctionDecl *FnDecl = Best->Function;
4110
4111 if (FnDecl) {
4112 // We matched an overloaded operator. Build a call to that
4113 // operator.
4114
4115 // Convert the arguments.
4116 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4117 if (PerformObjectArgumentInitialization(LHS, Method) ||
4118 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
4119 "passing"))
4120 return ExprError();
4121 } else {
4122 // Convert the arguments.
4123 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
4124 "passing") ||
4125 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
4126 "passing"))
4127 return ExprError();
4128 }
4129
4130 // Determine the result type
4131 QualType ResultTy
4132 = FnDecl->getType()->getAsFunctionType()->getResultType();
4133 ResultTy = ResultTy.getNonReferenceType();
4134
4135 // Build the actual expression node.
4136 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4137 SourceLocation());
4138 UsualUnaryConversions(FnExpr);
4139
4140 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4141 Args, 2, ResultTy,
4142 OpLoc));
4143 } else {
4144 // We matched a built-in operator. Convert the arguments, then
4145 // break out so that we will build the appropriate built-in
4146 // operator node.
4147 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
4148 Best->Conversions[0], "passing") ||
4149 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
4150 Best->Conversions[1], "passing"))
4151 return ExprError();
4152
4153 break;
4154 }
4155 }
4156
4157 case OR_No_Viable_Function:
4158 // For class as left operand for assignment or compound assigment operator
4159 // do not fall through to handling in built-in, but report that no overloaded
4160 // assignment operator found
4161 if (LHS->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4162 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4163 << BinaryOperator::getOpcodeStr(Opc)
4164 << LHS->getSourceRange() << RHS->getSourceRange();
4165 return ExprError();
4166 }
4167 // No viable function; fall through to handling this as a
4168 // built-in operator, which will produce an error message for us.
4169 break;
4170
4171 case OR_Ambiguous:
4172 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4173 << BinaryOperator::getOpcodeStr(Opc)
4174 << LHS->getSourceRange() << RHS->getSourceRange();
4175 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4176 return ExprError();
4177
4178 case OR_Deleted:
4179 Diag(OpLoc, diag::err_ovl_deleted_oper)
4180 << Best->Function->isDeleted()
4181 << BinaryOperator::getOpcodeStr(Opc)
4182 << LHS->getSourceRange() << RHS->getSourceRange();
4183 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4184 return ExprError();
4185 }
4186
4187 // Either we found no viable overloaded operator or we matched a
4188 // built-in operator. In either case, try to build a built-in
4189 // operation.
4190 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4191}
4192
4193/// BuildCallToMemberFunction - Build a call to a member
4194/// function. MemExpr is the expression that refers to the member
4195/// function (and includes the object parameter), Args/NumArgs are the
4196/// arguments to the function call (not including the object
4197/// parameter). The caller needs to validate that the member
4198/// expression refers to a member function or an overloaded member
4199/// function.
4200Sema::ExprResult
4201Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4202 SourceLocation LParenLoc, Expr **Args,
4203 unsigned NumArgs, SourceLocation *CommaLocs,
4204 SourceLocation RParenLoc) {
4205 // Dig out the member expression. This holds both the object
4206 // argument and the member function we're referring to.
4207 MemberExpr *MemExpr = 0;
4208 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4209 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4210 else
4211 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4212 assert(MemExpr && "Building member call without member expression");
4213
4214 // Extract the object argument.
4215 Expr *ObjectArg = MemExpr->getBase();
4216
4217 CXXMethodDecl *Method = 0;
4218 if (OverloadedFunctionDecl *Ovl
4219 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
4220 // Add overload candidates
4221 OverloadCandidateSet CandidateSet;
4222 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4223 FuncEnd = Ovl->function_end();
4224 Func != FuncEnd; ++Func) {
4225 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
4226 Method = cast<CXXMethodDecl>(*Func);
4227 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4228 /*SuppressUserConversions=*/false);
4229 }
4230
4231 OverloadCandidateSet::iterator Best;
4232 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
4233 case OR_Success:
4234 Method = cast<CXXMethodDecl>(Best->Function);
4235 break;
4236
4237 case OR_No_Viable_Function:
4238 Diag(MemExpr->getSourceRange().getBegin(),
4239 diag::err_ovl_no_viable_member_function_in_call)
4240 << Ovl->getDeclName() << MemExprE->getSourceRange();
4241 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4242 // FIXME: Leaking incoming expressions!
4243 return true;
4244
4245 case OR_Ambiguous:
4246 Diag(MemExpr->getSourceRange().getBegin(),
4247 diag::err_ovl_ambiguous_member_call)
4248 << Ovl->getDeclName() << MemExprE->getSourceRange();
4249 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4250 // FIXME: Leaking incoming expressions!
4251 return true;
4252
4253 case OR_Deleted:
4254 Diag(MemExpr->getSourceRange().getBegin(),
4255 diag::err_ovl_deleted_member_call)
4256 << Best->Function->isDeleted()
4257 << Ovl->getDeclName() << MemExprE->getSourceRange();
4258 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4259 // FIXME: Leaking incoming expressions!
4260 return true;
4261 }
4262
4263 FixOverloadedFunctionReference(MemExpr, Method);
4264 } else {
4265 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4266 }
4267
4268 assert(Method && "Member call to something that isn't a method?");
4269 ExprOwningPtr<CXXMemberCallExpr>
4270 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4271 NumArgs,
4272 Method->getResultType().getNonReferenceType(),
4273 RParenLoc));
4274
4275 // Convert the object argument (for a non-static member function call).
4276 if (!Method->isStatic() &&
4277 PerformObjectArgumentInitialization(ObjectArg, Method))
4278 return true;
4279 MemExpr->setBase(ObjectArg);
4280
4281 // Convert the rest of the arguments
4282 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
4283 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4284 RParenLoc))
4285 return true;
4286
4287 return CheckFunctionCall(Method, TheCall.take()).release();
4288}
4289
4290/// BuildCallToObjectOfClassType - Build a call to an object of class
4291/// type (C++ [over.call.object]), which can end up invoking an
4292/// overloaded function call operator (@c operator()) or performing a
4293/// user-defined conversion on the object argument.
4294Sema::ExprResult
4295Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4296 SourceLocation LParenLoc,
4297 Expr **Args, unsigned NumArgs,
4298 SourceLocation *CommaLocs,
4299 SourceLocation RParenLoc) {
4300 assert(Object->getType()->isRecordType() && "Requires object type argument");
4301 const RecordType *Record = Object->getType()->getAsRecordType();
4302
4303 // C++ [over.call.object]p1:
4304 // If the primary-expression E in the function call syntax
4305 // evaluates to a class object of type ���cv T���, then the set of
4306 // candidate functions includes at least the function call
4307 // operators of T. The function call operators of T are obtained by
4308 // ordinary lookup of the name operator() in the context of
4309 // (E).operator().
4310 OverloadCandidateSet CandidateSet;
4311 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
4312 DeclContext::lookup_const_iterator Oper, OperEnd;
4276 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(Context, OpName);
4313 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
4277 Oper != OperEnd; ++Oper)
4278 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4279 CandidateSet, /*SuppressUserConversions=*/false);
4280
4281 // C++ [over.call.object]p2:
4282 // In addition, for each conversion function declared in T of the
4283 // form
4284 //
4285 // operator conversion-type-id () cv-qualifier;
4286 //
4287 // where cv-qualifier is the same cv-qualification as, or a
4288 // greater cv-qualification than, cv, and where conversion-type-id
4289 // denotes the type "pointer to function of (P1,...,Pn) returning
4290 // R", or the type "reference to pointer to function of
4291 // (P1,...,Pn) returning R", or the type "reference to function
4292 // of (P1,...,Pn) returning R", a surrogate call function [...]
4293 // is also considered as a candidate function. Similarly,
4294 // surrogate call functions are added to the set of candidate
4295 // functions for each conversion function declared in an
4296 // accessible base class provided the function is not hidden
4297 // within T by another intervening declaration.
4298 //
4299 // FIXME: Look in base classes for more conversion operators!
4300 OverloadedFunctionDecl *Conversions
4301 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
4302 for (OverloadedFunctionDecl::function_iterator
4303 Func = Conversions->function_begin(),
4304 FuncEnd = Conversions->function_end();
4305 Func != FuncEnd; ++Func) {
4306 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
4307
4308 // Strip the reference type (if any) and then the pointer type (if
4309 // any) to get down to what might be a function type.
4310 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4311 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
4312 ConvType = ConvPtrType->getPointeeType();
4313
4314 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
4315 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4316 }
4317
4318 // Perform overload resolution.
4319 OverloadCandidateSet::iterator Best;
4320 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
4321 case OR_Success:
4322 // Overload resolution succeeded; we'll build the appropriate call
4323 // below.
4324 break;
4325
4326 case OR_No_Viable_Function:
4327 Diag(Object->getSourceRange().getBegin(),
4328 diag::err_ovl_no_viable_object_call)
4329 << Object->getType() << Object->getSourceRange();
4330 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4331 break;
4332
4333 case OR_Ambiguous:
4334 Diag(Object->getSourceRange().getBegin(),
4335 diag::err_ovl_ambiguous_object_call)
4336 << Object->getType() << Object->getSourceRange();
4337 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4338 break;
4339
4340 case OR_Deleted:
4341 Diag(Object->getSourceRange().getBegin(),
4342 diag::err_ovl_deleted_object_call)
4343 << Best->Function->isDeleted()
4344 << Object->getType() << Object->getSourceRange();
4345 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4346 break;
4347 }
4348
4349 if (Best == CandidateSet.end()) {
4350 // We had an error; delete all of the subexpressions and return
4351 // the error.
4352 Object->Destroy(Context);
4353 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4354 Args[ArgIdx]->Destroy(Context);
4355 return true;
4356 }
4357
4358 if (Best->Function == 0) {
4359 // Since there is no function declaration, this is one of the
4360 // surrogate candidates. Dig out the conversion function.
4361 CXXConversionDecl *Conv
4362 = cast<CXXConversionDecl>(
4363 Best->Conversions[0].UserDefined.ConversionFunction);
4364
4365 // We selected one of the surrogate functions that converts the
4366 // object parameter to a function pointer. Perform the conversion
4367 // on the object argument, then let ActOnCallExpr finish the job.
4368 // FIXME: Represent the user-defined conversion in the AST!
4369 ImpCastExprToType(Object,
4370 Conv->getConversionType().getNonReferenceType(),
4371 Conv->getConversionType()->isLValueReferenceType());
4372 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4373 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4374 CommaLocs, RParenLoc).release();
4375 }
4376
4377 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4378 // that calls this method, using Object for the implicit object
4379 // parameter and passing along the remaining arguments.
4380 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
4381 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
4382
4383 unsigned NumArgsInProto = Proto->getNumArgs();
4384 unsigned NumArgsToCheck = NumArgs;
4385
4386 // Build the full argument list for the method call (the
4387 // implicit object parameter is placed at the beginning of the
4388 // list).
4389 Expr **MethodArgs;
4390 if (NumArgs < NumArgsInProto) {
4391 NumArgsToCheck = NumArgsInProto;
4392 MethodArgs = new Expr*[NumArgsInProto + 1];
4393 } else {
4394 MethodArgs = new Expr*[NumArgs + 1];
4395 }
4396 MethodArgs[0] = Object;
4397 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4398 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4399
4400 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4401 SourceLocation());
4402 UsualUnaryConversions(NewFn);
4403
4404 // Once we've built TheCall, all of the expressions are properly
4405 // owned.
4406 QualType ResultTy = Method->getResultType().getNonReferenceType();
4407 ExprOwningPtr<CXXOperatorCallExpr>
4408 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4409 MethodArgs, NumArgs + 1,
4410 ResultTy, RParenLoc));
4411 delete [] MethodArgs;
4412
4413 // We may have default arguments. If so, we need to allocate more
4414 // slots in the call for them.
4415 if (NumArgs < NumArgsInProto)
4416 TheCall->setNumArgs(Context, NumArgsInProto + 1);
4417 else if (NumArgs > NumArgsInProto)
4418 NumArgsToCheck = NumArgsInProto;
4419
4420 bool IsError = false;
4421
4422 // Initialize the implicit object parameter.
4423 IsError |= PerformObjectArgumentInitialization(Object, Method);
4424 TheCall->setArg(0, Object);
4425
4426
4427 // Check the argument types.
4428 for (unsigned i = 0; i != NumArgsToCheck; i++) {
4429 Expr *Arg;
4430 if (i < NumArgs) {
4431 Arg = Args[i];
4432
4433 // Pass the argument.
4434 QualType ProtoArgType = Proto->getArgType(i);
4435 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
4436 } else {
4437 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
4438 }
4439
4440 TheCall->setArg(i + 1, Arg);
4441 }
4442
4443 // If this is a variadic call, handle args passed through "...".
4444 if (Proto->isVariadic()) {
4445 // Promote the arguments (C99 6.5.2.2p7).
4446 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4447 Expr *Arg = Args[i];
4448 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
4449 TheCall->setArg(i + 1, Arg);
4450 }
4451 }
4452
4453 if (IsError) return true;
4454
4455 return CheckFunctionCall(Method, TheCall.take()).release();
4456}
4457
4458/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4459/// (if one exists), where @c Base is an expression of class type and
4460/// @c Member is the name of the member we're trying to find.
4461Action::ExprResult
4462Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
4463 SourceLocation MemberLoc,
4464 IdentifierInfo &Member) {
4465 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4466
4467 // C++ [over.ref]p1:
4468 //
4469 // [...] An expression x->m is interpreted as (x.operator->())->m
4470 // for a class object x of type T if T::operator->() exists and if
4471 // the operator is selected as the best match function by the
4472 // overload resolution mechanism (13.3).
4473 // FIXME: look in base classes.
4474 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4475 OverloadCandidateSet CandidateSet;
4476 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
4477
4478 DeclContext::lookup_const_iterator Oper, OperEnd;
4479 for (llvm::tie(Oper, OperEnd)
4314 Oper != OperEnd; ++Oper)
4315 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4316 CandidateSet, /*SuppressUserConversions=*/false);
4317
4318 // C++ [over.call.object]p2:
4319 // In addition, for each conversion function declared in T of the
4320 // form
4321 //
4322 // operator conversion-type-id () cv-qualifier;
4323 //
4324 // where cv-qualifier is the same cv-qualification as, or a
4325 // greater cv-qualification than, cv, and where conversion-type-id
4326 // denotes the type "pointer to function of (P1,...,Pn) returning
4327 // R", or the type "reference to pointer to function of
4328 // (P1,...,Pn) returning R", or the type "reference to function
4329 // of (P1,...,Pn) returning R", a surrogate call function [...]
4330 // is also considered as a candidate function. Similarly,
4331 // surrogate call functions are added to the set of candidate
4332 // functions for each conversion function declared in an
4333 // accessible base class provided the function is not hidden
4334 // within T by another intervening declaration.
4335 //
4336 // FIXME: Look in base classes for more conversion operators!
4337 OverloadedFunctionDecl *Conversions
4338 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
4339 for (OverloadedFunctionDecl::function_iterator
4340 Func = Conversions->function_begin(),
4341 FuncEnd = Conversions->function_end();
4342 Func != FuncEnd; ++Func) {
4343 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
4344
4345 // Strip the reference type (if any) and then the pointer type (if
4346 // any) to get down to what might be a function type.
4347 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4348 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
4349 ConvType = ConvPtrType->getPointeeType();
4350
4351 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
4352 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4353 }
4354
4355 // Perform overload resolution.
4356 OverloadCandidateSet::iterator Best;
4357 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
4358 case OR_Success:
4359 // Overload resolution succeeded; we'll build the appropriate call
4360 // below.
4361 break;
4362
4363 case OR_No_Viable_Function:
4364 Diag(Object->getSourceRange().getBegin(),
4365 diag::err_ovl_no_viable_object_call)
4366 << Object->getType() << Object->getSourceRange();
4367 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4368 break;
4369
4370 case OR_Ambiguous:
4371 Diag(Object->getSourceRange().getBegin(),
4372 diag::err_ovl_ambiguous_object_call)
4373 << Object->getType() << Object->getSourceRange();
4374 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4375 break;
4376
4377 case OR_Deleted:
4378 Diag(Object->getSourceRange().getBegin(),
4379 diag::err_ovl_deleted_object_call)
4380 << Best->Function->isDeleted()
4381 << Object->getType() << Object->getSourceRange();
4382 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4383 break;
4384 }
4385
4386 if (Best == CandidateSet.end()) {
4387 // We had an error; delete all of the subexpressions and return
4388 // the error.
4389 Object->Destroy(Context);
4390 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4391 Args[ArgIdx]->Destroy(Context);
4392 return true;
4393 }
4394
4395 if (Best->Function == 0) {
4396 // Since there is no function declaration, this is one of the
4397 // surrogate candidates. Dig out the conversion function.
4398 CXXConversionDecl *Conv
4399 = cast<CXXConversionDecl>(
4400 Best->Conversions[0].UserDefined.ConversionFunction);
4401
4402 // We selected one of the surrogate functions that converts the
4403 // object parameter to a function pointer. Perform the conversion
4404 // on the object argument, then let ActOnCallExpr finish the job.
4405 // FIXME: Represent the user-defined conversion in the AST!
4406 ImpCastExprToType(Object,
4407 Conv->getConversionType().getNonReferenceType(),
4408 Conv->getConversionType()->isLValueReferenceType());
4409 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4410 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4411 CommaLocs, RParenLoc).release();
4412 }
4413
4414 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4415 // that calls this method, using Object for the implicit object
4416 // parameter and passing along the remaining arguments.
4417 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
4418 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
4419
4420 unsigned NumArgsInProto = Proto->getNumArgs();
4421 unsigned NumArgsToCheck = NumArgs;
4422
4423 // Build the full argument list for the method call (the
4424 // implicit object parameter is placed at the beginning of the
4425 // list).
4426 Expr **MethodArgs;
4427 if (NumArgs < NumArgsInProto) {
4428 NumArgsToCheck = NumArgsInProto;
4429 MethodArgs = new Expr*[NumArgsInProto + 1];
4430 } else {
4431 MethodArgs = new Expr*[NumArgs + 1];
4432 }
4433 MethodArgs[0] = Object;
4434 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4435 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4436
4437 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4438 SourceLocation());
4439 UsualUnaryConversions(NewFn);
4440
4441 // Once we've built TheCall, all of the expressions are properly
4442 // owned.
4443 QualType ResultTy = Method->getResultType().getNonReferenceType();
4444 ExprOwningPtr<CXXOperatorCallExpr>
4445 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4446 MethodArgs, NumArgs + 1,
4447 ResultTy, RParenLoc));
4448 delete [] MethodArgs;
4449
4450 // We may have default arguments. If so, we need to allocate more
4451 // slots in the call for them.
4452 if (NumArgs < NumArgsInProto)
4453 TheCall->setNumArgs(Context, NumArgsInProto + 1);
4454 else if (NumArgs > NumArgsInProto)
4455 NumArgsToCheck = NumArgsInProto;
4456
4457 bool IsError = false;
4458
4459 // Initialize the implicit object parameter.
4460 IsError |= PerformObjectArgumentInitialization(Object, Method);
4461 TheCall->setArg(0, Object);
4462
4463
4464 // Check the argument types.
4465 for (unsigned i = 0; i != NumArgsToCheck; i++) {
4466 Expr *Arg;
4467 if (i < NumArgs) {
4468 Arg = Args[i];
4469
4470 // Pass the argument.
4471 QualType ProtoArgType = Proto->getArgType(i);
4472 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
4473 } else {
4474 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
4475 }
4476
4477 TheCall->setArg(i + 1, Arg);
4478 }
4479
4480 // If this is a variadic call, handle args passed through "...".
4481 if (Proto->isVariadic()) {
4482 // Promote the arguments (C99 6.5.2.2p7).
4483 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4484 Expr *Arg = Args[i];
4485 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
4486 TheCall->setArg(i + 1, Arg);
4487 }
4488 }
4489
4490 if (IsError) return true;
4491
4492 return CheckFunctionCall(Method, TheCall.take()).release();
4493}
4494
4495/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4496/// (if one exists), where @c Base is an expression of class type and
4497/// @c Member is the name of the member we're trying to find.
4498Action::ExprResult
4499Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
4500 SourceLocation MemberLoc,
4501 IdentifierInfo &Member) {
4502 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4503
4504 // C++ [over.ref]p1:
4505 //
4506 // [...] An expression x->m is interpreted as (x.operator->())->m
4507 // for a class object x of type T if T::operator->() exists and if
4508 // the operator is selected as the best match function by the
4509 // overload resolution mechanism (13.3).
4510 // FIXME: look in base classes.
4511 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4512 OverloadCandidateSet CandidateSet;
4513 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
4514
4515 DeclContext::lookup_const_iterator Oper, OperEnd;
4516 for (llvm::tie(Oper, OperEnd)
4480 = BaseRecord->getDecl()->lookup(Context, OpName);
4481 Oper != OperEnd; ++Oper)
4517 = BaseRecord->getDecl()->lookup(OpName); Oper != OperEnd; ++Oper)
4482 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
4483 /*SuppressUserConversions=*/false);
4484
4485 ExprOwningPtr<Expr> BasePtr(this, Base);
4486
4487 // Perform overload resolution.
4488 OverloadCandidateSet::iterator Best;
4489 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4490 case OR_Success:
4491 // Overload resolution succeeded; we'll build the call below.
4492 break;
4493
4494 case OR_No_Viable_Function:
4495 if (CandidateSet.empty())
4496 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
4497 << BasePtr->getType() << BasePtr->getSourceRange();
4498 else
4499 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4500 << "operator->" << BasePtr->getSourceRange();
4501 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4502 return true;
4503
4504 case OR_Ambiguous:
4505 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4506 << "operator->" << BasePtr->getSourceRange();
4507 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4508 return true;
4509
4510 case OR_Deleted:
4511 Diag(OpLoc, diag::err_ovl_deleted_oper)
4512 << Best->Function->isDeleted()
4513 << "operator->" << BasePtr->getSourceRange();
4514 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4515 return true;
4516 }
4517
4518 // Convert the object parameter.
4519 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
4520 if (PerformObjectArgumentInitialization(Base, Method))
4521 return true;
4522
4523 // No concerns about early exits now.
4524 BasePtr.take();
4525
4526 // Build the operator call.
4527 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4528 SourceLocation());
4529 UsualUnaryConversions(FnExpr);
4530 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
4531 Method->getResultType().getNonReferenceType(),
4532 OpLoc);
4533 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
4534 MemberLoc, Member, DeclPtrTy()).release();
4535}
4536
4537/// FixOverloadedFunctionReference - E is an expression that refers to
4538/// a C++ overloaded function (possibly with some parentheses and
4539/// perhaps a '&' around it). We have resolved the overloaded function
4540/// to the function declaration Fn, so patch up the expression E to
4541/// refer (possibly indirectly) to Fn.
4542void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4543 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4544 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4545 E->setType(PE->getSubExpr()->getType());
4546 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4547 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4548 "Can only take the address of an overloaded function");
4549 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4550 if (Method->isStatic()) {
4551 // Do nothing: static member functions aren't any different
4552 // from non-member functions.
4553 }
4554 else if (QualifiedDeclRefExpr *DRE
4555 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4556 // We have taken the address of a pointer to member
4557 // function. Perform the computation here so that we get the
4558 // appropriate pointer to member type.
4559 DRE->setDecl(Fn);
4560 DRE->setType(Fn->getType());
4561 QualType ClassType
4562 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4563 E->setType(Context.getMemberPointerType(Fn->getType(),
4564 ClassType.getTypePtr()));
4565 return;
4566 }
4567 }
4568 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
4569 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
4570 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
4571 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
4572 "Expected overloaded function");
4573 DR->setDecl(Fn);
4574 E->setType(Fn->getType());
4575 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4576 MemExpr->setMemberDecl(Fn);
4577 E->setType(Fn->getType());
4578 } else {
4579 assert(false && "Invalid reference to overloaded function");
4580 }
4581}
4582
4583} // end namespace clang
4518 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
4519 /*SuppressUserConversions=*/false);
4520
4521 ExprOwningPtr<Expr> BasePtr(this, Base);
4522
4523 // Perform overload resolution.
4524 OverloadCandidateSet::iterator Best;
4525 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4526 case OR_Success:
4527 // Overload resolution succeeded; we'll build the call below.
4528 break;
4529
4530 case OR_No_Viable_Function:
4531 if (CandidateSet.empty())
4532 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
4533 << BasePtr->getType() << BasePtr->getSourceRange();
4534 else
4535 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4536 << "operator->" << BasePtr->getSourceRange();
4537 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4538 return true;
4539
4540 case OR_Ambiguous:
4541 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4542 << "operator->" << BasePtr->getSourceRange();
4543 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4544 return true;
4545
4546 case OR_Deleted:
4547 Diag(OpLoc, diag::err_ovl_deleted_oper)
4548 << Best->Function->isDeleted()
4549 << "operator->" << BasePtr->getSourceRange();
4550 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4551 return true;
4552 }
4553
4554 // Convert the object parameter.
4555 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
4556 if (PerformObjectArgumentInitialization(Base, Method))
4557 return true;
4558
4559 // No concerns about early exits now.
4560 BasePtr.take();
4561
4562 // Build the operator call.
4563 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4564 SourceLocation());
4565 UsualUnaryConversions(FnExpr);
4566 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
4567 Method->getResultType().getNonReferenceType(),
4568 OpLoc);
4569 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
4570 MemberLoc, Member, DeclPtrTy()).release();
4571}
4572
4573/// FixOverloadedFunctionReference - E is an expression that refers to
4574/// a C++ overloaded function (possibly with some parentheses and
4575/// perhaps a '&' around it). We have resolved the overloaded function
4576/// to the function declaration Fn, so patch up the expression E to
4577/// refer (possibly indirectly) to Fn.
4578void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4579 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4580 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4581 E->setType(PE->getSubExpr()->getType());
4582 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4583 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4584 "Can only take the address of an overloaded function");
4585 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4586 if (Method->isStatic()) {
4587 // Do nothing: static member functions aren't any different
4588 // from non-member functions.
4589 }
4590 else if (QualifiedDeclRefExpr *DRE
4591 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4592 // We have taken the address of a pointer to member
4593 // function. Perform the computation here so that we get the
4594 // appropriate pointer to member type.
4595 DRE->setDecl(Fn);
4596 DRE->setType(Fn->getType());
4597 QualType ClassType
4598 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4599 E->setType(Context.getMemberPointerType(Fn->getType(),
4600 ClassType.getTypePtr()));
4601 return;
4602 }
4603 }
4604 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
4605 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
4606 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
4607 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
4608 "Expected overloaded function");
4609 DR->setDecl(Fn);
4610 E->setType(Fn->getType());
4611 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4612 MemExpr->setMemberDecl(Fn);
4613 E->setType(Fn->getType());
4614 } else {
4615 assert(false && "Invalid reference to overloaded function");
4616 }
4617}
4618
4619} // end namespace clang