blob: 0fba0c62281c2bdea58b977013dbec26f7f49aa9 [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor4c2458a2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000082 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000083 ICR_Conversion
84 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +000091 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000092 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor60d62c22008-10-31 16:23:19 +0000115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118 First = ICK_Identity;
119 Second = ICK_Identity;
120 Third = ICK_Identity;
121 Deprecated = false;
122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000126}
127
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132 ImplicitConversionRank Rank = ICR_Exact_Match;
133 if (GetConversionRank(First) > Rank)
134 Rank = GetConversionRank(First);
135 if (GetConversionRank(Second) > Rank)
136 Rank = GetConversionRank(Second);
137 if (GetConversionRank(Third) > Rank)
138 Rank = GetConversionRank(Third);
139 return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
John McCall1d318332010-01-12 00:44:57 +0000151 if (getToType()->isBooleanType() &&
152 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000163bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000166 QualType FromType = getFromType();
167 QualType ToType = getToType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000168
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
Douglas Gregor01919692009-12-13 21:37:05 +0000175 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000185 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000188 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000194 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000195 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000199 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000200 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000201 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000202 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000203 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000204 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000210 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000211 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000212 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000217 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000227 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000228 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000229 OS << "'" << ConversionFunction->getNameAsString() << "'";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000231 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000232 After.DebugPrint();
233 }
234}
235
236/// DebugPrint - Print this implicit conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000239 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000240 switch (ConversionKind) {
241 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000242 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000243 Standard.DebugPrint();
244 break;
245 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000246 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000247 UserDefined.DebugPrint();
248 break;
249 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000250 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000251 break;
John McCall1d318332010-01-12 00:44:57 +0000252 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000253 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000254 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000255 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000256 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000257 break;
258 }
259
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000260 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000261}
262
John McCall1d318332010-01-12 00:44:57 +0000263void AmbiguousConversionSequence::construct() {
264 new (&conversions()) ConversionSet();
265}
266
267void AmbiguousConversionSequence::destruct() {
268 conversions().~ConversionSet();
269}
270
271void
272AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
273 FromTypePtr = O.FromTypePtr;
274 ToTypePtr = O.ToTypePtr;
275 new (&conversions()) ConversionSet(O.conversions());
276}
277
278
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000279// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000280// overload of the declarations in Old. This routine returns false if
281// New and Old cannot be overloaded, e.g., if New has the same
282// signature as some function in Old (C++ 1.3.10) or if the Old
283// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000284// it does return false, MatchedDecl will point to the decl that New
285// cannot be overloaded with. This decl may be a UsingShadowDecl on
286// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000287//
288// Example: Given the following input:
289//
290// void f(int, float); // #1
291// void f(int, int); // #2
292// int f(int, int); // #3
293//
294// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000295// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000296//
John McCall51fa86f2009-12-02 08:47:38 +0000297// When we process #2, Old contains only the FunctionDecl for #1. By
298// comparing the parameter types, we see that #1 and #2 are overloaded
299// (since they have different signatures), so this routine returns
300// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000301//
John McCall51fa86f2009-12-02 08:47:38 +0000302// When we process #3, Old is an overload set containing #1 and #2. We
303// compare the signatures of #3 to #1 (they're overloaded, so we do
304// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
305// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000306// signature), IsOverload returns false and MatchedDecl will be set to
307// point to the FunctionDecl for #2.
John McCall871b2e72009-12-09 03:35:25 +0000308Sema::OverloadKind
John McCall9f54ad42009-12-10 09:41:52 +0000309Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
310 NamedDecl *&Match) {
John McCall51fa86f2009-12-02 08:47:38 +0000311 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000312 I != E; ++I) {
John McCall51fa86f2009-12-02 08:47:38 +0000313 NamedDecl *OldD = (*I)->getUnderlyingDecl();
314 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000315 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCall871b2e72009-12-09 03:35:25 +0000316 Match = *I;
317 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000318 }
John McCall51fa86f2009-12-02 08:47:38 +0000319 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000320 if (!IsOverload(New, OldF)) {
John McCall871b2e72009-12-09 03:35:25 +0000321 Match = *I;
322 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000323 }
John McCall9f54ad42009-12-10 09:41:52 +0000324 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
325 // We can overload with these, which can show up when doing
326 // redeclaration checks for UsingDecls.
327 assert(Old.getLookupKind() == LookupUsingDeclName);
328 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
329 // Optimistically assume that an unresolved using decl will
330 // overload; if it doesn't, we'll have to diagnose during
331 // template instantiation.
332 } else {
John McCall68263142009-11-18 22:49:29 +0000333 // (C++ 13p1):
334 // Only function declarations can be overloaded; object and type
335 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000336 Match = *I;
337 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000338 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000339 }
John McCall68263142009-11-18 22:49:29 +0000340
John McCall871b2e72009-12-09 03:35:25 +0000341 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000342}
343
344bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
345 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
346 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
347
348 // C++ [temp.fct]p2:
349 // A function template can be overloaded with other function templates
350 // and with normal (non-template) functions.
351 if ((OldTemplate == 0) != (NewTemplate == 0))
352 return true;
353
354 // Is the function New an overload of the function Old?
355 QualType OldQType = Context.getCanonicalType(Old->getType());
356 QualType NewQType = Context.getCanonicalType(New->getType());
357
358 // Compare the signatures (C++ 1.3.10) of the two functions to
359 // determine whether they are overloads. If we find any mismatch
360 // in the signature, they are overloads.
361
362 // If either of these functions is a K&R-style function (no
363 // prototype), then we consider them to have matching signatures.
364 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
365 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
366 return false;
367
368 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
369 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
370
371 // The signature of a function includes the types of its
372 // parameters (C++ 1.3.10), which includes the presence or absence
373 // of the ellipsis; see C++ DR 357).
374 if (OldQType != NewQType &&
375 (OldType->getNumArgs() != NewType->getNumArgs() ||
376 OldType->isVariadic() != NewType->isVariadic() ||
377 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
378 NewType->arg_type_begin())))
379 return true;
380
381 // C++ [temp.over.link]p4:
382 // The signature of a function template consists of its function
383 // signature, its return type and its template parameter list. The names
384 // of the template parameters are significant only for establishing the
385 // relationship between the template parameters and the rest of the
386 // signature.
387 //
388 // We check the return type and template parameter lists for function
389 // templates first; the remaining checks follow.
390 if (NewTemplate &&
391 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
392 OldTemplate->getTemplateParameters(),
393 false, TPL_TemplateMatch) ||
394 OldType->getResultType() != NewType->getResultType()))
395 return true;
396
397 // If the function is a class member, its signature includes the
398 // cv-qualifiers (if any) on the function itself.
399 //
400 // As part of this, also check whether one of the member functions
401 // is static, in which case they are not overloads (C++
402 // 13.1p2). While not part of the definition of the signature,
403 // this check is important to determine whether these functions
404 // can be overloaded.
405 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
406 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
407 if (OldMethod && NewMethod &&
408 !OldMethod->isStatic() && !NewMethod->isStatic() &&
409 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
410 return true;
411
412 // The signatures match; this is not an overload.
413 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000414}
415
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000416/// TryImplicitConversion - Attempt to perform an implicit conversion
417/// from the given expression (Expr) to the given type (ToType). This
418/// function returns an implicit conversion sequence that can be used
419/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000420///
421/// void f(float f);
422/// void g(int i) { f(i); }
423///
424/// this routine would produce an implicit conversion sequence to
425/// describe the initialization of f from i, which will be a standard
426/// conversion sequence containing an lvalue-to-rvalue conversion (C++
427/// 4.1) followed by a floating-integral conversion (C++ 4.9).
428//
429/// Note that this routine only determines how the conversion can be
430/// performed; it does not actually perform the conversion. As such,
431/// it will not produce any diagnostics if no conversion is available,
432/// but will instead return an implicit conversion sequence of kind
433/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000434///
435/// If @p SuppressUserConversions, then user-defined conversions are
436/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000437/// If @p AllowExplicit, then explicit user-defined conversions are
438/// permitted.
Sebastian Redle2b68332009-04-12 17:16:29 +0000439/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
440/// no matter its actual lvalueness.
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000441/// If @p UserCast, the implicit conversion is being done for a user-specified
442/// cast.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000443ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000444Sema::TryImplicitConversion(Expr* From, QualType ToType,
445 bool SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +0000446 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000447 bool InOverloadResolution,
448 bool UserCast) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000449 ImplicitConversionSequence ICS;
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000450 OverloadCandidateSet Conversions;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000451 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson08972922009-08-28 15:33:32 +0000452 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
John McCall1d318332010-01-12 00:44:57 +0000453 ICS.setStandard();
Douglas Gregorf9201e02009-02-11 23:02:49 +0000454 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000455 (UserDefResult = IsUserDefinedConversion(From, ToType,
456 ICS.UserDefined,
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000457 Conversions,
Sebastian Redle2b68332009-04-12 17:16:29 +0000458 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000459 ForceRValue, UserCast)) == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000460 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000461 // C++ [over.ics.user]p4:
462 // A conversion of an expression of class type to the same class
463 // type is given Exact Match rank, and a conversion of an
464 // expression of class type to a base class of that type is
465 // given Conversion rank, in spite of the fact that a copy
466 // constructor (i.e., a user-defined conversion function) is
467 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000468 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000469 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000470 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000471 = Context.getCanonicalType(From->getType().getUnqualifiedType());
472 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000473 if (Constructor->isCopyConstructor() &&
Douglas Gregor0d6d12b2009-12-22 00:21:20 +0000474 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000475 // Turn this into a "standard" conversion sequence, so that it
476 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000477 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000478 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000479 ICS.Standard.setFromType(From->getType());
480 ICS.Standard.setToType(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000481 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000482 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000483 ICS.Standard.Second = ICK_Derived_To_Base;
484 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000485 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000486
487 // C++ [over.best.ics]p4:
488 // However, when considering the argument of a user-defined
489 // conversion function that is a candidate by 13.3.1.3 when
490 // invoked for the copying of the temporary in the second step
491 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
492 // 13.3.1.6 in all cases, only standard conversion sequences and
493 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000494 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall1d318332010-01-12 00:44:57 +0000495 ICS.setBad();
John McCalladbb8f82010-01-13 09:16:55 +0000496 ICS.Bad.init(BadConversionSequence::suppressed_user, From, ToType);
497 }
John McCallcefd3ad2010-01-13 22:30:33 +0000498 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000499 ICS.setAmbiguous();
500 ICS.Ambiguous.setFromType(From->getType());
501 ICS.Ambiguous.setToType(ToType);
502 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
503 Cand != Conversions.end(); ++Cand)
504 if (Cand->Viable)
505 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000506 } else {
John McCall1d318332010-01-12 00:44:57 +0000507 ICS.setBad();
John McCalladbb8f82010-01-13 09:16:55 +0000508 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000509 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000510
511 return ICS;
512}
513
Douglas Gregor43c79c22009-12-09 00:47:37 +0000514/// \brief Determine whether the conversion from FromType to ToType is a valid
515/// conversion that strips "noreturn" off the nested function type.
516static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
517 QualType ToType, QualType &ResultTy) {
518 if (Context.hasSameUnqualifiedType(FromType, ToType))
519 return false;
520
521 // Strip the noreturn off the type we're converting from; noreturn can
522 // safely be removed.
523 FromType = Context.getNoReturnType(FromType, false);
524 if (!Context.hasSameUnqualifiedType(FromType, ToType))
525 return false;
526
527 ResultTy = FromType;
528 return true;
529}
530
Douglas Gregor60d62c22008-10-31 16:23:19 +0000531/// IsStandardConversion - Determines whether there is a standard
532/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
533/// expression From to the type ToType. Standard conversion sequences
534/// only consider non-class types; for conversions that involve class
535/// types, use TryImplicitConversion. If a conversion exists, SCS will
536/// contain the standard conversion sequence required to perform this
537/// conversion and this routine will return true. Otherwise, this
538/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000539bool
540Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000541 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000542 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000543 QualType FromType = From->getType();
544
Douglas Gregor60d62c22008-10-31 16:23:19 +0000545 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000546 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000547 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000548 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000549 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000550 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000551
Douglas Gregorf9201e02009-02-11 23:02:49 +0000552 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000553 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000554 if (FromType->isRecordType() || ToType->isRecordType()) {
555 if (getLangOptions().CPlusPlus)
556 return false;
557
Mike Stump1eb44332009-09-09 15:08:12 +0000558 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000559 }
560
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000561 // The first conversion can be an lvalue-to-rvalue conversion,
562 // array-to-pointer conversion, or function-to-pointer conversion
563 // (C++ 4p1).
564
Mike Stump1eb44332009-09-09 15:08:12 +0000565 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000566 // An lvalue (3.10) of a non-function, non-array type T can be
567 // converted to an rvalue.
568 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000569 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000570 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000571 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000572 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000573
574 // If T is a non-class type, the type of the rvalue is the
575 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000576 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
577 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000578 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000579 } else if (FromType->isArrayType()) {
580 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000581 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000582
583 // An lvalue or rvalue of type "array of N T" or "array of unknown
584 // bound of T" can be converted to an rvalue of type "pointer to
585 // T" (C++ 4.2p1).
586 FromType = Context.getArrayDecayedType(FromType);
587
588 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
589 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000590 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000591
592 // For the purpose of ranking in overload resolution
593 // (13.3.3.1.1), this conversion is considered an
594 // array-to-pointer conversion followed by a qualification
595 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000596 SCS.Second = ICK_Identity;
597 SCS.Third = ICK_Qualification;
John McCall1d318332010-01-12 00:44:57 +0000598 SCS.setToType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000599 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000600 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000601 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
602 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000603 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000604
605 // An lvalue of function type T can be converted to an rvalue of
606 // type "pointer to T." The result is a pointer to the
607 // function. (C++ 4.3p1).
608 FromType = Context.getPointerType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000609 } else if (FunctionDecl *Fn
Douglas Gregor43c79c22009-12-09 00:47:37 +0000610 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000611 // Address of overloaded function (C++ [over.over]).
Douglas Gregor904eed32008-11-10 20:40:00 +0000612 SCS.First = ICK_Function_To_Pointer;
613
614 // We were able to resolve the address of the overloaded function,
615 // so we can convert to the type of that function.
616 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000617 if (ToType->isLValueReferenceType())
618 FromType = Context.getLValueReferenceType(FromType);
619 else if (ToType->isRValueReferenceType())
620 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000621 else if (ToType->isMemberPointerType()) {
622 // Resolve address only succeeds if both sides are member pointers,
623 // but it doesn't have to be the same class. See DR 247.
624 // Note that this means that the type of &Derived::fn can be
625 // Ret (Base::*)(Args) if the fn overload actually found is from the
626 // base class, even if it was brought into the derived class via a
627 // using declaration. The standard isn't clear on this issue at all.
628 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
629 FromType = Context.getMemberPointerType(FromType,
630 Context.getTypeDeclType(M->getParent()).getTypePtr());
631 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000632 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000633 } else {
634 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000635 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000636 }
637
638 // The second conversion can be an integral promotion, floating
639 // point promotion, integral conversion, floating point conversion,
640 // floating-integral conversion, pointer conversion,
641 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000642 // For overloading in C, this can also be a "compatible-type"
643 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000644 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000645 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000646 // The unqualified versions of the types are the same: there's no
647 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000648 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000649 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000650 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000651 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000652 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000653 } else if (IsFloatingPointPromotion(FromType, ToType)) {
654 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000655 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000656 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000657 } else if (IsComplexPromotion(FromType, ToType)) {
658 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000659 SCS.Second = ICK_Complex_Promotion;
660 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000661 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000662 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000663 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000664 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000665 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000666 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
667 // Floating point conversions (C++ 4.8).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000668 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000669 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000670 } else if (FromType->isComplexType() && ToType->isComplexType()) {
671 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000672 SCS.Second = ICK_Complex_Conversion;
673 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000674 } else if ((FromType->isFloatingType() &&
675 ToType->isIntegralType() && (!ToType->isBooleanType() &&
676 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000677 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000678 ToType->isFloatingType())) {
679 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000680 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000681 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000682 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
683 (ToType->isComplexType() && FromType->isArithmeticType())) {
684 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000685 SCS.Second = ICK_Complex_Real;
686 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000687 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
688 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000689 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000690 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000691 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000692 } else if (IsMemberPointerConversion(From, FromType, ToType,
693 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000694 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000695 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000696 } else if (ToType->isBooleanType() &&
697 (FromType->isArithmeticType() ||
698 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +0000699 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000700 FromType->isBlockPointerType() ||
701 FromType->isMemberPointerType() ||
702 FromType->isNullPtrType())) {
703 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000704 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000705 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000706 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000707 Context.typesAreCompatible(ToType, FromType)) {
708 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000709 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000710 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
711 // Treat a conversion that strips "noreturn" as an identity conversion.
712 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000713 } else {
714 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000715 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000716 }
717
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000718 QualType CanonFrom;
719 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000720 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000721 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000722 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000723 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000724 CanonFrom = Context.getCanonicalType(FromType);
725 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000726 } else {
727 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000728 SCS.Third = ICK_Identity;
729
Mike Stump1eb44332009-09-09 15:08:12 +0000730 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000731 // [...] Any difference in top-level cv-qualification is
732 // subsumed by the initialization itself and does not constitute
733 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000734 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000735 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +0000736 if (CanonFrom.getLocalUnqualifiedType()
737 == CanonTo.getLocalUnqualifiedType() &&
738 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000739 FromType = ToType;
740 CanonFrom = CanonTo;
741 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000742 }
743
744 // If we have not converted the argument type to the parameter type,
745 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000746 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000747 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000748
John McCall1d318332010-01-12 00:44:57 +0000749 SCS.setToType(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000750 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000751}
752
753/// IsIntegralPromotion - Determines whether the conversion from the
754/// expression From (whose potentially-adjusted type is FromType) to
755/// ToType is an integral promotion (C++ 4.5). If so, returns true and
756/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000757bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000758 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000759 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000760 if (!To) {
761 return false;
762 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000763
764 // An rvalue of type char, signed char, unsigned char, short int, or
765 // unsigned short int can be converted to an rvalue of type int if
766 // int can represent all the values of the source type; otherwise,
767 // the source rvalue can be converted to an rvalue of type unsigned
768 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000769 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000770 if (// We can promote any signed, promotable integer type to an int
771 (FromType->isSignedIntegerType() ||
772 // We can promote any unsigned integer type whose size is
773 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +0000774 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000775 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000776 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000777 }
778
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000779 return To->getKind() == BuiltinType::UInt;
780 }
781
782 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
783 // can be converted to an rvalue of the first of the following types
784 // that can represent all the values of its underlying type: int,
785 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +0000786
787 // We pre-calculate the promotion type for enum types.
788 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
789 if (ToType->isIntegerType())
790 return Context.hasSameUnqualifiedType(ToType,
791 FromEnumType->getDecl()->getPromotionType());
792
793 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000794 // Determine whether the type we're converting from is signed or
795 // unsigned.
796 bool FromIsSigned;
797 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +0000798
799 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
800 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000801
802 // The types we'll try to promote to, in the appropriate
803 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +0000804 QualType PromoteTypes[6] = {
805 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000806 Context.LongTy, Context.UnsignedLongTy ,
807 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000808 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000809 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000810 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
811 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000812 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000813 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
814 // We found the type that we can promote to. If this is the
815 // type we wanted, we have a promotion. Otherwise, no
816 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000817 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000818 }
819 }
820 }
821
822 // An rvalue for an integral bit-field (9.6) can be converted to an
823 // rvalue of type int if int can represent all the values of the
824 // bit-field; otherwise, it can be converted to unsigned int if
825 // unsigned int can represent all the values of the bit-field. If
826 // the bit-field is larger yet, no integral promotion applies to
827 // it. If the bit-field has an enumerated type, it is treated as any
828 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000829 // FIXME: We should delay checking of bit-fields until we actually perform the
830 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000831 using llvm::APSInt;
832 if (From)
833 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000834 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000835 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
836 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
837 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
838 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Douglas Gregor86f19402008-12-20 23:49:58 +0000840 // Are we promoting to an int from a bitfield that fits in an int?
841 if (BitWidth < ToSize ||
842 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
843 return To->getKind() == BuiltinType::Int;
844 }
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Douglas Gregor86f19402008-12-20 23:49:58 +0000846 // Are we promoting to an unsigned int from an unsigned bitfield
847 // that fits into an unsigned int?
848 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
849 return To->getKind() == BuiltinType::UInt;
850 }
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Douglas Gregor86f19402008-12-20 23:49:58 +0000852 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000853 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000854 }
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000856 // An rvalue of type bool can be converted to an rvalue of type int,
857 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000858 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000859 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000860 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000861
862 return false;
863}
864
865/// IsFloatingPointPromotion - Determines whether the conversion from
866/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
867/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000868bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000869 /// An rvalue of type float can be converted to an rvalue of type
870 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +0000871 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
872 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000873 if (FromBuiltin->getKind() == BuiltinType::Float &&
874 ToBuiltin->getKind() == BuiltinType::Double)
875 return true;
876
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000877 // C99 6.3.1.5p1:
878 // When a float is promoted to double or long double, or a
879 // double is promoted to long double [...].
880 if (!getLangOptions().CPlusPlus &&
881 (FromBuiltin->getKind() == BuiltinType::Float ||
882 FromBuiltin->getKind() == BuiltinType::Double) &&
883 (ToBuiltin->getKind() == BuiltinType::LongDouble))
884 return true;
885 }
886
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000887 return false;
888}
889
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000890/// \brief Determine if a conversion is a complex promotion.
891///
892/// A complex promotion is defined as a complex -> complex conversion
893/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000894/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000895bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000896 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000897 if (!FromComplex)
898 return false;
899
John McCall183700f2009-09-21 23:43:11 +0000900 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000901 if (!ToComplex)
902 return false;
903
904 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000905 ToComplex->getElementType()) ||
906 IsIntegralPromotion(0, FromComplex->getElementType(),
907 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000908}
909
Douglas Gregorcb7de522008-11-26 23:31:11 +0000910/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
911/// the pointer type FromPtr to a pointer to type ToPointee, with the
912/// same type qualifiers as FromPtr has on its pointee type. ToType,
913/// if non-empty, will be a pointer to ToType that may or may not have
914/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000915static QualType
916BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000917 QualType ToPointee, QualType ToType,
918 ASTContext &Context) {
919 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
920 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +0000921 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000922
923 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000924 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +0000925 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +0000926 if (!ToType.isNull())
Douglas Gregorcb7de522008-11-26 23:31:11 +0000927 return ToType;
928
929 // Build a pointer to ToPointee. It has the right qualifiers
930 // already.
931 return Context.getPointerType(ToPointee);
932 }
933
934 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +0000935 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +0000936 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
937 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +0000938}
939
Fariborz Jahanianadcfab12009-12-16 23:13:33 +0000940/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
941/// the FromType, which is an objective-c pointer, to ToType, which may or may
942/// not have the right set of qualifiers.
943static QualType
944BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
945 QualType ToType,
946 ASTContext &Context) {
947 QualType CanonFromType = Context.getCanonicalType(FromType);
948 QualType CanonToType = Context.getCanonicalType(ToType);
949 Qualifiers Quals = CanonFromType.getQualifiers();
950
951 // Exact qualifier match -> return the pointer type we're converting to.
952 if (CanonToType.getLocalQualifiers() == Quals)
953 return ToType;
954
955 // Just build a canonical type that has the right qualifiers.
956 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
957}
958
Mike Stump1eb44332009-09-09 15:08:12 +0000959static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000960 bool InOverloadResolution,
961 ASTContext &Context) {
962 // Handle value-dependent integral null pointer constants correctly.
963 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
964 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
965 Expr->getType()->isIntegralType())
966 return !InOverloadResolution;
967
Douglas Gregorce940492009-09-25 04:25:58 +0000968 return Expr->isNullPointerConstant(Context,
969 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
970 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000971}
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000973/// IsPointerConversion - Determines whether the conversion of the
974/// expression From, which has the (possibly adjusted) type FromType,
975/// can be converted to the type ToType via a pointer conversion (C++
976/// 4.10). If so, returns true and places the converted type (that
977/// might differ from ToType in its cv-qualifiers at some level) into
978/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000979///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000980/// This routine also supports conversions to and from block pointers
981/// and conversions with Objective-C's 'id', 'id<protocols...>', and
982/// pointers to interfaces. FIXME: Once we've determined the
983/// appropriate overloading rules for Objective-C, we may want to
984/// split the Objective-C checks into a different routine; however,
985/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000986/// conversions, so for now they live here. IncompatibleObjC will be
987/// set if the conversion is an allowed Objective-C conversion that
988/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000989bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000990 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +0000991 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +0000992 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +0000993 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000994 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
995 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000996
Mike Stump1eb44332009-09-09 15:08:12 +0000997 // Conversion from a null pointer constant to any Objective-C pointer type.
998 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000999 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001000 ConvertedType = ToType;
1001 return true;
1002 }
1003
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001004 // Blocks: Block pointers can be converted to void*.
1005 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001006 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001007 ConvertedType = ToType;
1008 return true;
1009 }
1010 // Blocks: A null pointer constant can be converted to a block
1011 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001012 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001013 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001014 ConvertedType = ToType;
1015 return true;
1016 }
1017
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001018 // If the left-hand-side is nullptr_t, the right side can be a null
1019 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001020 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001021 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001022 ConvertedType = ToType;
1023 return true;
1024 }
1025
Ted Kremenek6217b802009-07-29 21:53:49 +00001026 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001027 if (!ToTypePtr)
1028 return false;
1029
1030 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001031 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001032 ConvertedType = ToType;
1033 return true;
1034 }
Sebastian Redl07779722008-10-31 14:43:28 +00001035
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001036 // Beyond this point, both types need to be pointers
1037 // , including objective-c pointers.
1038 QualType ToPointeeType = ToTypePtr->getPointeeType();
1039 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1040 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1041 ToType, Context);
1042 return true;
1043
1044 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001045 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001046 if (!FromTypePtr)
1047 return false;
1048
1049 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001050
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001051 // An rvalue of type "pointer to cv T," where T is an object type,
1052 // can be converted to an rvalue of type "pointer to cv void" (C++
1053 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +00001054 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001055 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001056 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001057 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001058 return true;
1059 }
1060
Douglas Gregorf9201e02009-02-11 23:02:49 +00001061 // When we're overloading in C, we allow a special kind of pointer
1062 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001063 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001064 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001065 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001066 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001067 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001068 return true;
1069 }
1070
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001071 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001072 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001073 // An rvalue of type "pointer to cv D," where D is a class type,
1074 // can be converted to an rvalue of type "pointer to cv B," where
1075 // B is a base class (clause 10) of D. If B is an inaccessible
1076 // (clause 11) or ambiguous (10.2) base class of D, a program that
1077 // necessitates this conversion is ill-formed. The result of the
1078 // conversion is a pointer to the base class sub-object of the
1079 // derived class object. The null pointer value is converted to
1080 // the null pointer value of the destination type.
1081 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001082 // Note that we do not check for ambiguity or inaccessibility
1083 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001084 if (getLangOptions().CPlusPlus &&
1085 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001086 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001087 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001088 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001089 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001090 ToType, Context);
1091 return true;
1092 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001093
Douglas Gregorc7887512008-12-19 19:13:09 +00001094 return false;
1095}
1096
1097/// isObjCPointerConversion - Determines whether this is an
1098/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1099/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001100bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001101 QualType& ConvertedType,
1102 bool &IncompatibleObjC) {
1103 if (!getLangOptions().ObjC1)
1104 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001105
Steve Naroff14108da2009-07-10 23:34:53 +00001106 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001107 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001108 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001109 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001110
Steve Naroff14108da2009-07-10 23:34:53 +00001111 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001112 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001113 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001114 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001115 ConvertedType = ToType;
1116 return true;
1117 }
1118 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001119 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001120 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001121 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001122 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001123 ConvertedType = ToType;
1124 return true;
1125 }
1126 // Objective C++: We're able to convert from a pointer to an
1127 // interface to a pointer to a different interface.
1128 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1129 ConvertedType = ToType;
1130 return true;
1131 }
1132
1133 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1134 // Okay: this is some kind of implicit downcast of Objective-C
1135 // interfaces, which is permitted. However, we're going to
1136 // complain about it.
1137 IncompatibleObjC = true;
1138 ConvertedType = FromType;
1139 return true;
1140 }
Mike Stump1eb44332009-09-09 15:08:12 +00001141 }
Steve Naroff14108da2009-07-10 23:34:53 +00001142 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001143 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001144 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001145 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001146 else if (const BlockPointerType *ToBlockPtr =
1147 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001148 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001149 // to a block pointer type.
1150 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1151 ConvertedType = ToType;
1152 return true;
1153 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001154 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001155 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001156 else if (FromType->getAs<BlockPointerType>() &&
1157 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1158 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001159 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001160 ConvertedType = ToType;
1161 return true;
1162 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001163 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001164 return false;
1165
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001166 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001167 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001168 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001169 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001170 FromPointeeType = FromBlockPtr->getPointeeType();
1171 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001172 return false;
1173
Douglas Gregorc7887512008-12-19 19:13:09 +00001174 // If we have pointers to pointers, recursively check whether this
1175 // is an Objective-C conversion.
1176 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1177 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1178 IncompatibleObjC)) {
1179 // We always complain about this conversion.
1180 IncompatibleObjC = true;
1181 ConvertedType = ToType;
1182 return true;
1183 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001184 // Allow conversion of pointee being objective-c pointer to another one;
1185 // as in I* to id.
1186 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1187 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1188 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1189 IncompatibleObjC)) {
1190 ConvertedType = ToType;
1191 return true;
1192 }
1193
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001194 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001195 // differences in the argument and result types are in Objective-C
1196 // pointer conversions. If so, we permit the conversion (but
1197 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001198 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001199 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001200 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001201 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001202 if (FromFunctionType && ToFunctionType) {
1203 // If the function types are exactly the same, this isn't an
1204 // Objective-C pointer conversion.
1205 if (Context.getCanonicalType(FromPointeeType)
1206 == Context.getCanonicalType(ToPointeeType))
1207 return false;
1208
1209 // Perform the quick checks that will tell us whether these
1210 // function types are obviously different.
1211 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1212 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1213 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1214 return false;
1215
1216 bool HasObjCConversion = false;
1217 if (Context.getCanonicalType(FromFunctionType->getResultType())
1218 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1219 // Okay, the types match exactly. Nothing to do.
1220 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1221 ToFunctionType->getResultType(),
1222 ConvertedType, IncompatibleObjC)) {
1223 // Okay, we have an Objective-C pointer conversion.
1224 HasObjCConversion = true;
1225 } else {
1226 // Function types are too different. Abort.
1227 return false;
1228 }
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Douglas Gregorc7887512008-12-19 19:13:09 +00001230 // Check argument types.
1231 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1232 ArgIdx != NumArgs; ++ArgIdx) {
1233 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1234 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1235 if (Context.getCanonicalType(FromArgType)
1236 == Context.getCanonicalType(ToArgType)) {
1237 // Okay, the types match exactly. Nothing to do.
1238 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1239 ConvertedType, IncompatibleObjC)) {
1240 // Okay, we have an Objective-C pointer conversion.
1241 HasObjCConversion = true;
1242 } else {
1243 // Argument types are too different. Abort.
1244 return false;
1245 }
1246 }
1247
1248 if (HasObjCConversion) {
1249 // We had an Objective-C conversion. Allow this pointer
1250 // conversion, but complain about it.
1251 ConvertedType = ToType;
1252 IncompatibleObjC = true;
1253 return true;
1254 }
1255 }
1256
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001257 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001258}
1259
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001260/// CheckPointerConversion - Check the pointer conversion from the
1261/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001262/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001263/// conversions for which IsPointerConversion has already returned
1264/// true. It returns true and produces a diagnostic if there was an
1265/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001266bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001267 CastExpr::CastKind &Kind,
1268 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001269 QualType FromType = From->getType();
1270
Ted Kremenek6217b802009-07-29 21:53:49 +00001271 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1272 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001273 QualType FromPointeeType = FromPtrType->getPointeeType(),
1274 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001275
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001276 if (FromPointeeType->isRecordType() &&
1277 ToPointeeType->isRecordType()) {
1278 // We must have a derived-to-base conversion. Check an
1279 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001280 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1281 From->getExprLoc(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001282 From->getSourceRange(),
1283 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001284 return true;
1285
1286 // The conversion was successful.
1287 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001288 }
1289 }
Mike Stump1eb44332009-09-09 15:08:12 +00001290 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001291 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001292 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001293 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001294 // Objective-C++ conversions are always okay.
1295 // FIXME: We should have a different class of conversions for the
1296 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001297 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001298 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001299
Steve Naroff14108da2009-07-10 23:34:53 +00001300 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001301 return false;
1302}
1303
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001304/// IsMemberPointerConversion - Determines whether the conversion of the
1305/// expression From, which has the (possibly adjusted) type FromType, can be
1306/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1307/// If so, returns true and places the converted type (that might differ from
1308/// ToType in its cv-qualifiers at some level) into ConvertedType.
1309bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001310 QualType ToType,
1311 bool InOverloadResolution,
1312 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001313 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001314 if (!ToTypePtr)
1315 return false;
1316
1317 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001318 if (From->isNullPointerConstant(Context,
1319 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1320 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001321 ConvertedType = ToType;
1322 return true;
1323 }
1324
1325 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001326 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001327 if (!FromTypePtr)
1328 return false;
1329
1330 // A pointer to member of B can be converted to a pointer to member of D,
1331 // where D is derived from B (C++ 4.11p2).
1332 QualType FromClass(FromTypePtr->getClass(), 0);
1333 QualType ToClass(ToTypePtr->getClass(), 0);
1334 // FIXME: What happens when these are dependent? Is this function even called?
1335
1336 if (IsDerivedFrom(ToClass, FromClass)) {
1337 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1338 ToClass.getTypePtr());
1339 return true;
1340 }
1341
1342 return false;
1343}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001344
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001345/// CheckMemberPointerConversion - Check the member pointer conversion from the
1346/// expression From to the type ToType. This routine checks for ambiguous or
1347/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1348/// for which IsMemberPointerConversion has already returned true. It returns
1349/// true and produces a diagnostic if there was an error, or returns false
1350/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001351bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001352 CastExpr::CastKind &Kind,
1353 bool IgnoreBaseAccess) {
1354 (void)IgnoreBaseAccess;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001355 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001356 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001357 if (!FromPtrType) {
1358 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001359 assert(From->isNullPointerConstant(Context,
1360 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001361 "Expr must be null pointer constant!");
1362 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001363 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001364 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001365
Ted Kremenek6217b802009-07-29 21:53:49 +00001366 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001367 assert(ToPtrType && "No member pointer cast has a target type "
1368 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001369
Sebastian Redl21593ac2009-01-28 18:33:18 +00001370 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1371 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001372
Sebastian Redl21593ac2009-01-28 18:33:18 +00001373 // FIXME: What about dependent types?
1374 assert(FromClass->isRecordType() && "Pointer into non-class.");
1375 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001376
Douglas Gregora8f32e02009-10-06 17:59:45 +00001377 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1378 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001379 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1380 assert(DerivationOkay &&
1381 "Should not have been called if derivation isn't OK.");
1382 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001383
Sebastian Redl21593ac2009-01-28 18:33:18 +00001384 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1385 getUnqualifiedType())) {
1386 // Derivation is ambiguous. Redo the check to find the exact paths.
1387 Paths.clear();
1388 Paths.setRecordingPaths(true);
1389 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1390 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1391 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001392
Sebastian Redl21593ac2009-01-28 18:33:18 +00001393 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1394 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1395 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1396 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001397 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001398
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001399 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001400 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1401 << FromClass << ToClass << QualType(VBase, 0)
1402 << From->getSourceRange();
1403 return true;
1404 }
1405
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001406 // Must be a base to derived member conversion.
1407 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001408 return false;
1409}
1410
Douglas Gregor98cd5992008-10-21 23:43:52 +00001411/// IsQualificationConversion - Determines whether the conversion from
1412/// an rvalue of type FromType to ToType is a qualification conversion
1413/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001414bool
1415Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001416 FromType = Context.getCanonicalType(FromType);
1417 ToType = Context.getCanonicalType(ToType);
1418
1419 // If FromType and ToType are the same type, this is not a
1420 // qualification conversion.
1421 if (FromType == ToType)
1422 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001423
Douglas Gregor98cd5992008-10-21 23:43:52 +00001424 // (C++ 4.4p4):
1425 // A conversion can add cv-qualifiers at levels other than the first
1426 // in multi-level pointers, subject to the following rules: [...]
1427 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001428 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001429 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001430 // Within each iteration of the loop, we check the qualifiers to
1431 // determine if this still looks like a qualification
1432 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001433 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001434 // until there are no more pointers or pointers-to-members left to
1435 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001436 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001437
1438 // -- for every j > 0, if const is in cv 1,j then const is in cv
1439 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001440 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001441 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Douglas Gregor98cd5992008-10-21 23:43:52 +00001443 // -- if the cv 1,j and cv 2,j are different, then const is in
1444 // every cv for 0 < k < j.
1445 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001446 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001447 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Douglas Gregor98cd5992008-10-21 23:43:52 +00001449 // Keep track of whether all prior cv-qualifiers in the "to" type
1450 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001451 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001452 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001453 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001454
1455 // We are left with FromType and ToType being the pointee types
1456 // after unwrapping the original FromType and ToType the same number
1457 // of types. If we unwrapped any pointers, and if FromType and
1458 // ToType have the same unqualified type (since we checked
1459 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001460 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001461}
1462
Douglas Gregor734d9862009-01-30 23:27:23 +00001463/// Determines whether there is a user-defined conversion sequence
1464/// (C++ [over.ics.user]) that converts expression From to the type
1465/// ToType. If such a conversion exists, User will contain the
1466/// user-defined conversion sequence that performs such a conversion
1467/// and this routine will return true. Otherwise, this routine returns
1468/// false and User is unspecified.
1469///
1470/// \param AllowConversionFunctions true if the conversion should
1471/// consider conversion functions at all. If false, only constructors
1472/// will be considered.
1473///
1474/// \param AllowExplicit true if the conversion should consider C++0x
1475/// "explicit" conversion functions as well as non-explicit conversion
1476/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001477///
1478/// \param ForceRValue true if the expression should be treated as an rvalue
1479/// for overload resolution.
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001480/// \param UserCast true if looking for user defined conversion for a static
1481/// cast.
Douglas Gregor20093b42009-12-09 23:02:17 +00001482OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1483 UserDefinedConversionSequence& User,
1484 OverloadCandidateSet& CandidateSet,
1485 bool AllowConversionFunctions,
1486 bool AllowExplicit,
1487 bool ForceRValue,
1488 bool UserCast) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001489 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001490 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1491 // We're not going to find any constructors.
1492 } else if (CXXRecordDecl *ToRecordDecl
1493 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001494 // C++ [over.match.ctor]p1:
1495 // When objects of class type are direct-initialized (8.5), or
1496 // copy-initialized from an expression of the same or a
1497 // derived class type (8.5), overload resolution selects the
1498 // constructor. [...] For copy-initialization, the candidate
1499 // functions are all the converting constructors (12.3.1) of
1500 // that class. The argument list is the expression-list within
1501 // the parentheses of the initializer.
Douglas Gregor79b680e2009-11-13 18:44:21 +00001502 bool SuppressUserConversions = !UserCast;
1503 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1504 IsDerivedFrom(From->getType(), ToType)) {
1505 SuppressUserConversions = false;
1506 AllowConversionFunctions = false;
1507 }
1508
Mike Stump1eb44332009-09-09 15:08:12 +00001509 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001510 = Context.DeclarationNames.getCXXConstructorName(
1511 Context.getCanonicalType(ToType).getUnqualifiedType());
1512 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001513 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001514 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001515 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00001516 // Find the constructor (which may be a template).
1517 CXXConstructorDecl *Constructor = 0;
1518 FunctionTemplateDecl *ConstructorTmpl
1519 = dyn_cast<FunctionTemplateDecl>(*Con);
1520 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001521 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001522 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1523 else
1524 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001525
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001526 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001527 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001528 if (ConstructorTmpl)
John McCall86820f52010-01-26 01:37:31 +00001529 AddTemplateOverloadCandidate(ConstructorTmpl,
1530 ConstructorTmpl->getAccess(),
1531 /*ExplicitArgs*/ 0,
John McCalld5532b62009-11-23 01:53:49 +00001532 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001533 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001534 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001535 // Allow one user-defined conversion when user specifies a
1536 // From->ToType conversion via an static cast (c-style, etc).
John McCall86820f52010-01-26 01:37:31 +00001537 AddOverloadCandidate(Constructor, Constructor->getAccess(),
1538 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001539 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001540 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001541 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001542 }
1543 }
1544
Douglas Gregor734d9862009-01-30 23:27:23 +00001545 if (!AllowConversionFunctions) {
1546 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001547 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1548 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001549 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001550 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001551 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001552 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001553 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001554 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1555 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00001556 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001557 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001558 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001559 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00001560 NamedDecl *D = *I;
1561 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1562 if (isa<UsingShadowDecl>(D))
1563 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1564
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001565 CXXConversionDecl *Conv;
1566 FunctionTemplateDecl *ConvTemplate;
John McCallba135432009-11-21 08:51:07 +00001567 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001568 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1569 else
John McCallba135432009-11-21 08:51:07 +00001570 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001571
1572 if (AllowExplicit || !Conv->isExplicit()) {
1573 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00001574 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
1575 ActingContext, From, ToType,
1576 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001577 else
John McCall86820f52010-01-26 01:37:31 +00001578 AddConversionCandidate(Conv, I.getAccess(), ActingContext,
1579 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001580 }
1581 }
1582 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001583 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001584
1585 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001586 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001587 case OR_Success:
1588 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001589 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001590 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1591 // C++ [over.ics.user]p1:
1592 // If the user-defined conversion is specified by a
1593 // constructor (12.3.1), the initial standard conversion
1594 // sequence converts the source type to the type required by
1595 // the argument of the constructor.
1596 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001597 QualType ThisType = Constructor->getThisType(Context);
John McCall1d318332010-01-12 00:44:57 +00001598 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001599 User.EllipsisConversion = true;
1600 else {
1601 User.Before = Best->Conversions[0].Standard;
1602 User.EllipsisConversion = false;
1603 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001604 User.ConversionFunction = Constructor;
1605 User.After.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00001606 User.After.setFromType(
1607 ThisType->getAs<PointerType>()->getPointeeType());
1608 User.After.setToType(ToType);
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001609 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001610 } else if (CXXConversionDecl *Conversion
1611 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1612 // C++ [over.ics.user]p1:
1613 //
1614 // [...] If the user-defined conversion is specified by a
1615 // conversion function (12.3.2), the initial standard
1616 // conversion sequence converts the source type to the
1617 // implicit object parameter of the conversion function.
1618 User.Before = Best->Conversions[0].Standard;
1619 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001620 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001621
1622 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001623 // The second standard conversion sequence converts the
1624 // result of the user-defined conversion to the target type
1625 // for the sequence. Since an implicit conversion sequence
1626 // is an initialization, the special rules for
1627 // initialization by user-defined conversion apply when
1628 // selecting the best user-defined conversion for a
1629 // user-defined conversion sequence (see 13.3.3 and
1630 // 13.3.3.1).
1631 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001632 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001633 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001634 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001635 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001636 }
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Douglas Gregor60d62c22008-10-31 16:23:19 +00001638 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001639 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001640 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001641 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001642 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001643
1644 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001645 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001646 }
1647
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001648 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001649}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001650
1651bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001652Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001653 ImplicitConversionSequence ICS;
1654 OverloadCandidateSet CandidateSet;
1655 OverloadingResult OvResult =
1656 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1657 CandidateSet, true, false, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001658 if (OvResult == OR_Ambiguous)
1659 Diag(From->getSourceRange().getBegin(),
1660 diag::err_typecheck_ambiguous_condition)
1661 << From->getType() << ToType << From->getSourceRange();
1662 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1663 Diag(From->getSourceRange().getBegin(),
1664 diag::err_typecheck_nonviable_condition)
1665 << From->getType() << ToType << From->getSourceRange();
1666 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001667 return false;
John McCallcbce6062010-01-12 07:18:19 +00001668 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001669 return true;
1670}
Douglas Gregor60d62c22008-10-31 16:23:19 +00001671
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001672/// CompareImplicitConversionSequences - Compare two implicit
1673/// conversion sequences to determine whether one is better than the
1674/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001675ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001676Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1677 const ImplicitConversionSequence& ICS2)
1678{
1679 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1680 // conversion sequences (as defined in 13.3.3.1)
1681 // -- a standard conversion sequence (13.3.3.1.1) is a better
1682 // conversion sequence than a user-defined conversion sequence or
1683 // an ellipsis conversion sequence, and
1684 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1685 // conversion sequence than an ellipsis conversion sequence
1686 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001687 //
John McCall1d318332010-01-12 00:44:57 +00001688 // C++0x [over.best.ics]p10:
1689 // For the purpose of ranking implicit conversion sequences as
1690 // described in 13.3.3.2, the ambiguous conversion sequence is
1691 // treated as a user-defined sequence that is indistinguishable
1692 // from any other user-defined conversion sequence.
1693 if (ICS1.getKind() < ICS2.getKind()) {
1694 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1695 return ImplicitConversionSequence::Better;
1696 } else if (ICS2.getKind() < ICS1.getKind()) {
1697 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1698 return ImplicitConversionSequence::Worse;
1699 }
1700
1701 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1702 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001703
1704 // Two implicit conversion sequences of the same form are
1705 // indistinguishable conversion sequences unless one of the
1706 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00001707 if (ICS1.isStandard())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001708 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00001709 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001710 // User-defined conversion sequence U1 is a better conversion
1711 // sequence than another user-defined conversion sequence U2 if
1712 // they contain the same user-defined conversion function or
1713 // constructor and if the second standard conversion sequence of
1714 // U1 is better than the second standard conversion sequence of
1715 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001716 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001717 ICS2.UserDefined.ConversionFunction)
1718 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1719 ICS2.UserDefined.After);
1720 }
1721
1722 return ImplicitConversionSequence::Indistinguishable;
1723}
1724
1725/// CompareStandardConversionSequences - Compare two standard
1726/// conversion sequences to determine whether one is better than the
1727/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001728ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001729Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1730 const StandardConversionSequence& SCS2)
1731{
1732 // Standard conversion sequence S1 is a better conversion sequence
1733 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1734
1735 // -- S1 is a proper subsequence of S2 (comparing the conversion
1736 // sequences in the canonical form defined by 13.3.3.1.1,
1737 // excluding any Lvalue Transformation; the identity conversion
1738 // sequence is considered to be a subsequence of any
1739 // non-identity conversion sequence) or, if not that,
1740 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1741 // Neither is a proper subsequence of the other. Do nothing.
1742 ;
1743 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1744 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001745 (SCS1.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001746 SCS1.Third == ICK_Identity))
1747 // SCS1 is a proper subsequence of SCS2.
1748 return ImplicitConversionSequence::Better;
1749 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1750 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001751 (SCS2.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001752 SCS2.Third == ICK_Identity))
1753 // SCS2 is a proper subsequence of SCS1.
1754 return ImplicitConversionSequence::Worse;
1755
1756 // -- the rank of S1 is better than the rank of S2 (by the rules
1757 // defined below), or, if not that,
1758 ImplicitConversionRank Rank1 = SCS1.getRank();
1759 ImplicitConversionRank Rank2 = SCS2.getRank();
1760 if (Rank1 < Rank2)
1761 return ImplicitConversionSequence::Better;
1762 else if (Rank2 < Rank1)
1763 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001764
Douglas Gregor57373262008-10-22 14:17:15 +00001765 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1766 // are indistinguishable unless one of the following rules
1767 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001768
Douglas Gregor57373262008-10-22 14:17:15 +00001769 // A conversion that is not a conversion of a pointer, or
1770 // pointer to member, to bool is better than another conversion
1771 // that is such a conversion.
1772 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1773 return SCS2.isPointerConversionToBool()
1774 ? ImplicitConversionSequence::Better
1775 : ImplicitConversionSequence::Worse;
1776
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001777 // C++ [over.ics.rank]p4b2:
1778 //
1779 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001780 // conversion of B* to A* is better than conversion of B* to
1781 // void*, and conversion of A* to void* is better than conversion
1782 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001783 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001784 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001785 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001786 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001787 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1788 // Exactly one of the conversion sequences is a conversion to
1789 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001790 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1791 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001792 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1793 // Neither conversion sequence converts to a void pointer; compare
1794 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001795 if (ImplicitConversionSequence::CompareKind DerivedCK
1796 = CompareDerivedToBaseConversions(SCS1, SCS2))
1797 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001798 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1799 // Both conversion sequences are conversions to void
1800 // pointers. Compare the source types to determine if there's an
1801 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00001802 QualType FromType1 = SCS1.getFromType();
1803 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001804
1805 // Adjust the types we're converting from via the array-to-pointer
1806 // conversion, if we need to.
1807 if (SCS1.First == ICK_Array_To_Pointer)
1808 FromType1 = Context.getArrayDecayedType(FromType1);
1809 if (SCS2.First == ICK_Array_To_Pointer)
1810 FromType2 = Context.getArrayDecayedType(FromType2);
1811
Douglas Gregor01919692009-12-13 21:37:05 +00001812 QualType FromPointee1
1813 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1814 QualType FromPointee2
1815 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001816
Douglas Gregor01919692009-12-13 21:37:05 +00001817 if (IsDerivedFrom(FromPointee2, FromPointee1))
1818 return ImplicitConversionSequence::Better;
1819 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1820 return ImplicitConversionSequence::Worse;
1821
1822 // Objective-C++: If one interface is more specific than the
1823 // other, it is the better one.
1824 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1825 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1826 if (FromIface1 && FromIface1) {
1827 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1828 return ImplicitConversionSequence::Better;
1829 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1830 return ImplicitConversionSequence::Worse;
1831 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001832 }
Douglas Gregor57373262008-10-22 14:17:15 +00001833
1834 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1835 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001836 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001837 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001838 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001839
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001840 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001841 // C++0x [over.ics.rank]p3b4:
1842 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1843 // implicit object parameter of a non-static member function declared
1844 // without a ref-qualifier, and S1 binds an rvalue reference to an
1845 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001846 // FIXME: We don't know if we're dealing with the implicit object parameter,
1847 // or if the member function in this case has a ref qualifier.
1848 // (Of course, we don't have ref qualifiers yet.)
1849 if (SCS1.RRefBinding != SCS2.RRefBinding)
1850 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1851 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001852
1853 // C++ [over.ics.rank]p3b4:
1854 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1855 // which the references refer are the same type except for
1856 // top-level cv-qualifiers, and the type to which the reference
1857 // initialized by S2 refers is more cv-qualified than the type
1858 // to which the reference initialized by S1 refers.
John McCall1d318332010-01-12 00:44:57 +00001859 QualType T1 = SCS1.getToType();
1860 QualType T2 = SCS2.getToType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001861 T1 = Context.getCanonicalType(T1);
1862 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001863 Qualifiers T1Quals, T2Quals;
1864 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1865 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1866 if (UnqualT1 == UnqualT2) {
1867 // If the type is an array type, promote the element qualifiers to the type
1868 // for comparison.
1869 if (isa<ArrayType>(T1) && T1Quals)
1870 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1871 if (isa<ArrayType>(T2) && T2Quals)
1872 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001873 if (T2.isMoreQualifiedThan(T1))
1874 return ImplicitConversionSequence::Better;
1875 else if (T1.isMoreQualifiedThan(T2))
1876 return ImplicitConversionSequence::Worse;
1877 }
1878 }
Douglas Gregor57373262008-10-22 14:17:15 +00001879
1880 return ImplicitConversionSequence::Indistinguishable;
1881}
1882
1883/// CompareQualificationConversions - Compares two standard conversion
1884/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001885/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1886ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001887Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001888 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001889 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001890 // -- S1 and S2 differ only in their qualification conversion and
1891 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1892 // cv-qualification signature of type T1 is a proper subset of
1893 // the cv-qualification signature of type T2, and S1 is not the
1894 // deprecated string literal array-to-pointer conversion (4.2).
1895 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1896 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1897 return ImplicitConversionSequence::Indistinguishable;
1898
1899 // FIXME: the example in the standard doesn't use a qualification
1900 // conversion (!)
1901 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1902 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1903 T1 = Context.getCanonicalType(T1);
1904 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001905 Qualifiers T1Quals, T2Quals;
1906 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1907 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00001908
1909 // If the types are the same, we won't learn anything by unwrapped
1910 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00001911 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00001912 return ImplicitConversionSequence::Indistinguishable;
1913
Chandler Carruth28e318c2009-12-29 07:16:59 +00001914 // If the type is an array type, promote the element qualifiers to the type
1915 // for comparison.
1916 if (isa<ArrayType>(T1) && T1Quals)
1917 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1918 if (isa<ArrayType>(T2) && T2Quals)
1919 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1920
Mike Stump1eb44332009-09-09 15:08:12 +00001921 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001922 = ImplicitConversionSequence::Indistinguishable;
1923 while (UnwrapSimilarPointerTypes(T1, T2)) {
1924 // Within each iteration of the loop, we check the qualifiers to
1925 // determine if this still looks like a qualification
1926 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001927 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001928 // until there are no more pointers or pointers-to-members left
1929 // to unwrap. This essentially mimics what
1930 // IsQualificationConversion does, but here we're checking for a
1931 // strict subset of qualifiers.
1932 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1933 // The qualifiers are the same, so this doesn't tell us anything
1934 // about how the sequences rank.
1935 ;
1936 else if (T2.isMoreQualifiedThan(T1)) {
1937 // T1 has fewer qualifiers, so it could be the better sequence.
1938 if (Result == ImplicitConversionSequence::Worse)
1939 // Neither has qualifiers that are a subset of the other's
1940 // qualifiers.
1941 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Douglas Gregor57373262008-10-22 14:17:15 +00001943 Result = ImplicitConversionSequence::Better;
1944 } else if (T1.isMoreQualifiedThan(T2)) {
1945 // T2 has fewer qualifiers, so it could be the better sequence.
1946 if (Result == ImplicitConversionSequence::Better)
1947 // Neither has qualifiers that are a subset of the other's
1948 // qualifiers.
1949 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Douglas Gregor57373262008-10-22 14:17:15 +00001951 Result = ImplicitConversionSequence::Worse;
1952 } else {
1953 // Qualifiers are disjoint.
1954 return ImplicitConversionSequence::Indistinguishable;
1955 }
1956
1957 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001958 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00001959 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001960 }
1961
Douglas Gregor57373262008-10-22 14:17:15 +00001962 // Check that the winning standard conversion sequence isn't using
1963 // the deprecated string literal array to pointer conversion.
1964 switch (Result) {
1965 case ImplicitConversionSequence::Better:
1966 if (SCS1.Deprecated)
1967 Result = ImplicitConversionSequence::Indistinguishable;
1968 break;
1969
1970 case ImplicitConversionSequence::Indistinguishable:
1971 break;
1972
1973 case ImplicitConversionSequence::Worse:
1974 if (SCS2.Deprecated)
1975 Result = ImplicitConversionSequence::Indistinguishable;
1976 break;
1977 }
1978
1979 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001980}
1981
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001982/// CompareDerivedToBaseConversions - Compares two standard conversion
1983/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001984/// various kinds of derived-to-base conversions (C++
1985/// [over.ics.rank]p4b3). As part of these checks, we also look at
1986/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001987ImplicitConversionSequence::CompareKind
1988Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1989 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00001990 QualType FromType1 = SCS1.getFromType();
1991 QualType ToType1 = SCS1.getToType();
1992 QualType FromType2 = SCS2.getFromType();
1993 QualType ToType2 = SCS2.getToType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001994
1995 // Adjust the types we're converting from via the array-to-pointer
1996 // conversion, if we need to.
1997 if (SCS1.First == ICK_Array_To_Pointer)
1998 FromType1 = Context.getArrayDecayedType(FromType1);
1999 if (SCS2.First == ICK_Array_To_Pointer)
2000 FromType2 = Context.getArrayDecayedType(FromType2);
2001
2002 // Canonicalize all of the types.
2003 FromType1 = Context.getCanonicalType(FromType1);
2004 ToType1 = Context.getCanonicalType(ToType1);
2005 FromType2 = Context.getCanonicalType(FromType2);
2006 ToType2 = Context.getCanonicalType(ToType2);
2007
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002008 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002009 //
2010 // If class B is derived directly or indirectly from class A and
2011 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002012 //
2013 // For Objective-C, we let A, B, and C also be Objective-C
2014 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002015
2016 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002017 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002018 SCS2.Second == ICK_Pointer_Conversion &&
2019 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2020 FromType1->isPointerType() && FromType2->isPointerType() &&
2021 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002022 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002023 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002024 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002025 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002026 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002027 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002028 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002029 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002030
John McCall183700f2009-09-21 23:43:11 +00002031 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2032 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2033 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2034 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002035
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002036 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002037 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2038 if (IsDerivedFrom(ToPointee1, ToPointee2))
2039 return ImplicitConversionSequence::Better;
2040 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2041 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002042
2043 if (ToIface1 && ToIface2) {
2044 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2045 return ImplicitConversionSequence::Better;
2046 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2047 return ImplicitConversionSequence::Worse;
2048 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002049 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002050
2051 // -- conversion of B* to A* is better than conversion of C* to A*,
2052 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2053 if (IsDerivedFrom(FromPointee2, FromPointee1))
2054 return ImplicitConversionSequence::Better;
2055 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2056 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Douglas Gregorcb7de522008-11-26 23:31:11 +00002058 if (FromIface1 && FromIface2) {
2059 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2060 return ImplicitConversionSequence::Better;
2061 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2062 return ImplicitConversionSequence::Worse;
2063 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002064 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002065 }
2066
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002067 // Compare based on reference bindings.
2068 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
2069 SCS1.Second == ICK_Derived_To_Base) {
2070 // -- binding of an expression of type C to a reference of type
2071 // B& is better than binding an expression of type C to a
2072 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002073 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2074 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002075 if (IsDerivedFrom(ToType1, ToType2))
2076 return ImplicitConversionSequence::Better;
2077 else if (IsDerivedFrom(ToType2, ToType1))
2078 return ImplicitConversionSequence::Worse;
2079 }
2080
Douglas Gregor225c41e2008-11-03 19:09:14 +00002081 // -- binding of an expression of type B to a reference of type
2082 // A& is better than binding an expression of type C to a
2083 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002084 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2085 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002086 if (IsDerivedFrom(FromType2, FromType1))
2087 return ImplicitConversionSequence::Better;
2088 else if (IsDerivedFrom(FromType1, FromType2))
2089 return ImplicitConversionSequence::Worse;
2090 }
2091 }
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002092
2093 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002094 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2095 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2096 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2097 const MemberPointerType * FromMemPointer1 =
2098 FromType1->getAs<MemberPointerType>();
2099 const MemberPointerType * ToMemPointer1 =
2100 ToType1->getAs<MemberPointerType>();
2101 const MemberPointerType * FromMemPointer2 =
2102 FromType2->getAs<MemberPointerType>();
2103 const MemberPointerType * ToMemPointer2 =
2104 ToType2->getAs<MemberPointerType>();
2105 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2106 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2107 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2108 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2109 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2110 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2111 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2112 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002113 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002114 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2115 if (IsDerivedFrom(ToPointee1, ToPointee2))
2116 return ImplicitConversionSequence::Worse;
2117 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2118 return ImplicitConversionSequence::Better;
2119 }
2120 // conversion of B::* to C::* is better than conversion of A::* to C::*
2121 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2122 if (IsDerivedFrom(FromPointee1, FromPointee2))
2123 return ImplicitConversionSequence::Better;
2124 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2125 return ImplicitConversionSequence::Worse;
2126 }
2127 }
2128
Douglas Gregor225c41e2008-11-03 19:09:14 +00002129 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2130 SCS1.Second == ICK_Derived_To_Base) {
2131 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002132 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2133 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002134 if (IsDerivedFrom(ToType1, ToType2))
2135 return ImplicitConversionSequence::Better;
2136 else if (IsDerivedFrom(ToType2, ToType1))
2137 return ImplicitConversionSequence::Worse;
2138 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002139
Douglas Gregor225c41e2008-11-03 19:09:14 +00002140 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002141 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2142 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002143 if (IsDerivedFrom(FromType2, FromType1))
2144 return ImplicitConversionSequence::Better;
2145 else if (IsDerivedFrom(FromType1, FromType2))
2146 return ImplicitConversionSequence::Worse;
2147 }
2148 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002149
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002150 return ImplicitConversionSequence::Indistinguishable;
2151}
2152
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002153/// TryCopyInitialization - Try to copy-initialize a value of type
2154/// ToType from the expression From. Return the implicit conversion
2155/// sequence required to pass this argument, which may be a bad
2156/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002157/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00002158/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2159/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00002160ImplicitConversionSequence
2161Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002162 bool SuppressUserConversions, bool ForceRValue,
2163 bool InOverloadResolution) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00002164 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002165 ImplicitConversionSequence ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002166 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00002167 CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002168 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002169 SuppressUserConversions,
2170 /*AllowExplicit=*/false,
2171 ForceRValue,
2172 &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002173 return ICS;
2174 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002175 return TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002176 SuppressUserConversions,
2177 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002178 ForceRValue,
2179 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002180 }
2181}
2182
Sebastian Redle2b68332009-04-12 17:16:29 +00002183/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2184/// the expression @p From. Returns true (and emits a diagnostic) if there was
2185/// an error, returns false if the initialization succeeded. Elidable should
2186/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2187/// differently in C++0x for this case.
Mike Stump1eb44332009-09-09 15:08:12 +00002188bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00002189 AssignmentAction Action, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002190 if (!getLangOptions().CPlusPlus) {
2191 // In C, argument passing is the same as performing an assignment.
2192 QualType FromType = From->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002194 AssignConvertType ConvTy =
2195 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00002196 if (ConvTy != Compatible &&
2197 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2198 ConvTy = Compatible;
Mike Stump1eb44332009-09-09 15:08:12 +00002199
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002200 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00002201 FromType, From, Action);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002202 }
Sebastian Redle2b68332009-04-12 17:16:29 +00002203
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002204 if (ToType->isReferenceType())
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002205 return CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002206 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002207 /*SuppressUserConversions=*/false,
2208 /*AllowExplicit=*/false,
2209 /*ForceRValue=*/false);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002210
Douglas Gregor68647482009-12-16 03:45:30 +00002211 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redle2b68332009-04-12 17:16:29 +00002212 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002213 return false;
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002214 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002215 return Diag(From->getSourceRange().getBegin(),
2216 diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00002217 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002218 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002219}
2220
Douglas Gregor96176b32008-11-18 23:14:02 +00002221/// TryObjectArgumentInitialization - Try to initialize the object
2222/// parameter of the given member function (@c Method) from the
2223/// expression @p From.
2224ImplicitConversionSequence
John McCall651f3ee2010-01-14 03:28:57 +00002225Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall701c89e2009-12-03 04:06:58 +00002226 CXXMethodDecl *Method,
2227 CXXRecordDecl *ActingContext) {
2228 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002229 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2230 // const volatile object.
2231 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2232 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2233 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002234
2235 // Set up the conversion sequence as a "bad" conversion, to allow us
2236 // to exit early.
2237 ImplicitConversionSequence ICS;
2238 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00002239 ICS.setBad();
Douglas Gregor96176b32008-11-18 23:14:02 +00002240
2241 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00002242 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002243 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002244 FromType = PT->getPointeeType();
2245
2246 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002247
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002248 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002249 // where X is the class of which the function is a member
2250 // (C++ [over.match.funcs]p4). However, when finding an implicit
2251 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002252 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002253 // (C++ [over.match.funcs]p5). We perform a simplified version of
2254 // reference binding here, that allows class rvalues to bind to
2255 // non-constant references.
2256
2257 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2258 // with the implicit object parameter (C++ [over.match.funcs]p5).
2259 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002260 if (ImplicitParamType.getCVRQualifiers()
2261 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00002262 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall651f3ee2010-01-14 03:28:57 +00002263 ICS.Bad.init(BadConversionSequence::bad_qualifiers,
2264 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002265 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002266 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002267
2268 // Check that we have either the same type or a derived type. It
2269 // affects the conversion rank.
2270 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002271 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor96176b32008-11-18 23:14:02 +00002272 ICS.Standard.Second = ICK_Identity;
2273 else if (IsDerivedFrom(FromType, ClassType))
2274 ICS.Standard.Second = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00002275 else {
2276 ICS.Bad.init(BadConversionSequence::unrelated_class, FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002277 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002278 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002279
2280 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00002281 ICS.setStandard();
2282 ICS.Standard.setFromType(FromType);
2283 ICS.Standard.setToType(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002284 ICS.Standard.ReferenceBinding = true;
2285 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002286 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002287 return ICS;
2288}
2289
2290/// PerformObjectArgumentInitialization - Perform initialization of
2291/// the implicit object parameter for the given Method with the given
2292/// expression.
2293bool
2294Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002295 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002296 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002297 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002298
Ted Kremenek6217b802009-07-29 21:53:49 +00002299 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002300 FromRecordType = PT->getPointeeType();
2301 DestType = Method->getThisType(Context);
2302 } else {
2303 FromRecordType = From->getType();
2304 DestType = ImplicitParamRecordType;
2305 }
2306
John McCall701c89e2009-12-03 04:06:58 +00002307 // Note that we always use the true parent context when performing
2308 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002309 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00002310 = TryObjectArgumentInitialization(From->getType(), Method,
2311 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00002312 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00002313 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002314 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002315 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Douglas Gregor96176b32008-11-18 23:14:02 +00002317 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssona552f7c2009-05-01 18:34:30 +00002318 CheckDerivedToBaseConversion(FromRecordType,
2319 ImplicitParamRecordType,
Douglas Gregor96176b32008-11-18 23:14:02 +00002320 From->getSourceRange().getBegin(),
2321 From->getSourceRange()))
2322 return true;
2323
Mike Stump1eb44332009-09-09 15:08:12 +00002324 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson116b7d92009-08-07 18:45:49 +00002325 /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002326 return false;
2327}
2328
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002329/// TryContextuallyConvertToBool - Attempt to contextually convert the
2330/// expression From to bool (C++0x [conv]p3).
2331ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002332 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002333 // FIXME: Are these flags correct?
2334 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002335 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002336 /*ForceRValue=*/false,
2337 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002338}
2339
2340/// PerformContextuallyConvertToBool - Perform a contextual conversion
2341/// of the expression From to bool (C++0x [conv]p3).
2342bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2343 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall1d318332010-01-12 00:44:57 +00002344 if (!ICS.isBad())
2345 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002346
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002347 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002348 return Diag(From->getSourceRange().getBegin(),
2349 diag::err_typecheck_bool_condition)
2350 << From->getType() << From->getSourceRange();
2351 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002352}
2353
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002354/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002355/// candidate functions, using the given function call arguments. If
2356/// @p SuppressUserConversions, then don't allow user-defined
2357/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002358/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2359/// hacky way to implement the overloading rules for elidable copy
2360/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002361///
2362/// \para PartialOverloading true if we are performing "partial" overloading
2363/// based on an incomplete set of function arguments. This feature is used by
2364/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00002365void
2366Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall86820f52010-01-26 01:37:31 +00002367 AccessSpecifier Access,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002368 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002369 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002370 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002371 bool ForceRValue,
2372 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00002373 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002374 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002375 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002376 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002377 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002378
Douglas Gregor88a35142008-12-22 05:46:06 +00002379 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002380 if (!isa<CXXConstructorDecl>(Method)) {
2381 // If we get here, it's because we're calling a member function
2382 // that is named without a member access expression (e.g.,
2383 // "this->f") that was either written explicitly or created
2384 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00002385 // function, e.g., X::f(). We use an empty type for the implied
2386 // object argument (C++ [over.call.func]p3), and the acting context
2387 // is irrelevant.
John McCall86820f52010-01-26 01:37:31 +00002388 AddMethodCandidate(Method, Access, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00002389 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002390 SuppressUserConversions, ForceRValue);
2391 return;
2392 }
2393 // We treat a constructor like a non-member function, since its object
2394 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002395 }
2396
Douglas Gregorfd476482009-11-13 23:59:09 +00002397 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00002398 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00002399
Douglas Gregor7edfb692009-11-23 12:27:39 +00002400 // Overload resolution is always an unevaluated context.
2401 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2402
Douglas Gregor66724ea2009-11-14 01:20:54 +00002403 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2404 // C++ [class.copy]p3:
2405 // A member function template is never instantiated to perform the copy
2406 // of a class object to an object of its class type.
2407 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2408 if (NumArgs == 1 &&
2409 Constructor->isCopyConstructorLikeSpecialization() &&
2410 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2411 return;
2412 }
2413
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002414 // Add this candidate
2415 CandidateSet.push_back(OverloadCandidate());
2416 OverloadCandidate& Candidate = CandidateSet.back();
2417 Candidate.Function = Function;
John McCall86820f52010-01-26 01:37:31 +00002418 Candidate.Access = Access;
Douglas Gregor88a35142008-12-22 05:46:06 +00002419 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002420 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002421 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002422
2423 unsigned NumArgsInProto = Proto->getNumArgs();
2424
2425 // (C++ 13.3.2p2): A candidate function having fewer than m
2426 // parameters is viable only if it has an ellipsis in its parameter
2427 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00002428 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2429 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002430 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002431 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002432 return;
2433 }
2434
2435 // (C++ 13.3.2p2): A candidate function having more than m parameters
2436 // is viable only if the (m+1)st parameter has a default argument
2437 // (8.3.6). For the purposes of overload resolution, the
2438 // parameter list is truncated on the right, so that there are
2439 // exactly m parameters.
2440 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002441 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002442 // Not enough arguments.
2443 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002444 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002445 return;
2446 }
2447
2448 // Determine the implicit conversion sequences for each of the
2449 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002450 Candidate.Conversions.resize(NumArgs);
2451 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2452 if (ArgIdx < NumArgsInProto) {
2453 // (C++ 13.3.2p3): for F to be a viable function, there shall
2454 // exist for each argument an implicit conversion sequence
2455 // (13.3.3.1) that converts that argument to the corresponding
2456 // parameter of F.
2457 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002458 Candidate.Conversions[ArgIdx]
2459 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002460 SuppressUserConversions, ForceRValue,
2461 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00002462 if (Candidate.Conversions[ArgIdx].isBad()) {
2463 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002464 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00002465 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00002466 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002467 } else {
2468 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2469 // argument for which there is no corresponding parameter is
2470 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002471 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002472 }
2473 }
2474}
2475
Douglas Gregor063daf62009-03-13 18:40:31 +00002476/// \brief Add all of the function declarations in the given function set to
2477/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00002478void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00002479 Expr **Args, unsigned NumArgs,
2480 OverloadCandidateSet& CandidateSet,
2481 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00002482 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall701c89e2009-12-03 04:06:58 +00002483 // FIXME: using declarations
Douglas Gregor3f396022009-09-28 04:47:19 +00002484 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2485 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall6e266892010-01-26 03:27:55 +00002486 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getAccess(),
John McCall701c89e2009-12-03 04:06:58 +00002487 cast<CXXMethodDecl>(FD)->getParent(),
2488 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002489 CandidateSet, SuppressUserConversions);
2490 else
John McCall86820f52010-01-26 01:37:31 +00002491 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00002492 SuppressUserConversions);
2493 } else {
2494 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2495 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2496 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall6e266892010-01-26 03:27:55 +00002497 AddMethodTemplateCandidate(FunTmpl, F.getAccess(),
John McCall701c89e2009-12-03 04:06:58 +00002498 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00002499 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00002500 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002501 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002502 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00002503 else
John McCall86820f52010-01-26 01:37:31 +00002504 AddTemplateOverloadCandidate(FunTmpl, AS_none,
John McCalld5532b62009-11-23 01:53:49 +00002505 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00002506 Args, NumArgs, CandidateSet,
2507 SuppressUserConversions);
2508 }
Douglas Gregor364e0212009-06-27 21:05:07 +00002509 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002510}
2511
John McCall314be4e2009-11-17 07:50:12 +00002512/// AddMethodCandidate - Adds a named decl (which is some kind of
2513/// method) as a method candidate to the given overload set.
John McCall701c89e2009-12-03 04:06:58 +00002514void Sema::AddMethodCandidate(NamedDecl *Decl,
John McCall86820f52010-01-26 01:37:31 +00002515 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002516 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00002517 Expr **Args, unsigned NumArgs,
2518 OverloadCandidateSet& CandidateSet,
2519 bool SuppressUserConversions, bool ForceRValue) {
John McCall701c89e2009-12-03 04:06:58 +00002520 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00002521
2522 if (isa<UsingShadowDecl>(Decl))
2523 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2524
2525 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2526 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2527 "Expected a member function template");
John McCall86820f52010-01-26 01:37:31 +00002528 AddMethodTemplateCandidate(TD, Access, ActingContext, /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00002529 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002530 CandidateSet,
2531 SuppressUserConversions,
2532 ForceRValue);
2533 } else {
John McCall86820f52010-01-26 01:37:31 +00002534 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Access, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00002535 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002536 CandidateSet, SuppressUserConversions, ForceRValue);
2537 }
2538}
2539
Douglas Gregor96176b32008-11-18 23:14:02 +00002540/// AddMethodCandidate - Adds the given C++ member function to the set
2541/// of candidate functions, using the given function call arguments
2542/// and the object argument (@c Object). For example, in a call
2543/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2544/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2545/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002546/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2547/// a slightly hacky way to implement the overloading rules for elidable copy
2548/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002549void
John McCall86820f52010-01-26 01:37:31 +00002550Sema::AddMethodCandidate(CXXMethodDecl *Method, AccessSpecifier Access,
2551 CXXRecordDecl *ActingContext, QualType ObjectType,
2552 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00002553 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002554 bool SuppressUserConversions, bool ForceRValue) {
2555 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002556 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002557 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002558 assert(!isa<CXXConstructorDecl>(Method) &&
2559 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002560
Douglas Gregor3f396022009-09-28 04:47:19 +00002561 if (!CandidateSet.isNewCandidate(Method))
2562 return;
2563
Douglas Gregor7edfb692009-11-23 12:27:39 +00002564 // Overload resolution is always an unevaluated context.
2565 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2566
Douglas Gregor96176b32008-11-18 23:14:02 +00002567 // Add this candidate
2568 CandidateSet.push_back(OverloadCandidate());
2569 OverloadCandidate& Candidate = CandidateSet.back();
2570 Candidate.Function = Method;
John McCall86820f52010-01-26 01:37:31 +00002571 Candidate.Access = Access;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002572 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002573 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002574
2575 unsigned NumArgsInProto = Proto->getNumArgs();
2576
2577 // (C++ 13.3.2p2): A candidate function having fewer than m
2578 // parameters is viable only if it has an ellipsis in its parameter
2579 // list (8.3.5).
2580 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2581 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002582 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00002583 return;
2584 }
2585
2586 // (C++ 13.3.2p2): A candidate function having more than m parameters
2587 // is viable only if the (m+1)st parameter has a default argument
2588 // (8.3.6). For the purposes of overload resolution, the
2589 // parameter list is truncated on the right, so that there are
2590 // exactly m parameters.
2591 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2592 if (NumArgs < MinRequiredArgs) {
2593 // Not enough arguments.
2594 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002595 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00002596 return;
2597 }
2598
2599 Candidate.Viable = true;
2600 Candidate.Conversions.resize(NumArgs + 1);
2601
John McCall701c89e2009-12-03 04:06:58 +00002602 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00002603 // The implicit object argument is ignored.
2604 Candidate.IgnoreObjectArgument = true;
2605 else {
2606 // Determine the implicit conversion sequence for the object
2607 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00002608 Candidate.Conversions[0]
2609 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00002610 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002611 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002612 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00002613 return;
2614 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002615 }
2616
2617 // Determine the implicit conversion sequences for each of the
2618 // arguments.
2619 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2620 if (ArgIdx < NumArgsInProto) {
2621 // (C++ 13.3.2p3): for F to be a viable function, there shall
2622 // exist for each argument an implicit conversion sequence
2623 // (13.3.3.1) that converts that argument to the corresponding
2624 // parameter of F.
2625 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002626 Candidate.Conversions[ArgIdx + 1]
2627 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002628 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002629 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00002630 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002631 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002632 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00002633 break;
2634 }
2635 } else {
2636 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2637 // argument for which there is no corresponding parameter is
2638 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002639 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00002640 }
2641 }
2642}
2643
Douglas Gregor6b906862009-08-21 00:16:32 +00002644/// \brief Add a C++ member function template as a candidate to the candidate
2645/// set, using template argument deduction to produce an appropriate member
2646/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002647void
Douglas Gregor6b906862009-08-21 00:16:32 +00002648Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall86820f52010-01-26 01:37:31 +00002649 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002650 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00002651 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00002652 QualType ObjectType,
2653 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002654 OverloadCandidateSet& CandidateSet,
2655 bool SuppressUserConversions,
2656 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002657 if (!CandidateSet.isNewCandidate(MethodTmpl))
2658 return;
2659
Douglas Gregor6b906862009-08-21 00:16:32 +00002660 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002661 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002662 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002663 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002664 // candidate functions in the usual way.113) A given name can refer to one
2665 // or more function templates and also to a set of overloaded non-template
2666 // functions. In such a case, the candidate functions generated from each
2667 // function template are combined with the set of non-template candidate
2668 // functions.
2669 TemplateDeductionInfo Info(Context);
2670 FunctionDecl *Specialization = 0;
2671 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002672 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002673 Args, NumArgs, Specialization, Info)) {
2674 // FIXME: Record what happened with template argument deduction, so
2675 // that we can give the user a beautiful diagnostic.
2676 (void)Result;
2677 return;
2678 }
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Douglas Gregor6b906862009-08-21 00:16:32 +00002680 // Add the function template specialization produced by template argument
2681 // deduction as a candidate.
2682 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002683 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002684 "Specialization is not a member function?");
John McCall86820f52010-01-26 01:37:31 +00002685 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Access,
2686 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002687 CandidateSet, SuppressUserConversions, ForceRValue);
2688}
2689
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002690/// \brief Add a C++ function template specialization as a candidate
2691/// in the candidate set, using template argument deduction to produce
2692/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002693void
Douglas Gregore53060f2009-06-25 22:08:12 +00002694Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall86820f52010-01-26 01:37:31 +00002695 AccessSpecifier Access,
John McCalld5532b62009-11-23 01:53:49 +00002696 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002697 Expr **Args, unsigned NumArgs,
2698 OverloadCandidateSet& CandidateSet,
2699 bool SuppressUserConversions,
2700 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002701 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2702 return;
2703
Douglas Gregore53060f2009-06-25 22:08:12 +00002704 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002705 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00002706 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002707 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00002708 // candidate functions in the usual way.113) A given name can refer to one
2709 // or more function templates and also to a set of overloaded non-template
2710 // functions. In such a case, the candidate functions generated from each
2711 // function template are combined with the set of non-template candidate
2712 // functions.
2713 TemplateDeductionInfo Info(Context);
2714 FunctionDecl *Specialization = 0;
2715 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002716 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002717 Args, NumArgs, Specialization, Info)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002718 // FIXME: Record what happened with template argument deduction, so
2719 // that we can give the user a beautiful diagnostic.
John McCall578b69b2009-12-16 08:11:27 +00002720 (void) Result;
2721
2722 CandidateSet.push_back(OverloadCandidate());
2723 OverloadCandidate &Candidate = CandidateSet.back();
2724 Candidate.Function = FunctionTemplate->getTemplatedDecl();
John McCall86820f52010-01-26 01:37:31 +00002725 Candidate.Access = Access;
John McCall578b69b2009-12-16 08:11:27 +00002726 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002727 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00002728 Candidate.IsSurrogate = false;
2729 Candidate.IgnoreObjectArgument = false;
Douglas Gregore53060f2009-06-25 22:08:12 +00002730 return;
2731 }
Mike Stump1eb44332009-09-09 15:08:12 +00002732
Douglas Gregore53060f2009-06-25 22:08:12 +00002733 // Add the function template specialization produced by template argument
2734 // deduction as a candidate.
2735 assert(Specialization && "Missing function template specialization?");
John McCall86820f52010-01-26 01:37:31 +00002736 AddOverloadCandidate(Specialization, Access, Args, NumArgs, CandidateSet,
Douglas Gregore53060f2009-06-25 22:08:12 +00002737 SuppressUserConversions, ForceRValue);
2738}
Mike Stump1eb44332009-09-09 15:08:12 +00002739
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002740/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002741/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002742/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002743/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002744/// (which may or may not be the same type as the type that the
2745/// conversion function produces).
2746void
2747Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall86820f52010-01-26 01:37:31 +00002748 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002749 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002750 Expr *From, QualType ToType,
2751 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002752 assert(!Conversion->getDescribedFunctionTemplate() &&
2753 "Conversion function templates use AddTemplateConversionCandidate");
2754
Douglas Gregor3f396022009-09-28 04:47:19 +00002755 if (!CandidateSet.isNewCandidate(Conversion))
2756 return;
2757
Douglas Gregor7edfb692009-11-23 12:27:39 +00002758 // Overload resolution is always an unevaluated context.
2759 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2760
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002761 // Add this candidate
2762 CandidateSet.push_back(OverloadCandidate());
2763 OverloadCandidate& Candidate = CandidateSet.back();
2764 Candidate.Function = Conversion;
John McCall86820f52010-01-26 01:37:31 +00002765 Candidate.Access = Access;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002766 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002767 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002768 Candidate.FinalConversion.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00002769 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
2770 Candidate.FinalConversion.setToType(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002771
Douglas Gregor96176b32008-11-18 23:14:02 +00002772 // Determine the implicit conversion sequence for the implicit
2773 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002774 Candidate.Viable = true;
2775 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00002776 Candidate.Conversions[0]
2777 = TryObjectArgumentInitialization(From->getType(), Conversion,
2778 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002779 // Conversion functions to a different type in the base class is visible in
2780 // the derived class. So, a derived to base conversion should not participate
2781 // in overload resolution.
2782 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2783 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall1d318332010-01-12 00:44:57 +00002784 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002785 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002786 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002787 return;
2788 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002789
2790 // We won't go through a user-define type conversion function to convert a
2791 // derived to base as such conversions are given Conversion Rank. They only
2792 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2793 QualType FromCanon
2794 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2795 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2796 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2797 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00002798 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002799 return;
2800 }
2801
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002802
2803 // To determine what the conversion from the result of calling the
2804 // conversion function to the type we're eventually trying to
2805 // convert to (ToType), we need to synthesize a call to the
2806 // conversion function and attempt copy initialization from it. This
2807 // makes sure that we get the right semantics with respect to
2808 // lvalues/rvalues and the type. Fortunately, we can allocate this
2809 // call on the stack and we don't need its arguments to be
2810 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002811 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002812 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002813 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00002814 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002815 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002816
2817 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002818 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2819 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002820 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002821 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002822 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00002823 ImplicitConversionSequence ICS =
2824 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002825 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002826 /*ForceRValue=*/false,
2827 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002828
John McCall1d318332010-01-12 00:44:57 +00002829 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002830 case ImplicitConversionSequence::StandardConversion:
2831 Candidate.FinalConversion = ICS.Standard;
2832 break;
2833
2834 case ImplicitConversionSequence::BadConversion:
2835 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00002836 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002837 break;
2838
2839 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002840 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002841 "Can only end up with a standard conversion sequence or failure");
2842 }
2843}
2844
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002845/// \brief Adds a conversion function template specialization
2846/// candidate to the overload set, using template argument deduction
2847/// to deduce the template arguments of the conversion function
2848/// template from the type that we are converting to (C++
2849/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002850void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002851Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall86820f52010-01-26 01:37:31 +00002852 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002853 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002854 Expr *From, QualType ToType,
2855 OverloadCandidateSet &CandidateSet) {
2856 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2857 "Only conversion function templates permitted here");
2858
Douglas Gregor3f396022009-09-28 04:47:19 +00002859 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2860 return;
2861
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002862 TemplateDeductionInfo Info(Context);
2863 CXXConversionDecl *Specialization = 0;
2864 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002865 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002866 Specialization, Info)) {
2867 // FIXME: Record what happened with template argument deduction, so
2868 // that we can give the user a beautiful diagnostic.
2869 (void)Result;
2870 return;
2871 }
Mike Stump1eb44332009-09-09 15:08:12 +00002872
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002873 // Add the conversion function template specialization produced by
2874 // template argument deduction as a candidate.
2875 assert(Specialization && "Missing function template specialization?");
John McCall86820f52010-01-26 01:37:31 +00002876 AddConversionCandidate(Specialization, Access, ActingDC, From, ToType,
2877 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002878}
2879
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002880/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2881/// converts the given @c Object to a function pointer via the
2882/// conversion function @c Conversion, and then attempts to call it
2883/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2884/// the type of function that we'll eventually be calling.
2885void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall86820f52010-01-26 01:37:31 +00002886 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002887 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00002888 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00002889 QualType ObjectType,
2890 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002891 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002892 if (!CandidateSet.isNewCandidate(Conversion))
2893 return;
2894
Douglas Gregor7edfb692009-11-23 12:27:39 +00002895 // Overload resolution is always an unevaluated context.
2896 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2897
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002898 CandidateSet.push_back(OverloadCandidate());
2899 OverloadCandidate& Candidate = CandidateSet.back();
2900 Candidate.Function = 0;
John McCall86820f52010-01-26 01:37:31 +00002901 Candidate.Access = Access;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002902 Candidate.Surrogate = Conversion;
2903 Candidate.Viable = true;
2904 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002905 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002906 Candidate.Conversions.resize(NumArgs + 1);
2907
2908 // Determine the implicit conversion sequence for the implicit
2909 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002910 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00002911 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00002912 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002913 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002914 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00002915 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002916 return;
2917 }
2918
2919 // The first conversion is actually a user-defined conversion whose
2920 // first conversion is ObjectInit's standard conversion (which is
2921 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00002922 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002923 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002924 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002925 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002926 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002927 = Candidate.Conversions[0].UserDefined.Before;
2928 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2929
Mike Stump1eb44332009-09-09 15:08:12 +00002930 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002931 unsigned NumArgsInProto = Proto->getNumArgs();
2932
2933 // (C++ 13.3.2p2): A candidate function having fewer than m
2934 // parameters is viable only if it has an ellipsis in its parameter
2935 // list (8.3.5).
2936 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2937 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002938 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002939 return;
2940 }
2941
2942 // Function types don't have any default arguments, so just check if
2943 // we have enough arguments.
2944 if (NumArgs < NumArgsInProto) {
2945 // Not enough arguments.
2946 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002947 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002948 return;
2949 }
2950
2951 // Determine the implicit conversion sequences for each of the
2952 // arguments.
2953 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2954 if (ArgIdx < NumArgsInProto) {
2955 // (C++ 13.3.2p3): for F to be a viable function, there shall
2956 // exist for each argument an implicit conversion sequence
2957 // (13.3.3.1) that converts that argument to the corresponding
2958 // parameter of F.
2959 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002960 Candidate.Conversions[ArgIdx + 1]
2961 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002962 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002963 /*ForceRValue=*/false,
2964 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00002965 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002966 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002967 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002968 break;
2969 }
2970 } else {
2971 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2972 // argument for which there is no corresponding parameter is
2973 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002974 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002975 }
2976 }
2977}
2978
Mike Stump390b4cc2009-05-16 07:39:55 +00002979// FIXME: This will eventually be removed, once we've migrated all of the
2980// operator overloading logic over to the scheme used by binary operators, which
2981// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002982void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002983 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002984 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002985 OverloadCandidateSet& CandidateSet,
2986 SourceRange OpRange) {
John McCall6e266892010-01-26 03:27:55 +00002987 UnresolvedSet<16> Fns;
Douglas Gregor063daf62009-03-13 18:40:31 +00002988
2989 QualType T1 = Args[0]->getType();
2990 QualType T2;
2991 if (NumArgs > 1)
2992 T2 = Args[1]->getType();
2993
2994 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002995 if (S)
John McCall6e266892010-01-26 03:27:55 +00002996 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
2997 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
2998 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
2999 CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00003000 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregor573d9c32009-10-21 23:19:44 +00003001 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00003002}
3003
3004/// \brief Add overload candidates for overloaded operators that are
3005/// member functions.
3006///
3007/// Add the overloaded operator candidates that are member functions
3008/// for the operator Op that was used in an operator expression such
3009/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3010/// CandidateSet will store the added overload candidates. (C++
3011/// [over.match.oper]).
3012void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3013 SourceLocation OpLoc,
3014 Expr **Args, unsigned NumArgs,
3015 OverloadCandidateSet& CandidateSet,
3016 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003017 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3018
3019 // C++ [over.match.oper]p3:
3020 // For a unary operator @ with an operand of a type whose
3021 // cv-unqualified version is T1, and for a binary operator @ with
3022 // a left operand of a type whose cv-unqualified version is T1 and
3023 // a right operand of a type whose cv-unqualified version is T2,
3024 // three sets of candidate functions, designated member
3025 // candidates, non-member candidates and built-in candidates, are
3026 // constructed as follows:
3027 QualType T1 = Args[0]->getType();
3028 QualType T2;
3029 if (NumArgs > 1)
3030 T2 = Args[1]->getType();
3031
3032 // -- If T1 is a class type, the set of member candidates is the
3033 // result of the qualified lookup of T1::operator@
3034 // (13.3.1.1.1); otherwise, the set of member candidates is
3035 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00003036 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003037 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003038 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003039 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003040
John McCalla24dc2e2009-11-17 02:14:36 +00003041 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3042 LookupQualifiedName(Operators, T1Rec->getDecl());
3043 Operators.suppressDiagnostics();
3044
Mike Stump1eb44332009-09-09 15:08:12 +00003045 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003046 OperEnd = Operators.end();
3047 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00003048 ++Oper)
John McCall86820f52010-01-26 01:37:31 +00003049 AddMethodCandidate(*Oper, Oper.getAccess(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00003050 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00003051 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00003052 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003053}
3054
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003055/// AddBuiltinCandidate - Add a candidate for a built-in
3056/// operator. ResultTy and ParamTys are the result and parameter types
3057/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003058/// arguments being passed to the candidate. IsAssignmentOperator
3059/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003060/// operator. NumContextualBoolArguments is the number of arguments
3061/// (at the beginning of the argument list) that will be contextually
3062/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00003063void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003064 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003065 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003066 bool IsAssignmentOperator,
3067 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00003068 // Overload resolution is always an unevaluated context.
3069 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3070
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003071 // Add this candidate
3072 CandidateSet.push_back(OverloadCandidate());
3073 OverloadCandidate& Candidate = CandidateSet.back();
3074 Candidate.Function = 0;
John McCall86820f52010-01-26 01:37:31 +00003075 Candidate.Access = AS_none;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003076 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003077 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003078 Candidate.BuiltinTypes.ResultTy = ResultTy;
3079 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3080 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3081
3082 // Determine the implicit conversion sequences for each of the
3083 // arguments.
3084 Candidate.Viable = true;
3085 Candidate.Conversions.resize(NumArgs);
3086 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003087 // C++ [over.match.oper]p4:
3088 // For the built-in assignment operators, conversions of the
3089 // left operand are restricted as follows:
3090 // -- no temporaries are introduced to hold the left operand, and
3091 // -- no user-defined conversions are applied to the left
3092 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00003093 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003094 //
3095 // We block these conversions by turning off user-defined
3096 // conversions, since that is the only way that initialization of
3097 // a reference to a non-class type can occur from something that
3098 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003099 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00003100 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003101 "Contextual conversion to bool requires bool type");
3102 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3103 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003104 Candidate.Conversions[ArgIdx]
3105 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00003106 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003107 /*ForceRValue=*/false,
3108 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003109 }
John McCall1d318332010-01-12 00:44:57 +00003110 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003111 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003112 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003113 break;
3114 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003115 }
3116}
3117
3118/// BuiltinCandidateTypeSet - A set of types that will be used for the
3119/// candidate operator functions for built-in operators (C++
3120/// [over.built]). The types are separated into pointer types and
3121/// enumeration types.
3122class BuiltinCandidateTypeSet {
3123 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003124 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003125
3126 /// PointerTypes - The set of pointer types that will be used in the
3127 /// built-in candidates.
3128 TypeSet PointerTypes;
3129
Sebastian Redl78eb8742009-04-19 21:53:20 +00003130 /// MemberPointerTypes - The set of member pointer types that will be
3131 /// used in the built-in candidates.
3132 TypeSet MemberPointerTypes;
3133
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003134 /// EnumerationTypes - The set of enumeration types that will be
3135 /// used in the built-in candidates.
3136 TypeSet EnumerationTypes;
3137
Douglas Gregor5842ba92009-08-24 15:23:48 +00003138 /// Sema - The semantic analysis instance where we are building the
3139 /// candidate type set.
3140 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003141
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003142 /// Context - The AST context in which we will build the type sets.
3143 ASTContext &Context;
3144
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003145 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3146 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003147 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003148
3149public:
3150 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003151 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003152
Mike Stump1eb44332009-09-09 15:08:12 +00003153 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003154 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003155
Douglas Gregor573d9c32009-10-21 23:19:44 +00003156 void AddTypesConvertedFrom(QualType Ty,
3157 SourceLocation Loc,
3158 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003159 bool AllowExplicitConversions,
3160 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003161
3162 /// pointer_begin - First pointer type found;
3163 iterator pointer_begin() { return PointerTypes.begin(); }
3164
Sebastian Redl78eb8742009-04-19 21:53:20 +00003165 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003166 iterator pointer_end() { return PointerTypes.end(); }
3167
Sebastian Redl78eb8742009-04-19 21:53:20 +00003168 /// member_pointer_begin - First member pointer type found;
3169 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3170
3171 /// member_pointer_end - Past the last member pointer type found;
3172 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3173
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003174 /// enumeration_begin - First enumeration type found;
3175 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3176
Sebastian Redl78eb8742009-04-19 21:53:20 +00003177 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003178 iterator enumeration_end() { return EnumerationTypes.end(); }
3179};
3180
Sebastian Redl78eb8742009-04-19 21:53:20 +00003181/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003182/// the set of pointer types along with any more-qualified variants of
3183/// that type. For example, if @p Ty is "int const *", this routine
3184/// will add "int const *", "int const volatile *", "int const
3185/// restrict *", and "int const volatile restrict *" to the set of
3186/// pointer types. Returns true if the add of @p Ty itself succeeded,
3187/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003188///
3189/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003190bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003191BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3192 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003193
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003194 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003195 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003196 return false;
3197
John McCall0953e762009-09-24 19:53:00 +00003198 const PointerType *PointerTy = Ty->getAs<PointerType>();
3199 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003200
John McCall0953e762009-09-24 19:53:00 +00003201 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003202 // Don't add qualified variants of arrays. For one, they're not allowed
3203 // (the qualifier would sink to the element type), and for another, the
3204 // only overload situation where it matters is subscript or pointer +- int,
3205 // and those shouldn't have qualifier variants anyway.
3206 if (PointeeTy->isArrayType())
3207 return true;
John McCall0953e762009-09-24 19:53:00 +00003208 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003209 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003210 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003211 bool hasVolatile = VisibleQuals.hasVolatile();
3212 bool hasRestrict = VisibleQuals.hasRestrict();
3213
John McCall0953e762009-09-24 19:53:00 +00003214 // Iterate through all strict supersets of BaseCVR.
3215 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3216 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003217 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3218 // in the types.
3219 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3220 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003221 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3222 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003223 }
3224
3225 return true;
3226}
3227
Sebastian Redl78eb8742009-04-19 21:53:20 +00003228/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3229/// to the set of pointer types along with any more-qualified variants of
3230/// that type. For example, if @p Ty is "int const *", this routine
3231/// will add "int const *", "int const volatile *", "int const
3232/// restrict *", and "int const volatile restrict *" to the set of
3233/// pointer types. Returns true if the add of @p Ty itself succeeded,
3234/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003235///
3236/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003237bool
3238BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3239 QualType Ty) {
3240 // Insert this type.
3241 if (!MemberPointerTypes.insert(Ty))
3242 return false;
3243
John McCall0953e762009-09-24 19:53:00 +00003244 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3245 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003246
John McCall0953e762009-09-24 19:53:00 +00003247 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003248 // Don't add qualified variants of arrays. For one, they're not allowed
3249 // (the qualifier would sink to the element type), and for another, the
3250 // only overload situation where it matters is subscript or pointer +- int,
3251 // and those shouldn't have qualifier variants anyway.
3252 if (PointeeTy->isArrayType())
3253 return true;
John McCall0953e762009-09-24 19:53:00 +00003254 const Type *ClassTy = PointerTy->getClass();
3255
3256 // Iterate through all strict supersets of the pointee type's CVR
3257 // qualifiers.
3258 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3259 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3260 if ((CVR | BaseCVR) != CVR) continue;
3261
3262 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3263 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003264 }
3265
3266 return true;
3267}
3268
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003269/// AddTypesConvertedFrom - Add each of the types to which the type @p
3270/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003271/// primarily interested in pointer types and enumeration types. We also
3272/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003273/// AllowUserConversions is true if we should look at the conversion
3274/// functions of a class type, and AllowExplicitConversions if we
3275/// should also include the explicit conversion functions of a class
3276/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003277void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003278BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003279 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003280 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003281 bool AllowExplicitConversions,
3282 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003283 // Only deal with canonical types.
3284 Ty = Context.getCanonicalType(Ty);
3285
3286 // Look through reference types; they aren't part of the type of an
3287 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003288 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003289 Ty = RefTy->getPointeeType();
3290
3291 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003292 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003293
Sebastian Redla65b5512009-11-05 16:36:20 +00003294 // If we're dealing with an array type, decay to the pointer.
3295 if (Ty->isArrayType())
3296 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3297
Ted Kremenek6217b802009-07-29 21:53:49 +00003298 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003299 QualType PointeeTy = PointerTy->getPointeeType();
3300
3301 // Insert our type, and its more-qualified variants, into the set
3302 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003303 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003304 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003305 } else if (Ty->isMemberPointerType()) {
3306 // Member pointers are far easier, since the pointee can't be converted.
3307 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3308 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003309 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003310 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003311 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003312 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003313 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003314 // No conversion functions in incomplete types.
3315 return;
3316 }
Mike Stump1eb44332009-09-09 15:08:12 +00003317
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003318 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00003319 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003320 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003321 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003322 E = Conversions->end(); I != E; ++I) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003323
Mike Stump1eb44332009-09-09 15:08:12 +00003324 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003325 // about which builtin types we can convert to.
John McCallba135432009-11-21 08:51:07 +00003326 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003327 continue;
3328
John McCallba135432009-11-21 08:51:07 +00003329 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003330 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003331 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003332 VisibleQuals);
3333 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003334 }
3335 }
3336 }
3337}
3338
Douglas Gregor19b7b152009-08-24 13:43:27 +00003339/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3340/// the volatile- and non-volatile-qualified assignment operators for the
3341/// given type to the candidate set.
3342static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3343 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003344 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003345 unsigned NumArgs,
3346 OverloadCandidateSet &CandidateSet) {
3347 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003348
Douglas Gregor19b7b152009-08-24 13:43:27 +00003349 // T& operator=(T&, T)
3350 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3351 ParamTypes[1] = T;
3352 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3353 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003354
Douglas Gregor19b7b152009-08-24 13:43:27 +00003355 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3356 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003357 ParamTypes[0]
3358 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003359 ParamTypes[1] = T;
3360 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003361 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003362 }
3363}
Mike Stump1eb44332009-09-09 15:08:12 +00003364
Sebastian Redl9994a342009-10-25 17:03:50 +00003365/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3366/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003367static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3368 Qualifiers VRQuals;
3369 const RecordType *TyRec;
3370 if (const MemberPointerType *RHSMPType =
3371 ArgExpr->getType()->getAs<MemberPointerType>())
3372 TyRec = cast<RecordType>(RHSMPType->getClass());
3373 else
3374 TyRec = ArgExpr->getType()->getAs<RecordType>();
3375 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003376 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003377 VRQuals.addVolatile();
3378 VRQuals.addRestrict();
3379 return VRQuals;
3380 }
3381
3382 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00003383 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00003384 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003385
John McCalleec51cf2010-01-20 00:46:10 +00003386 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003387 E = Conversions->end(); I != E; ++I) {
3388 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003389 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3390 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3391 CanTy = ResTypeRef->getPointeeType();
3392 // Need to go down the pointer/mempointer chain and add qualifiers
3393 // as see them.
3394 bool done = false;
3395 while (!done) {
3396 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3397 CanTy = ResTypePtr->getPointeeType();
3398 else if (const MemberPointerType *ResTypeMPtr =
3399 CanTy->getAs<MemberPointerType>())
3400 CanTy = ResTypeMPtr->getPointeeType();
3401 else
3402 done = true;
3403 if (CanTy.isVolatileQualified())
3404 VRQuals.addVolatile();
3405 if (CanTy.isRestrictQualified())
3406 VRQuals.addRestrict();
3407 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3408 return VRQuals;
3409 }
3410 }
3411 }
3412 return VRQuals;
3413}
3414
Douglas Gregor74253732008-11-19 15:42:04 +00003415/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3416/// operator overloads to the candidate set (C++ [over.built]), based
3417/// on the operator @p Op and the arguments given. For example, if the
3418/// operator is a binary '+', this routine might add "int
3419/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003420void
Mike Stump1eb44332009-09-09 15:08:12 +00003421Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003422 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00003423 Expr **Args, unsigned NumArgs,
3424 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003425 // The set of "promoted arithmetic types", which are the arithmetic
3426 // types are that preserved by promotion (C++ [over.built]p2). Note
3427 // that the first few of these types are the promoted integral
3428 // types; these types need to be first.
3429 // FIXME: What about complex?
3430 const unsigned FirstIntegralType = 0;
3431 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00003432 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003433 LastPromotedIntegralType = 13;
3434 const unsigned FirstPromotedArithmeticType = 7,
3435 LastPromotedArithmeticType = 16;
3436 const unsigned NumArithmeticTypes = 16;
3437 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003438 Context.BoolTy, Context.CharTy, Context.WCharTy,
3439// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003440 Context.SignedCharTy, Context.ShortTy,
3441 Context.UnsignedCharTy, Context.UnsignedShortTy,
3442 Context.IntTy, Context.LongTy, Context.LongLongTy,
3443 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3444 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3445 };
Douglas Gregor652371a2009-10-21 22:01:30 +00003446 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3447 "Invalid first promoted integral type");
3448 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3449 == Context.UnsignedLongLongTy &&
3450 "Invalid last promoted integral type");
3451 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3452 "Invalid first promoted arithmetic type");
3453 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3454 == Context.LongDoubleTy &&
3455 "Invalid last promoted arithmetic type");
3456
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003457 // Find all of the types that the arguments can convert to, but only
3458 // if the operator we're looking at has built-in operator candidates
3459 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003460 Qualifiers VisibleTypeConversionsQuals;
3461 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003462 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3463 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3464
Douglas Gregor5842ba92009-08-24 15:23:48 +00003465 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003466 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3467 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003468 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003469 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003470 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003471 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003472 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003473 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregor573d9c32009-10-21 23:19:44 +00003474 OpLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003475 true,
3476 (Op == OO_Exclaim ||
3477 Op == OO_AmpAmp ||
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003478 Op == OO_PipePipe),
3479 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003480 }
3481
3482 bool isComparison = false;
3483 switch (Op) {
3484 case OO_None:
3485 case NUM_OVERLOADED_OPERATORS:
3486 assert(false && "Expected an overloaded operator");
3487 break;
3488
Douglas Gregor74253732008-11-19 15:42:04 +00003489 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003490 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003491 goto UnaryStar;
3492 else
3493 goto BinaryStar;
3494 break;
3495
3496 case OO_Plus: // '+' is either unary or binary
3497 if (NumArgs == 1)
3498 goto UnaryPlus;
3499 else
3500 goto BinaryPlus;
3501 break;
3502
3503 case OO_Minus: // '-' is either unary or binary
3504 if (NumArgs == 1)
3505 goto UnaryMinus;
3506 else
3507 goto BinaryMinus;
3508 break;
3509
3510 case OO_Amp: // '&' is either unary or binary
3511 if (NumArgs == 1)
3512 goto UnaryAmp;
3513 else
3514 goto BinaryAmp;
3515
3516 case OO_PlusPlus:
3517 case OO_MinusMinus:
3518 // C++ [over.built]p3:
3519 //
3520 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3521 // is either volatile or empty, there exist candidate operator
3522 // functions of the form
3523 //
3524 // VQ T& operator++(VQ T&);
3525 // T operator++(VQ T&, int);
3526 //
3527 // C++ [over.built]p4:
3528 //
3529 // For every pair (T, VQ), where T is an arithmetic type other
3530 // than bool, and VQ is either volatile or empty, there exist
3531 // candidate operator functions of the form
3532 //
3533 // VQ T& operator--(VQ T&);
3534 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003535 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003536 Arith < NumArithmeticTypes; ++Arith) {
3537 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003538 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003539 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003540
3541 // Non-volatile version.
3542 if (NumArgs == 1)
3543 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3544 else
3545 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003546 // heuristic to reduce number of builtin candidates in the set.
3547 // Add volatile version only if there are conversions to a volatile type.
3548 if (VisibleTypeConversionsQuals.hasVolatile()) {
3549 // Volatile version
3550 ParamTypes[0]
3551 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3552 if (NumArgs == 1)
3553 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3554 else
3555 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3556 }
Douglas Gregor74253732008-11-19 15:42:04 +00003557 }
3558
3559 // C++ [over.built]p5:
3560 //
3561 // For every pair (T, VQ), where T is a cv-qualified or
3562 // cv-unqualified object type, and VQ is either volatile or
3563 // empty, there exist candidate operator functions of the form
3564 //
3565 // T*VQ& operator++(T*VQ&);
3566 // T*VQ& operator--(T*VQ&);
3567 // T* operator++(T*VQ&, int);
3568 // T* operator--(T*VQ&, int);
3569 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3570 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3571 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003572 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003573 continue;
3574
Mike Stump1eb44332009-09-09 15:08:12 +00003575 QualType ParamTypes[2] = {
3576 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003577 };
Mike Stump1eb44332009-09-09 15:08:12 +00003578
Douglas Gregor74253732008-11-19 15:42:04 +00003579 // Without volatile
3580 if (NumArgs == 1)
3581 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3582 else
3583 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3584
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003585 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3586 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003587 // With volatile
John McCall0953e762009-09-24 19:53:00 +00003588 ParamTypes[0]
3589 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00003590 if (NumArgs == 1)
3591 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3592 else
3593 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3594 }
3595 }
3596 break;
3597
3598 UnaryStar:
3599 // C++ [over.built]p6:
3600 // For every cv-qualified or cv-unqualified object type T, there
3601 // exist candidate operator functions of the form
3602 //
3603 // T& operator*(T*);
3604 //
3605 // C++ [over.built]p7:
3606 // For every function type T, there exist candidate operator
3607 // functions of the form
3608 // T& operator*(T*);
3609 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3610 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3611 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003612 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003613 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003614 &ParamTy, Args, 1, CandidateSet);
3615 }
3616 break;
3617
3618 UnaryPlus:
3619 // C++ [over.built]p8:
3620 // For every type T, there exist candidate operator functions of
3621 // the form
3622 //
3623 // T* operator+(T*);
3624 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3625 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3626 QualType ParamTy = *Ptr;
3627 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3628 }
Mike Stump1eb44332009-09-09 15:08:12 +00003629
Douglas Gregor74253732008-11-19 15:42:04 +00003630 // Fall through
3631
3632 UnaryMinus:
3633 // C++ [over.built]p9:
3634 // For every promoted arithmetic type T, there exist candidate
3635 // operator functions of the form
3636 //
3637 // T operator+(T);
3638 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003639 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003640 Arith < LastPromotedArithmeticType; ++Arith) {
3641 QualType ArithTy = ArithmeticTypes[Arith];
3642 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3643 }
3644 break;
3645
3646 case OO_Tilde:
3647 // C++ [over.built]p10:
3648 // For every promoted integral type T, there exist candidate
3649 // operator functions of the form
3650 //
3651 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003652 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003653 Int < LastPromotedIntegralType; ++Int) {
3654 QualType IntTy = ArithmeticTypes[Int];
3655 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3656 }
3657 break;
3658
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003659 case OO_New:
3660 case OO_Delete:
3661 case OO_Array_New:
3662 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003663 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003664 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003665 break;
3666
3667 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003668 UnaryAmp:
3669 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003670 // C++ [over.match.oper]p3:
3671 // -- For the operator ',', the unary operator '&', or the
3672 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003673 break;
3674
Douglas Gregor19b7b152009-08-24 13:43:27 +00003675 case OO_EqualEqual:
3676 case OO_ExclaimEqual:
3677 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003678 // For every pointer to member type T, there exist candidate operator
3679 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003680 //
3681 // bool operator==(T,T);
3682 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003683 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003684 MemPtr = CandidateTypes.member_pointer_begin(),
3685 MemPtrEnd = CandidateTypes.member_pointer_end();
3686 MemPtr != MemPtrEnd;
3687 ++MemPtr) {
3688 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3689 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3690 }
Mike Stump1eb44332009-09-09 15:08:12 +00003691
Douglas Gregor19b7b152009-08-24 13:43:27 +00003692 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003693
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003694 case OO_Less:
3695 case OO_Greater:
3696 case OO_LessEqual:
3697 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003698 // C++ [over.built]p15:
3699 //
3700 // For every pointer or enumeration type T, there exist
3701 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003702 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003703 // bool operator<(T, T);
3704 // bool operator>(T, T);
3705 // bool operator<=(T, T);
3706 // bool operator>=(T, T);
3707 // bool operator==(T, T);
3708 // bool operator!=(T, T);
3709 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3710 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3711 QualType ParamTypes[2] = { *Ptr, *Ptr };
3712 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3713 }
Mike Stump1eb44332009-09-09 15:08:12 +00003714 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003715 = CandidateTypes.enumeration_begin();
3716 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3717 QualType ParamTypes[2] = { *Enum, *Enum };
3718 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3719 }
3720
3721 // Fall through.
3722 isComparison = true;
3723
Douglas Gregor74253732008-11-19 15:42:04 +00003724 BinaryPlus:
3725 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003726 if (!isComparison) {
3727 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3728
3729 // C++ [over.built]p13:
3730 //
3731 // For every cv-qualified or cv-unqualified object type T
3732 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003733 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003734 // T* operator+(T*, ptrdiff_t);
3735 // T& operator[](T*, ptrdiff_t); [BELOW]
3736 // T* operator-(T*, ptrdiff_t);
3737 // T* operator+(ptrdiff_t, T*);
3738 // T& operator[](ptrdiff_t, T*); [BELOW]
3739 //
3740 // C++ [over.built]p14:
3741 //
3742 // For every T, where T is a pointer to object type, there
3743 // exist candidate operator functions of the form
3744 //
3745 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003746 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003747 = CandidateTypes.pointer_begin();
3748 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3749 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3750
3751 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3752 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3753
3754 if (Op == OO_Plus) {
3755 // T* operator+(ptrdiff_t, T*);
3756 ParamTypes[0] = ParamTypes[1];
3757 ParamTypes[1] = *Ptr;
3758 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3759 } else {
3760 // ptrdiff_t operator-(T, T);
3761 ParamTypes[1] = *Ptr;
3762 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3763 Args, 2, CandidateSet);
3764 }
3765 }
3766 }
3767 // Fall through
3768
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003769 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003770 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003771 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003772 // C++ [over.built]p12:
3773 //
3774 // For every pair of promoted arithmetic types L and R, there
3775 // exist candidate operator functions of the form
3776 //
3777 // LR operator*(L, R);
3778 // LR operator/(L, R);
3779 // LR operator+(L, R);
3780 // LR operator-(L, R);
3781 // bool operator<(L, R);
3782 // bool operator>(L, R);
3783 // bool operator<=(L, R);
3784 // bool operator>=(L, R);
3785 // bool operator==(L, R);
3786 // bool operator!=(L, R);
3787 //
3788 // where LR is the result of the usual arithmetic conversions
3789 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003790 //
3791 // C++ [over.built]p24:
3792 //
3793 // For every pair of promoted arithmetic types L and R, there exist
3794 // candidate operator functions of the form
3795 //
3796 // LR operator?(bool, L, R);
3797 //
3798 // where LR is the result of the usual arithmetic conversions
3799 // between types L and R.
3800 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003801 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003802 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003803 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003804 Right < LastPromotedArithmeticType; ++Right) {
3805 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003806 QualType Result
3807 = isComparison
3808 ? Context.BoolTy
3809 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003810 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3811 }
3812 }
3813 break;
3814
3815 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003816 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003817 case OO_Caret:
3818 case OO_Pipe:
3819 case OO_LessLess:
3820 case OO_GreaterGreater:
3821 // C++ [over.built]p17:
3822 //
3823 // For every pair of promoted integral types L and R, there
3824 // exist candidate operator functions of the form
3825 //
3826 // LR operator%(L, R);
3827 // LR operator&(L, R);
3828 // LR operator^(L, R);
3829 // LR operator|(L, R);
3830 // L operator<<(L, R);
3831 // L operator>>(L, R);
3832 //
3833 // where LR is the result of the usual arithmetic conversions
3834 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003835 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003836 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003837 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003838 Right < LastPromotedIntegralType; ++Right) {
3839 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3840 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3841 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003842 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003843 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3844 }
3845 }
3846 break;
3847
3848 case OO_Equal:
3849 // C++ [over.built]p20:
3850 //
3851 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003852 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003853 // empty, there exist candidate operator functions of the form
3854 //
3855 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003856 for (BuiltinCandidateTypeSet::iterator
3857 Enum = CandidateTypes.enumeration_begin(),
3858 EnumEnd = CandidateTypes.enumeration_end();
3859 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003860 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003861 CandidateSet);
3862 for (BuiltinCandidateTypeSet::iterator
3863 MemPtr = CandidateTypes.member_pointer_begin(),
3864 MemPtrEnd = CandidateTypes.member_pointer_end();
3865 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003866 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003867 CandidateSet);
3868 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003869
3870 case OO_PlusEqual:
3871 case OO_MinusEqual:
3872 // C++ [over.built]p19:
3873 //
3874 // For every pair (T, VQ), where T is any type and VQ is either
3875 // volatile or empty, there exist candidate operator functions
3876 // of the form
3877 //
3878 // T*VQ& operator=(T*VQ&, T*);
3879 //
3880 // C++ [over.built]p21:
3881 //
3882 // For every pair (T, VQ), where T is a cv-qualified or
3883 // cv-unqualified object type and VQ is either volatile or
3884 // empty, there exist candidate operator functions of the form
3885 //
3886 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3887 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3888 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3889 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3890 QualType ParamTypes[2];
3891 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3892
3893 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003894 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003895 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3896 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003897
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003898 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3899 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003900 // volatile version
John McCall0953e762009-09-24 19:53:00 +00003901 ParamTypes[0]
3902 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003903 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3904 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003905 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003906 }
3907 // Fall through.
3908
3909 case OO_StarEqual:
3910 case OO_SlashEqual:
3911 // C++ [over.built]p18:
3912 //
3913 // For every triple (L, VQ, R), where L is an arithmetic type,
3914 // VQ is either volatile or empty, and R is a promoted
3915 // arithmetic type, there exist candidate operator functions of
3916 // the form
3917 //
3918 // VQ L& operator=(VQ L&, R);
3919 // VQ L& operator*=(VQ L&, R);
3920 // VQ L& operator/=(VQ L&, R);
3921 // VQ L& operator+=(VQ L&, R);
3922 // VQ L& operator-=(VQ L&, R);
3923 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003924 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003925 Right < LastPromotedArithmeticType; ++Right) {
3926 QualType ParamTypes[2];
3927 ParamTypes[1] = ArithmeticTypes[Right];
3928
3929 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003930 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003931 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3932 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003933
3934 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003935 if (VisibleTypeConversionsQuals.hasVolatile()) {
3936 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3937 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3938 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3939 /*IsAssigmentOperator=*/Op == OO_Equal);
3940 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003941 }
3942 }
3943 break;
3944
3945 case OO_PercentEqual:
3946 case OO_LessLessEqual:
3947 case OO_GreaterGreaterEqual:
3948 case OO_AmpEqual:
3949 case OO_CaretEqual:
3950 case OO_PipeEqual:
3951 // C++ [over.built]p22:
3952 //
3953 // For every triple (L, VQ, R), where L is an integral type, VQ
3954 // is either volatile or empty, and R is a promoted integral
3955 // type, there exist candidate operator functions of the form
3956 //
3957 // VQ L& operator%=(VQ L&, R);
3958 // VQ L& operator<<=(VQ L&, R);
3959 // VQ L& operator>>=(VQ L&, R);
3960 // VQ L& operator&=(VQ L&, R);
3961 // VQ L& operator^=(VQ L&, R);
3962 // VQ L& operator|=(VQ L&, R);
3963 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003964 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003965 Right < LastPromotedIntegralType; ++Right) {
3966 QualType ParamTypes[2];
3967 ParamTypes[1] = ArithmeticTypes[Right];
3968
3969 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003970 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003971 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00003972 if (VisibleTypeConversionsQuals.hasVolatile()) {
3973 // Add this built-in operator as a candidate (VQ is 'volatile').
3974 ParamTypes[0] = ArithmeticTypes[Left];
3975 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3976 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3977 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3978 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003979 }
3980 }
3981 break;
3982
Douglas Gregor74253732008-11-19 15:42:04 +00003983 case OO_Exclaim: {
3984 // C++ [over.operator]p23:
3985 //
3986 // There also exist candidate operator functions of the form
3987 //
Mike Stump1eb44332009-09-09 15:08:12 +00003988 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00003989 // bool operator&&(bool, bool); [BELOW]
3990 // bool operator||(bool, bool); [BELOW]
3991 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003992 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3993 /*IsAssignmentOperator=*/false,
3994 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003995 break;
3996 }
3997
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003998 case OO_AmpAmp:
3999 case OO_PipePipe: {
4000 // C++ [over.operator]p23:
4001 //
4002 // There also exist candidate operator functions of the form
4003 //
Douglas Gregor74253732008-11-19 15:42:04 +00004004 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004005 // bool operator&&(bool, bool);
4006 // bool operator||(bool, bool);
4007 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004008 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4009 /*IsAssignmentOperator=*/false,
4010 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004011 break;
4012 }
4013
4014 case OO_Subscript:
4015 // C++ [over.built]p13:
4016 //
4017 // For every cv-qualified or cv-unqualified object type T there
4018 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004019 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004020 // T* operator+(T*, ptrdiff_t); [ABOVE]
4021 // T& operator[](T*, ptrdiff_t);
4022 // T* operator-(T*, ptrdiff_t); [ABOVE]
4023 // T* operator+(ptrdiff_t, T*); [ABOVE]
4024 // T& operator[](ptrdiff_t, T*);
4025 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4026 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4027 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00004028 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004029 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004030
4031 // T& operator[](T*, ptrdiff_t)
4032 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4033
4034 // T& operator[](ptrdiff_t, T*);
4035 ParamTypes[0] = ParamTypes[1];
4036 ParamTypes[1] = *Ptr;
4037 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4038 }
4039 break;
4040
4041 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004042 // C++ [over.built]p11:
4043 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4044 // C1 is the same type as C2 or is a derived class of C2, T is an object
4045 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4046 // there exist candidate operator functions of the form
4047 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4048 // where CV12 is the union of CV1 and CV2.
4049 {
4050 for (BuiltinCandidateTypeSet::iterator Ptr =
4051 CandidateTypes.pointer_begin();
4052 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4053 QualType C1Ty = (*Ptr);
4054 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004055 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004056 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004057 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004058 if (!isa<RecordType>(C1))
4059 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004060 // heuristic to reduce number of builtin candidates in the set.
4061 // Add volatile/restrict version only if there are conversions to a
4062 // volatile/restrict type.
4063 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4064 continue;
4065 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4066 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004067 }
4068 for (BuiltinCandidateTypeSet::iterator
4069 MemPtr = CandidateTypes.member_pointer_begin(),
4070 MemPtrEnd = CandidateTypes.member_pointer_end();
4071 MemPtr != MemPtrEnd; ++MemPtr) {
4072 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4073 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00004074 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004075 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4076 break;
4077 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4078 // build CV12 T&
4079 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004080 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4081 T.isVolatileQualified())
4082 continue;
4083 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4084 T.isRestrictQualified())
4085 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004086 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004087 QualType ResultTy = Context.getLValueReferenceType(T);
4088 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4089 }
4090 }
4091 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004092 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004093
4094 case OO_Conditional:
4095 // Note that we don't consider the first argument, since it has been
4096 // contextually converted to bool long ago. The candidates below are
4097 // therefore added as binary.
4098 //
4099 // C++ [over.built]p24:
4100 // For every type T, where T is a pointer or pointer-to-member type,
4101 // there exist candidate operator functions of the form
4102 //
4103 // T operator?(bool, T, T);
4104 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004105 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4106 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4107 QualType ParamTypes[2] = { *Ptr, *Ptr };
4108 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4109 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00004110 for (BuiltinCandidateTypeSet::iterator Ptr =
4111 CandidateTypes.member_pointer_begin(),
4112 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4113 QualType ParamTypes[2] = { *Ptr, *Ptr };
4114 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4115 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004116 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004117 }
4118}
4119
Douglas Gregorfa047642009-02-04 00:32:51 +00004120/// \brief Add function candidates found via argument-dependent lookup
4121/// to the set of overloading candidates.
4122///
4123/// This routine performs argument-dependent name lookup based on the
4124/// given function name (which may also be an operator name) and adds
4125/// all of the overload candidates found by ADL to the overload
4126/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004127void
Douglas Gregorfa047642009-02-04 00:32:51 +00004128Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00004129 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00004130 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004131 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004132 OverloadCandidateSet& CandidateSet,
4133 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00004134 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00004135
John McCalla113e722010-01-26 06:04:06 +00004136 // FIXME: This approach for uniquing ADL results (and removing
4137 // redundant candidates from the set) relies on pointer-equality,
4138 // which means we need to key off the canonical decl. However,
4139 // always going back to the canonical decl might not get us the
4140 // right set of default arguments. What default arguments are
4141 // we supposed to consider on ADL candidates, anyway?
4142
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004143 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00004144 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00004145
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004146 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004147 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4148 CandEnd = CandidateSet.end();
4149 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004150 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00004151 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004152 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00004153 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00004154 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004155
4156 // For each of the ADL candidates we found, add it to the overload
4157 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00004158 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00004159 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00004160 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004161 continue;
4162
John McCall86820f52010-01-26 01:37:31 +00004163 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004164 false, false, PartialOverloading);
4165 } else
John McCall6e266892010-01-26 03:27:55 +00004166 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall86820f52010-01-26 01:37:31 +00004167 AS_none, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004168 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004169 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004170}
4171
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004172/// isBetterOverloadCandidate - Determines whether the first overload
4173/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004174bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004175Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump1eb44332009-09-09 15:08:12 +00004176 const OverloadCandidate& Cand2) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004177 // Define viable functions to be better candidates than non-viable
4178 // functions.
4179 if (!Cand2.Viable)
4180 return Cand1.Viable;
4181 else if (!Cand1.Viable)
4182 return false;
4183
Douglas Gregor88a35142008-12-22 05:46:06 +00004184 // C++ [over.match.best]p1:
4185 //
4186 // -- if F is a static member function, ICS1(F) is defined such
4187 // that ICS1(F) is neither better nor worse than ICS1(G) for
4188 // any function G, and, symmetrically, ICS1(G) is neither
4189 // better nor worse than ICS1(F).
4190 unsigned StartArg = 0;
4191 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4192 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004193
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004194 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004195 // A viable function F1 is defined to be a better function than another
4196 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004197 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004198 unsigned NumArgs = Cand1.Conversions.size();
4199 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4200 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004201 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004202 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4203 Cand2.Conversions[ArgIdx])) {
4204 case ImplicitConversionSequence::Better:
4205 // Cand1 has a better conversion sequence.
4206 HasBetterConversion = true;
4207 break;
4208
4209 case ImplicitConversionSequence::Worse:
4210 // Cand1 can't be better than Cand2.
4211 return false;
4212
4213 case ImplicitConversionSequence::Indistinguishable:
4214 // Do nothing.
4215 break;
4216 }
4217 }
4218
Mike Stump1eb44332009-09-09 15:08:12 +00004219 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004220 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004221 if (HasBetterConversion)
4222 return true;
4223
Mike Stump1eb44332009-09-09 15:08:12 +00004224 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004225 // specialization, or, if not that,
4226 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4227 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4228 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004229
4230 // -- F1 and F2 are function template specializations, and the function
4231 // template for F1 is more specialized than the template for F2
4232 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004233 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004234 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4235 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004236 if (FunctionTemplateDecl *BetterTemplate
4237 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4238 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004239 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4240 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004241 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004242
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004243 // -- the context is an initialization by user-defined conversion
4244 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4245 // from the return type of F1 to the destination type (i.e.,
4246 // the type of the entity being initialized) is a better
4247 // conversion sequence than the standard conversion sequence
4248 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004249 if (Cand1.Function && Cand2.Function &&
4250 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004251 isa<CXXConversionDecl>(Cand2.Function)) {
4252 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4253 Cand2.FinalConversion)) {
4254 case ImplicitConversionSequence::Better:
4255 // Cand1 has a better conversion sequence.
4256 return true;
4257
4258 case ImplicitConversionSequence::Worse:
4259 // Cand1 can't be better than Cand2.
4260 return false;
4261
4262 case ImplicitConversionSequence::Indistinguishable:
4263 // Do nothing
4264 break;
4265 }
4266 }
4267
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004268 return false;
4269}
4270
Mike Stump1eb44332009-09-09 15:08:12 +00004271/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004272/// within an overload candidate set.
4273///
4274/// \param CandidateSet the set of candidate functions.
4275///
4276/// \param Loc the location of the function name (or operator symbol) for
4277/// which overload resolution occurs.
4278///
Mike Stump1eb44332009-09-09 15:08:12 +00004279/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004280/// function, Best points to the candidate function found.
4281///
4282/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00004283OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4284 SourceLocation Loc,
4285 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004286 // Find the best viable function.
4287 Best = CandidateSet.end();
4288 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4289 Cand != CandidateSet.end(); ++Cand) {
4290 if (Cand->Viable) {
4291 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4292 Best = Cand;
4293 }
4294 }
4295
4296 // If we didn't find any viable functions, abort.
4297 if (Best == CandidateSet.end())
4298 return OR_No_Viable_Function;
4299
4300 // Make sure that this function is better than every other viable
4301 // function. If not, we have an ambiguity.
4302 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4303 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00004304 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004305 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004306 !isBetterOverloadCandidate(*Best, *Cand)) {
4307 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004308 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004309 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004310 }
Mike Stump1eb44332009-09-09 15:08:12 +00004311
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004312 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004313 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00004314 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004315 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004316 return OR_Deleted;
4317
Douglas Gregore0762c92009-06-19 23:52:42 +00004318 // C++ [basic.def.odr]p2:
4319 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00004320 // when referred to from a potentially-evaluated expression. [Note: this
4321 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00004322 // (clause 13), user-defined conversions (12.3.2), allocation function for
4323 // placement new (5.3.4), as well as non-default initialization (8.5).
4324 if (Best->Function)
4325 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004326 return OR_Success;
4327}
4328
John McCall3c80f572010-01-12 02:15:36 +00004329namespace {
4330
4331enum OverloadCandidateKind {
4332 oc_function,
4333 oc_method,
4334 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004335 oc_function_template,
4336 oc_method_template,
4337 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00004338 oc_implicit_default_constructor,
4339 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004340 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00004341};
4342
John McCall220ccbf2010-01-13 00:25:19 +00004343OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4344 FunctionDecl *Fn,
4345 std::string &Description) {
4346 bool isTemplate = false;
4347
4348 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4349 isTemplate = true;
4350 Description = S.getTemplateArgumentBindingsText(
4351 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4352 }
John McCallb1622a12010-01-06 09:43:14 +00004353
4354 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00004355 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004356 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004357
John McCall3c80f572010-01-12 02:15:36 +00004358 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4359 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004360 }
4361
4362 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4363 // This actually gets spelled 'candidate function' for now, but
4364 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00004365 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004366 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00004367
4368 assert(Meth->isCopyAssignment()
4369 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00004370 return oc_implicit_copy_assignment;
4371 }
4372
John McCall220ccbf2010-01-13 00:25:19 +00004373 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00004374}
4375
4376} // end anonymous namespace
4377
4378// Notes the location of an overload candidate.
4379void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00004380 std::string FnDesc;
4381 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4382 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4383 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00004384}
4385
John McCall1d318332010-01-12 00:44:57 +00004386/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4387/// "lead" diagnostic; it will be given two arguments, the source and
4388/// target types of the conversion.
4389void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4390 SourceLocation CaretLoc,
4391 const PartialDiagnostic &PDiag) {
4392 Diag(CaretLoc, PDiag)
4393 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4394 for (AmbiguousConversionSequence::const_iterator
4395 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4396 NoteOverloadCandidate(*I);
4397 }
John McCall81201622010-01-08 04:41:39 +00004398}
4399
John McCall1d318332010-01-12 00:44:57 +00004400namespace {
4401
John McCalladbb8f82010-01-13 09:16:55 +00004402void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4403 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4404 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00004405 assert(Cand->Function && "for now, candidate must be a function");
4406 FunctionDecl *Fn = Cand->Function;
4407
4408 // There's a conversion slot for the object argument if this is a
4409 // non-constructor method. Note that 'I' corresponds the
4410 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00004411 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00004412 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00004413 if (I == 0)
4414 isObjectArgument = true;
4415 else
4416 I--;
John McCall220ccbf2010-01-13 00:25:19 +00004417 }
4418
John McCall220ccbf2010-01-13 00:25:19 +00004419 std::string FnDesc;
4420 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4421
John McCalladbb8f82010-01-13 09:16:55 +00004422 Expr *FromExpr = Conv.Bad.FromExpr;
4423 QualType FromTy = Conv.Bad.getFromType();
4424 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00004425
John McCall258b2032010-01-23 08:10:49 +00004426 // Do some hand-waving analysis to see if the non-viability is due
4427 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00004428 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4429 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4430 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4431 CToTy = RT->getPointeeType();
4432 else {
4433 // TODO: detect and diagnose the full richness of const mismatches.
4434 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4435 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4436 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4437 }
4438
4439 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4440 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4441 // It is dumb that we have to do this here.
4442 while (isa<ArrayType>(CFromTy))
4443 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4444 while (isa<ArrayType>(CToTy))
4445 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4446
4447 Qualifiers FromQs = CFromTy.getQualifiers();
4448 Qualifiers ToQs = CToTy.getQualifiers();
4449
4450 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4451 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4452 << (unsigned) FnKind << FnDesc
4453 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4454 << FromTy
4455 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4456 << (unsigned) isObjectArgument << I+1;
4457 return;
4458 }
4459
4460 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4461 assert(CVR && "unexpected qualifiers mismatch");
4462
4463 if (isObjectArgument) {
4464 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4465 << (unsigned) FnKind << FnDesc
4466 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4467 << FromTy << (CVR - 1);
4468 } else {
4469 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4470 << (unsigned) FnKind << FnDesc
4471 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4472 << FromTy << (CVR - 1) << I+1;
4473 }
4474 return;
4475 }
4476
John McCall258b2032010-01-23 08:10:49 +00004477 // Diagnose references or pointers to incomplete types differently,
4478 // since it's far from impossible that the incompleteness triggered
4479 // the failure.
4480 QualType TempFromTy = FromTy.getNonReferenceType();
4481 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4482 TempFromTy = PTy->getPointeeType();
4483 if (TempFromTy->isIncompleteType()) {
4484 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4485 << (unsigned) FnKind << FnDesc
4486 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4487 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4488 return;
4489 }
4490
John McCall651f3ee2010-01-14 03:28:57 +00004491 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00004492 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4493 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00004494 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00004495 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00004496}
4497
4498void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4499 unsigned NumFormalArgs) {
4500 // TODO: treat calls to a missing default constructor as a special case
4501
4502 FunctionDecl *Fn = Cand->Function;
4503 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4504
4505 unsigned MinParams = Fn->getMinRequiredArguments();
4506
4507 // at least / at most / exactly
4508 unsigned mode, modeCount;
4509 if (NumFormalArgs < MinParams) {
4510 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4511 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4512 mode = 0; // "at least"
4513 else
4514 mode = 2; // "exactly"
4515 modeCount = MinParams;
4516 } else {
4517 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4518 if (MinParams != FnTy->getNumArgs())
4519 mode = 1; // "at most"
4520 else
4521 mode = 2; // "exactly"
4522 modeCount = FnTy->getNumArgs();
4523 }
4524
4525 std::string Description;
4526 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4527
4528 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4529 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00004530}
4531
4532void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4533 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00004534 FunctionDecl *Fn = Cand->Function;
4535
John McCall81201622010-01-08 04:41:39 +00004536 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00004537 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00004538 std::string FnDesc;
4539 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00004540
4541 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00004542 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00004543 return;
John McCall81201622010-01-08 04:41:39 +00004544 }
4545
John McCall220ccbf2010-01-13 00:25:19 +00004546 // We don't really have anything else to say about viable candidates.
4547 if (Cand->Viable) {
4548 S.NoteOverloadCandidate(Fn);
4549 return;
4550 }
John McCall1d318332010-01-12 00:44:57 +00004551
John McCalladbb8f82010-01-13 09:16:55 +00004552 switch (Cand->FailureKind) {
4553 case ovl_fail_too_many_arguments:
4554 case ovl_fail_too_few_arguments:
4555 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00004556
John McCalladbb8f82010-01-13 09:16:55 +00004557 case ovl_fail_bad_deduction:
John McCall717e8912010-01-23 05:17:32 +00004558 case ovl_fail_trivial_conversion:
4559 case ovl_fail_bad_final_conversion:
John McCalladbb8f82010-01-13 09:16:55 +00004560 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00004561
John McCalladbb8f82010-01-13 09:16:55 +00004562 case ovl_fail_bad_conversion:
4563 for (unsigned I = 0, N = Cand->Conversions.size(); I != N; ++I)
4564 if (Cand->Conversions[I].isBad())
4565 return DiagnoseBadConversion(S, Cand, I);
4566
4567 // FIXME: this currently happens when we're called from SemaInit
4568 // when user-conversion overload fails. Figure out how to handle
4569 // those conditions and diagnose them well.
4570 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00004571 }
John McCalla1d7d622010-01-08 00:58:21 +00004572}
4573
4574void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4575 // Desugar the type of the surrogate down to a function type,
4576 // retaining as many typedefs as possible while still showing
4577 // the function type (and, therefore, its parameter types).
4578 QualType FnType = Cand->Surrogate->getConversionType();
4579 bool isLValueReference = false;
4580 bool isRValueReference = false;
4581 bool isPointer = false;
4582 if (const LValueReferenceType *FnTypeRef =
4583 FnType->getAs<LValueReferenceType>()) {
4584 FnType = FnTypeRef->getPointeeType();
4585 isLValueReference = true;
4586 } else if (const RValueReferenceType *FnTypeRef =
4587 FnType->getAs<RValueReferenceType>()) {
4588 FnType = FnTypeRef->getPointeeType();
4589 isRValueReference = true;
4590 }
4591 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4592 FnType = FnTypePtr->getPointeeType();
4593 isPointer = true;
4594 }
4595 // Desugar down to a function type.
4596 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4597 // Reconstruct the pointer/reference as appropriate.
4598 if (isPointer) FnType = S.Context.getPointerType(FnType);
4599 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4600 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4601
4602 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4603 << FnType;
4604}
4605
4606void NoteBuiltinOperatorCandidate(Sema &S,
4607 const char *Opc,
4608 SourceLocation OpLoc,
4609 OverloadCandidate *Cand) {
4610 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4611 std::string TypeStr("operator");
4612 TypeStr += Opc;
4613 TypeStr += "(";
4614 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4615 if (Cand->Conversions.size() == 1) {
4616 TypeStr += ")";
4617 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4618 } else {
4619 TypeStr += ", ";
4620 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4621 TypeStr += ")";
4622 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4623 }
4624}
4625
4626void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4627 OverloadCandidate *Cand) {
4628 unsigned NoOperands = Cand->Conversions.size();
4629 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4630 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00004631 if (ICS.isBad()) break; // all meaningless after first invalid
4632 if (!ICS.isAmbiguous()) continue;
4633
4634 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4635 PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00004636 }
4637}
4638
John McCall1b77e732010-01-15 23:32:50 +00004639SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4640 if (Cand->Function)
4641 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00004642 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00004643 return Cand->Surrogate->getLocation();
4644 return SourceLocation();
4645}
4646
John McCallbf65c0b2010-01-12 00:48:53 +00004647struct CompareOverloadCandidatesForDisplay {
4648 Sema &S;
4649 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00004650
4651 bool operator()(const OverloadCandidate *L,
4652 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00004653 // Fast-path this check.
4654 if (L == R) return false;
4655
John McCall81201622010-01-08 04:41:39 +00004656 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00004657 if (L->Viable) {
4658 if (!R->Viable) return true;
4659
4660 // TODO: introduce a tri-valued comparison for overload
4661 // candidates. Would be more worthwhile if we had a sort
4662 // that could exploit it.
4663 if (S.isBetterOverloadCandidate(*L, *R)) return true;
4664 if (S.isBetterOverloadCandidate(*R, *L)) return false;
4665 } else if (R->Viable)
4666 return false;
John McCall81201622010-01-08 04:41:39 +00004667
John McCall1b77e732010-01-15 23:32:50 +00004668 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00004669
John McCall1b77e732010-01-15 23:32:50 +00004670 // Criteria by which we can sort non-viable candidates:
4671 if (!L->Viable) {
4672 // 1. Arity mismatches come after other candidates.
4673 if (L->FailureKind == ovl_fail_too_many_arguments ||
4674 L->FailureKind == ovl_fail_too_few_arguments)
4675 return false;
4676 if (R->FailureKind == ovl_fail_too_many_arguments ||
4677 R->FailureKind == ovl_fail_too_few_arguments)
4678 return true;
John McCall81201622010-01-08 04:41:39 +00004679
John McCall717e8912010-01-23 05:17:32 +00004680 // 2. Bad conversions come first and are ordered by the number
4681 // of bad conversions and quality of good conversions.
4682 if (L->FailureKind == ovl_fail_bad_conversion) {
4683 if (R->FailureKind != ovl_fail_bad_conversion)
4684 return true;
4685
4686 // If there's any ordering between the defined conversions...
4687 // FIXME: this might not be transitive.
4688 assert(L->Conversions.size() == R->Conversions.size());
4689
4690 int leftBetter = 0;
4691 for (unsigned I = 0, E = L->Conversions.size(); I != E; ++I) {
4692 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
4693 R->Conversions[I])) {
4694 case ImplicitConversionSequence::Better:
4695 leftBetter++;
4696 break;
4697
4698 case ImplicitConversionSequence::Worse:
4699 leftBetter--;
4700 break;
4701
4702 case ImplicitConversionSequence::Indistinguishable:
4703 break;
4704 }
4705 }
4706 if (leftBetter > 0) return true;
4707 if (leftBetter < 0) return false;
4708
4709 } else if (R->FailureKind == ovl_fail_bad_conversion)
4710 return false;
4711
John McCall1b77e732010-01-15 23:32:50 +00004712 // TODO: others?
4713 }
4714
4715 // Sort everything else by location.
4716 SourceLocation LLoc = GetLocationForCandidate(L);
4717 SourceLocation RLoc = GetLocationForCandidate(R);
4718
4719 // Put candidates without locations (e.g. builtins) at the end.
4720 if (LLoc.isInvalid()) return false;
4721 if (RLoc.isInvalid()) return true;
4722
4723 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00004724 }
4725};
4726
John McCall717e8912010-01-23 05:17:32 +00004727/// CompleteNonViableCandidate - Normally, overload resolution only
4728/// computes up to the first
4729void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
4730 Expr **Args, unsigned NumArgs) {
4731 assert(!Cand->Viable);
4732
4733 // Don't do anything on failures other than bad conversion.
4734 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
4735
4736 // Skip forward to the first bad conversion.
4737 unsigned ConvIdx = 0;
4738 unsigned ConvCount = Cand->Conversions.size();
4739 while (true) {
4740 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
4741 ConvIdx++;
4742 if (Cand->Conversions[ConvIdx - 1].isBad())
4743 break;
4744 }
4745
4746 if (ConvIdx == ConvCount)
4747 return;
4748
4749 // FIXME: these should probably be preserved from the overload
4750 // operation somehow.
4751 bool SuppressUserConversions = false;
4752 bool ForceRValue = false;
4753
4754 const FunctionProtoType* Proto;
4755 unsigned ArgIdx = ConvIdx;
4756
4757 if (Cand->IsSurrogate) {
4758 QualType ConvType
4759 = Cand->Surrogate->getConversionType().getNonReferenceType();
4760 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4761 ConvType = ConvPtrType->getPointeeType();
4762 Proto = ConvType->getAs<FunctionProtoType>();
4763 ArgIdx--;
4764 } else if (Cand->Function) {
4765 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
4766 if (isa<CXXMethodDecl>(Cand->Function) &&
4767 !isa<CXXConstructorDecl>(Cand->Function))
4768 ArgIdx--;
4769 } else {
4770 // Builtin binary operator with a bad first conversion.
4771 assert(ConvCount <= 3);
4772 for (; ConvIdx != ConvCount; ++ConvIdx)
4773 Cand->Conversions[ConvIdx]
4774 = S.TryCopyInitialization(Args[ConvIdx],
4775 Cand->BuiltinTypes.ParamTypes[ConvIdx],
4776 SuppressUserConversions, ForceRValue,
4777 /*InOverloadResolution*/ true);
4778 return;
4779 }
4780
4781 // Fill in the rest of the conversions.
4782 unsigned NumArgsInProto = Proto->getNumArgs();
4783 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
4784 if (ArgIdx < NumArgsInProto)
4785 Cand->Conversions[ConvIdx]
4786 = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx),
4787 SuppressUserConversions, ForceRValue,
4788 /*InOverloadResolution=*/true);
4789 else
4790 Cand->Conversions[ConvIdx].setEllipsis();
4791 }
4792}
4793
John McCalla1d7d622010-01-08 00:58:21 +00004794} // end anonymous namespace
4795
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004796/// PrintOverloadCandidates - When overload resolution fails, prints
4797/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00004798/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00004799void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004800Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00004801 OverloadCandidateDisplayKind OCD,
John McCallcbce6062010-01-12 07:18:19 +00004802 Expr **Args, unsigned NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004803 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004804 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00004805 // Sort the candidates by viability and position. Sorting directly would
4806 // be prohibitive, so we make a set of pointers and sort those.
4807 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4808 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4809 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4810 LastCand = CandidateSet.end();
John McCall717e8912010-01-23 05:17:32 +00004811 Cand != LastCand; ++Cand) {
4812 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00004813 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00004814 else if (OCD == OCD_AllCandidates) {
4815 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
4816 Cands.push_back(Cand);
4817 }
4818 }
4819
John McCallbf65c0b2010-01-12 00:48:53 +00004820 std::sort(Cands.begin(), Cands.end(),
4821 CompareOverloadCandidatesForDisplay(*this));
John McCall81201622010-01-08 04:41:39 +00004822
John McCall1d318332010-01-12 00:44:57 +00004823 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00004824
John McCall81201622010-01-08 04:41:39 +00004825 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4826 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4827 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00004828
John McCalla1d7d622010-01-08 00:58:21 +00004829 if (Cand->Function)
John McCall220ccbf2010-01-13 00:25:19 +00004830 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00004831 else if (Cand->IsSurrogate)
4832 NoteSurrogateCandidate(*this, Cand);
4833
4834 // This a builtin candidate. We do not, in general, want to list
4835 // every possible builtin candidate.
John McCall1d318332010-01-12 00:44:57 +00004836 else if (Cand->Viable) {
4837 // Generally we only see ambiguities including viable builtin
4838 // operators if overload resolution got screwed up by an
4839 // ambiguous user-defined conversion.
4840 //
4841 // FIXME: It's quite possible for different conversions to see
4842 // different ambiguities, though.
4843 if (!ReportedAmbiguousConversions) {
4844 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4845 ReportedAmbiguousConversions = true;
4846 }
John McCalla1d7d622010-01-08 00:58:21 +00004847
John McCall1d318332010-01-12 00:44:57 +00004848 // If this is a viable builtin, print it.
John McCalla1d7d622010-01-08 00:58:21 +00004849 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004850 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004851 }
4852}
4853
Douglas Gregor904eed32008-11-10 20:40:00 +00004854/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4855/// an overloaded function (C++ [over.over]), where @p From is an
4856/// expression with overloaded function type and @p ToType is the type
4857/// we're trying to resolve to. For example:
4858///
4859/// @code
4860/// int f(double);
4861/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00004862///
Douglas Gregor904eed32008-11-10 20:40:00 +00004863/// int (*pfd)(double) = f; // selects f(double)
4864/// @endcode
4865///
4866/// This routine returns the resulting FunctionDecl if it could be
4867/// resolved, and NULL otherwise. When @p Complain is true, this
4868/// routine will emit diagnostics if there is an error.
4869FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00004870Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004871 bool Complain) {
4872 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00004873 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00004874 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00004875 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004876 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00004877 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00004878 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00004879 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004880 FunctionType = MemTypePtr->getPointeeType();
4881 IsMember = true;
4882 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004883
4884 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00004885 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00004886 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00004887 return 0;
4888
4889 // Find the actual overloaded function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004890
Douglas Gregor904eed32008-11-10 20:40:00 +00004891 // C++ [over.over]p1:
4892 // [...] [Note: any redundant set of parentheses surrounding the
4893 // overloaded function name is ignored (5.1). ]
4894 Expr *OvlExpr = From->IgnoreParens();
4895
4896 // C++ [over.over]p1:
4897 // [...] The overloaded function name can be preceded by the &
4898 // operator.
4899 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4900 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4901 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4902 }
4903
Anders Carlsson70534852009-10-20 22:53:47 +00004904 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004905 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCallba135432009-11-21 08:51:07 +00004906
4907 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlsson70534852009-10-20 22:53:47 +00004908
John McCall129e2df2009-11-30 22:42:35 +00004909 // Look into the overloaded expression.
John McCallf7a1a742009-11-24 19:00:30 +00004910 if (UnresolvedLookupExpr *UL
John McCallba135432009-11-21 08:51:07 +00004911 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4912 Fns.append(UL->decls_begin(), UL->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00004913 if (UL->hasExplicitTemplateArgs()) {
4914 HasExplicitTemplateArgs = true;
4915 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4916 }
John McCall129e2df2009-11-30 22:42:35 +00004917 } else if (UnresolvedMemberExpr *ME
4918 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4919 Fns.append(ME->decls_begin(), ME->decls_end());
4920 if (ME->hasExplicitTemplateArgs()) {
4921 HasExplicitTemplateArgs = true;
John McCalld5532b62009-11-23 01:53:49 +00004922 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004923 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00004924 }
Mike Stump1eb44332009-09-09 15:08:12 +00004925
John McCallba135432009-11-21 08:51:07 +00004926 // If we didn't actually find anything, we're done.
4927 if (Fns.empty())
4928 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004929
Douglas Gregor904eed32008-11-10 20:40:00 +00004930 // Look through all of the overloaded functions, searching for one
4931 // whose type matches exactly.
Douglas Gregor00aeb522009-07-08 23:33:52 +00004932 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004933 bool FoundNonTemplateFunction = false;
John McCallba135432009-11-21 08:51:07 +00004934 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4935 E = Fns.end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00004936 // Look through any using declarations to find the underlying function.
4937 NamedDecl *Fn = (*I)->getUnderlyingDecl();
4938
Douglas Gregor904eed32008-11-10 20:40:00 +00004939 // C++ [over.over]p3:
4940 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00004941 // targets of type "pointer-to-function" or "reference-to-function."
4942 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00004943 // type "pointer-to-member-function."
4944 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00004945
Mike Stump1eb44332009-09-09 15:08:12 +00004946 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00004947 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004948 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00004949 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004950 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00004951 // static when converting to member pointer.
4952 if (Method->isStatic() == IsMember)
4953 continue;
4954 } else if (IsMember)
4955 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00004956
Douglas Gregor00aeb522009-07-08 23:33:52 +00004957 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004958 // If the name is a function template, template argument deduction is
4959 // done (14.8.2.2), and if the argument deduction succeeds, the
4960 // resulting template argument list is used to generate a single
4961 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00004962 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004963 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00004964 FunctionDecl *Specialization = 0;
4965 TemplateDeductionInfo Info(Context);
4966 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004967 = DeduceTemplateArguments(FunctionTemplate,
4968 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor83314aa2009-07-08 20:55:45 +00004969 FunctionType, Specialization, Info)) {
4970 // FIXME: make a note of the failed deduction for diagnostics.
4971 (void)Result;
4972 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004973 // FIXME: If the match isn't exact, shouldn't we just drop this as
4974 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00004975 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00004976 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004977 Matches.insert(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00004978 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor83314aa2009-07-08 20:55:45 +00004979 }
John McCallba135432009-11-21 08:51:07 +00004980
4981 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00004982 }
Mike Stump1eb44332009-09-09 15:08:12 +00004983
Chandler Carruthbd647292009-12-29 06:17:27 +00004984 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004985 // Skip non-static functions when converting to pointer, and static
4986 // when converting to member pointer.
4987 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00004988 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00004989
4990 // If we have explicit template arguments, skip non-templates.
4991 if (HasExplicitTemplateArgs)
4992 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004993 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00004994 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00004995
Chandler Carruthbd647292009-12-29 06:17:27 +00004996 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00004997 QualType ResultTy;
4998 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4999 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5000 ResultTy)) {
John McCallba135432009-11-21 08:51:07 +00005001 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00005002 FoundNonTemplateFunction = true;
5003 }
Mike Stump1eb44332009-09-09 15:08:12 +00005004 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005005 }
5006
Douglas Gregor00aeb522009-07-08 23:33:52 +00005007 // If there were 0 or 1 matches, we're done.
5008 if (Matches.empty())
5009 return 0;
Sebastian Redl07ab2022009-10-17 21:12:09 +00005010 else if (Matches.size() == 1) {
5011 FunctionDecl *Result = *Matches.begin();
5012 MarkDeclarationReferenced(From->getLocStart(), Result);
5013 return Result;
5014 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00005015
5016 // C++ [over.over]p4:
5017 // If more than one function is selected, [...]
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005018 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregor312a2022009-09-26 03:56:17 +00005019 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005020 // [...] and any given function template specialization F1 is
5021 // eliminated if the set contains a second function template
5022 // specialization whose function template is more specialized
5023 // than the function template of F1 according to the partial
5024 // ordering rules of 14.5.5.2.
5025
5026 // The algorithm specified above is quadratic. We instead use a
5027 // two-pass algorithm (similar to the one used to identify the
5028 // best viable function in an overload set) that identifies the
5029 // best function template (if it exists).
Sebastian Redl07ab2022009-10-17 21:12:09 +00005030 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregor312a2022009-09-26 03:56:17 +00005031 Matches.end());
Sebastian Redl07ab2022009-10-17 21:12:09 +00005032 FunctionDecl *Result =
5033 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
5034 TPOC_Other, From->getLocStart(),
5035 PDiag(),
5036 PDiag(diag::err_addr_ovl_ambiguous)
5037 << TemplateMatches[0]->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00005038 PDiag(diag::note_ovl_candidate)
5039 << (unsigned) oc_function_template);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005040 MarkDeclarationReferenced(From->getLocStart(), Result);
5041 return Result;
Douglas Gregor00aeb522009-07-08 23:33:52 +00005042 }
Mike Stump1eb44332009-09-09 15:08:12 +00005043
Douglas Gregor312a2022009-09-26 03:56:17 +00005044 // [...] any function template specializations in the set are
5045 // eliminated if the set also contains a non-template function, [...]
5046 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
5047 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
5048 if ((*M)->getPrimaryTemplate() == 0)
5049 RemainingMatches.push_back(*M);
5050
Mike Stump1eb44332009-09-09 15:08:12 +00005051 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00005052 // selected function.
Sebastian Redl07ab2022009-10-17 21:12:09 +00005053 if (RemainingMatches.size() == 1) {
5054 FunctionDecl *Result = RemainingMatches.front();
5055 MarkDeclarationReferenced(From->getLocStart(), Result);
5056 return Result;
5057 }
Mike Stump1eb44332009-09-09 15:08:12 +00005058
Douglas Gregor00aeb522009-07-08 23:33:52 +00005059 // FIXME: We should probably return the same thing that BestViableFunction
5060 // returns (even if we issue the diagnostics here).
5061 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
5062 << RemainingMatches[0]->getDeclName();
5063 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
John McCallb1622a12010-01-06 09:43:14 +00005064 NoteOverloadCandidate(RemainingMatches[I]);
Douglas Gregor904eed32008-11-10 20:40:00 +00005065 return 0;
5066}
5067
Douglas Gregor4b52e252009-12-21 23:17:24 +00005068/// \brief Given an expression that refers to an overloaded function, try to
5069/// resolve that overloaded function expression down to a single function.
5070///
5071/// This routine can only resolve template-ids that refer to a single function
5072/// template, where that template-id refers to a single template whose template
5073/// arguments are either provided by the template-id or have defaults,
5074/// as described in C++0x [temp.arg.explicit]p3.
5075FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5076 // C++ [over.over]p1:
5077 // [...] [Note: any redundant set of parentheses surrounding the
5078 // overloaded function name is ignored (5.1). ]
5079 Expr *OvlExpr = From->IgnoreParens();
5080
5081 // C++ [over.over]p1:
5082 // [...] The overloaded function name can be preceded by the &
5083 // operator.
5084 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
5085 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
5086 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
5087 }
5088
5089 bool HasExplicitTemplateArgs = false;
5090 TemplateArgumentListInfo ExplicitTemplateArgs;
5091
5092 llvm::SmallVector<NamedDecl*,8> Fns;
5093
5094 // Look into the overloaded expression.
5095 if (UnresolvedLookupExpr *UL
5096 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
5097 Fns.append(UL->decls_begin(), UL->decls_end());
5098 if (UL->hasExplicitTemplateArgs()) {
5099 HasExplicitTemplateArgs = true;
5100 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
5101 }
5102 } else if (UnresolvedMemberExpr *ME
5103 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
5104 Fns.append(ME->decls_begin(), ME->decls_end());
5105 if (ME->hasExplicitTemplateArgs()) {
5106 HasExplicitTemplateArgs = true;
5107 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
5108 }
5109 }
5110
5111 // If we didn't actually find any template-ids, we're done.
5112 if (Fns.empty() || !HasExplicitTemplateArgs)
5113 return 0;
5114
5115 // Look through all of the overloaded functions, searching for one
5116 // whose type matches exactly.
5117 FunctionDecl *Matched = 0;
5118 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
5119 E = Fns.end(); I != E; ++I) {
5120 // C++0x [temp.arg.explicit]p3:
5121 // [...] In contexts where deduction is done and fails, or in contexts
5122 // where deduction is not done, if a template argument list is
5123 // specified and it, along with any default template arguments,
5124 // identifies a single function template specialization, then the
5125 // template-id is an lvalue for the function template specialization.
5126 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5127
5128 // C++ [over.over]p2:
5129 // If the name is a function template, template argument deduction is
5130 // done (14.8.2.2), and if the argument deduction succeeds, the
5131 // resulting template argument list is used to generate a single
5132 // function template specialization, which is added to the set of
5133 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00005134 FunctionDecl *Specialization = 0;
5135 TemplateDeductionInfo Info(Context);
5136 if (TemplateDeductionResult Result
5137 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5138 Specialization, Info)) {
5139 // FIXME: make a note of the failed deduction for diagnostics.
5140 (void)Result;
5141 continue;
5142 }
5143
5144 // Multiple matches; we can't resolve to a single declaration.
5145 if (Matched)
5146 return 0;
5147
5148 Matched = Specialization;
5149 }
5150
5151 return Matched;
5152}
5153
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005154/// \brief Add a single candidate to the overload set.
5155static void AddOverloadedCallCandidate(Sema &S,
John McCallba135432009-11-21 08:51:07 +00005156 NamedDecl *Callee,
John McCall86820f52010-01-26 01:37:31 +00005157 AccessSpecifier Access,
John McCalld5532b62009-11-23 01:53:49 +00005158 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005159 Expr **Args, unsigned NumArgs,
5160 OverloadCandidateSet &CandidateSet,
5161 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00005162 if (isa<UsingShadowDecl>(Callee))
5163 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5164
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005165 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00005166 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall86820f52010-01-26 01:37:31 +00005167 S.AddOverloadCandidate(Func, Access, Args, NumArgs, CandidateSet,
5168 false, false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005169 return;
John McCallba135432009-11-21 08:51:07 +00005170 }
5171
5172 if (FunctionTemplateDecl *FuncTemplate
5173 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall86820f52010-01-26 01:37:31 +00005174 S.AddTemplateOverloadCandidate(FuncTemplate, Access, ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005175 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00005176 return;
5177 }
5178
5179 assert(false && "unhandled case in overloaded call candidate");
5180
5181 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005182}
5183
5184/// \brief Add the overload candidates named by callee and/or found by argument
5185/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00005186void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005187 Expr **Args, unsigned NumArgs,
5188 OverloadCandidateSet &CandidateSet,
5189 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00005190
5191#ifndef NDEBUG
5192 // Verify that ArgumentDependentLookup is consistent with the rules
5193 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005194 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005195 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5196 // and let Y be the lookup set produced by argument dependent
5197 // lookup (defined as follows). If X contains
5198 //
5199 // -- a declaration of a class member, or
5200 //
5201 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00005202 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005203 //
5204 // -- a declaration that is neither a function or a function
5205 // template
5206 //
5207 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00005208
John McCall3b4294e2009-12-16 12:17:52 +00005209 if (ULE->requiresADL()) {
5210 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5211 E = ULE->decls_end(); I != E; ++I) {
5212 assert(!(*I)->getDeclContext()->isRecord());
5213 assert(isa<UsingShadowDecl>(*I) ||
5214 !(*I)->getDeclContext()->isFunctionOrMethod());
5215 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00005216 }
5217 }
5218#endif
5219
John McCall3b4294e2009-12-16 12:17:52 +00005220 // It would be nice to avoid this copy.
5221 TemplateArgumentListInfo TABuffer;
5222 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5223 if (ULE->hasExplicitTemplateArgs()) {
5224 ULE->copyTemplateArgumentsInto(TABuffer);
5225 ExplicitTemplateArgs = &TABuffer;
5226 }
5227
5228 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5229 E = ULE->decls_end(); I != E; ++I)
John McCall86820f52010-01-26 01:37:31 +00005230 AddOverloadedCallCandidate(*this, *I, I.getAccess(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005231 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005232 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00005233
John McCall3b4294e2009-12-16 12:17:52 +00005234 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00005235 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5236 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005237 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005238 CandidateSet,
5239 PartialOverloading);
5240}
John McCall578b69b2009-12-16 08:11:27 +00005241
John McCall3b4294e2009-12-16 12:17:52 +00005242static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5243 Expr **Args, unsigned NumArgs) {
5244 Fn->Destroy(SemaRef.Context);
5245 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5246 Args[Arg]->Destroy(SemaRef.Context);
5247 return SemaRef.ExprError();
5248}
5249
John McCall578b69b2009-12-16 08:11:27 +00005250/// Attempts to recover from a call where no functions were found.
5251///
5252/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00005253static Sema::OwningExprResult
5254BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5255 UnresolvedLookupExpr *ULE,
5256 SourceLocation LParenLoc,
5257 Expr **Args, unsigned NumArgs,
5258 SourceLocation *CommaLocs,
5259 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00005260
5261 CXXScopeSpec SS;
5262 if (ULE->getQualifier()) {
5263 SS.setScopeRep(ULE->getQualifier());
5264 SS.setRange(ULE->getQualifierRange());
5265 }
5266
John McCall3b4294e2009-12-16 12:17:52 +00005267 TemplateArgumentListInfo TABuffer;
5268 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5269 if (ULE->hasExplicitTemplateArgs()) {
5270 ULE->copyTemplateArgumentsInto(TABuffer);
5271 ExplicitTemplateArgs = &TABuffer;
5272 }
5273
John McCall578b69b2009-12-16 08:11:27 +00005274 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5275 Sema::LookupOrdinaryName);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00005276 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall3b4294e2009-12-16 12:17:52 +00005277 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCall578b69b2009-12-16 08:11:27 +00005278
John McCall3b4294e2009-12-16 12:17:52 +00005279 assert(!R.empty() && "lookup results empty despite recovery");
5280
5281 // Build an implicit member call if appropriate. Just drop the
5282 // casts and such from the call, we don't really care.
5283 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5284 if ((*R.begin())->isCXXClassMember())
5285 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5286 else if (ExplicitTemplateArgs)
5287 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5288 else
5289 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5290
5291 if (NewFn.isInvalid())
5292 return Destroy(SemaRef, Fn, Args, NumArgs);
5293
5294 Fn->Destroy(SemaRef.Context);
5295
5296 // This shouldn't cause an infinite loop because we're giving it
5297 // an expression with non-empty lookup results, which should never
5298 // end up here.
5299 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5300 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5301 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00005302}
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005303
Douglas Gregorf6b89692008-11-26 05:54:23 +00005304/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00005305/// (which eventually refers to the declaration Func) and the call
5306/// arguments Args/NumArgs, attempt to resolve the function call down
5307/// to a specific function. If overload resolution succeeds, returns
5308/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00005309/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00005310/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00005311Sema::OwningExprResult
5312Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5313 SourceLocation LParenLoc,
5314 Expr **Args, unsigned NumArgs,
5315 SourceLocation *CommaLocs,
5316 SourceLocation RParenLoc) {
5317#ifndef NDEBUG
5318 if (ULE->requiresADL()) {
5319 // To do ADL, we must have found an unqualified name.
5320 assert(!ULE->getQualifier() && "qualified name with ADL");
5321
5322 // We don't perform ADL for implicit declarations of builtins.
5323 // Verify that this was correctly set up.
5324 FunctionDecl *F;
5325 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5326 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5327 F->getBuiltinID() && F->isImplicit())
5328 assert(0 && "performing ADL for builtin");
5329
5330 // We don't perform ADL in C.
5331 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5332 }
5333#endif
5334
Douglas Gregorf6b89692008-11-26 05:54:23 +00005335 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00005336
John McCall3b4294e2009-12-16 12:17:52 +00005337 // Add the functions denoted by the callee to the set of candidate
5338 // functions, including those from argument-dependent lookup.
5339 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00005340
5341 // If we found nothing, try to recover.
5342 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5343 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00005344 if (CandidateSet.empty())
5345 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5346 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00005347
Douglas Gregorf6b89692008-11-26 05:54:23 +00005348 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005349 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00005350 case OR_Success: {
5351 FunctionDecl *FDecl = Best->Function;
5352 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5353 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5354 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00005355
5356 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00005357 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00005358 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00005359 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005360 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005361 break;
5362
5363 case OR_Ambiguous:
5364 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00005365 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005366 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005367 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005368
5369 case OR_Deleted:
5370 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5371 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00005372 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005373 << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005374 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005375 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00005376 }
5377
5378 // Overload resolution failed. Destroy all of the subexpressions and
5379 // return NULL.
5380 Fn->Destroy(Context);
5381 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5382 Args[Arg]->Destroy(Context);
John McCall3b4294e2009-12-16 12:17:52 +00005383 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00005384}
5385
John McCall6e266892010-01-26 03:27:55 +00005386static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00005387 return Functions.size() > 1 ||
5388 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5389}
5390
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005391/// \brief Create a unary operation that may resolve to an overloaded
5392/// operator.
5393///
5394/// \param OpLoc The location of the operator itself (e.g., '*').
5395///
5396/// \param OpcIn The UnaryOperator::Opcode that describes this
5397/// operator.
5398///
5399/// \param Functions The set of non-member functions that will be
5400/// considered by overload resolution. The caller needs to build this
5401/// set based on the context using, e.g.,
5402/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5403/// set should not contain any member functions; those will be added
5404/// by CreateOverloadedUnaryOp().
5405///
5406/// \param input The input argument.
John McCall6e266892010-01-26 03:27:55 +00005407Sema::OwningExprResult
5408Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5409 const UnresolvedSetImpl &Fns,
5410 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005411 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5412 Expr *Input = (Expr *)input.get();
5413
5414 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5415 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5416 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5417
5418 Expr *Args[2] = { Input, 0 };
5419 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00005420
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005421 // For post-increment and post-decrement, add the implicit '0' as
5422 // the second argument, so that we know this is a post-increment or
5423 // post-decrement.
5424 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5425 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00005426 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005427 SourceLocation());
5428 NumArgs = 2;
5429 }
5430
5431 if (Input->isTypeDependent()) {
John McCallba135432009-11-21 08:51:07 +00005432 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00005433 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5434 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00005435 /*ADL*/ true, IsOverloaded(Fns));
5436 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump1eb44332009-09-09 15:08:12 +00005437
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005438 input.release();
5439 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5440 &Args[0], NumArgs,
5441 Context.DependentTy,
5442 OpLoc));
5443 }
5444
5445 // Build an empty overload set.
5446 OverloadCandidateSet CandidateSet;
5447
5448 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00005449 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005450
5451 // Add operator candidates that are member functions.
5452 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5453
John McCall6e266892010-01-26 03:27:55 +00005454 // Add candidates from ADL.
5455 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5456 Args, 1,
5457 /*ExplicitTemplateArgs*/ 0,
5458 CandidateSet);
5459
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005460 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005461 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005462
5463 // Perform overload resolution.
5464 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005465 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005466 case OR_Success: {
5467 // We found a built-in operator or an overloaded operator.
5468 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00005469
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005470 if (FnDecl) {
5471 // We matched an overloaded operator. Build a call to that
5472 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00005473
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005474 // Convert the arguments.
5475 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
5476 if (PerformObjectArgumentInitialization(Input, Method))
5477 return ExprError();
5478 } else {
5479 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00005480 OwningExprResult InputInit
5481 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005482 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00005483 SourceLocation(),
5484 move(input));
5485 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005486 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005487
Douglas Gregore1a5c172009-12-23 17:40:29 +00005488 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005489 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005490 }
5491
5492 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00005493 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005494
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005495 // Build the actual expression node.
5496 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5497 SourceLocation());
5498 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00005499
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005500 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00005501 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00005502 ExprOwningPtr<CallExpr> TheCall(this,
5503 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00005504 Args, NumArgs, ResultTy, OpLoc));
Anders Carlsson26a2a072009-10-13 21:19:37 +00005505
5506 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5507 FnDecl))
5508 return ExprError();
5509
5510 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005511 } else {
5512 // We matched a built-in operator. Convert the arguments, then
5513 // break out so that we will build the appropriate built-in
5514 // operator node.
5515 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005516 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005517 return ExprError();
5518
5519 break;
5520 }
5521 }
5522
5523 case OR_No_Viable_Function:
5524 // No viable function; fall through to handling this as a
5525 // built-in operator, which will produce an error message for us.
5526 break;
5527
5528 case OR_Ambiguous:
5529 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5530 << UnaryOperator::getOpcodeStr(Opc)
5531 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005532 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005533 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005534 return ExprError();
5535
5536 case OR_Deleted:
5537 Diag(OpLoc, diag::err_ovl_deleted_oper)
5538 << Best->Function->isDeleted()
5539 << UnaryOperator::getOpcodeStr(Opc)
5540 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005541 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005542 return ExprError();
5543 }
5544
5545 // Either we found no viable overloaded operator or we matched a
5546 // built-in operator. In either case, fall through to trying to
5547 // build a built-in operation.
5548 input.release();
5549 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5550}
5551
Douglas Gregor063daf62009-03-13 18:40:31 +00005552/// \brief Create a binary operation that may resolve to an overloaded
5553/// operator.
5554///
5555/// \param OpLoc The location of the operator itself (e.g., '+').
5556///
5557/// \param OpcIn The BinaryOperator::Opcode that describes this
5558/// operator.
5559///
5560/// \param Functions The set of non-member functions that will be
5561/// considered by overload resolution. The caller needs to build this
5562/// set based on the context using, e.g.,
5563/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5564/// set should not contain any member functions; those will be added
5565/// by CreateOverloadedBinOp().
5566///
5567/// \param LHS Left-hand argument.
5568/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005569Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00005570Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005571 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00005572 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00005573 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00005574 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005575 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00005576
5577 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5578 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5579 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5580
5581 // If either side is type-dependent, create an appropriate dependent
5582 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005583 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00005584 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005585 // If there are no functions to store, just build a dependent
5586 // BinaryOperator or CompoundAssignment.
5587 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5588 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5589 Context.DependentTy, OpLoc));
5590
5591 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5592 Context.DependentTy,
5593 Context.DependentTy,
5594 Context.DependentTy,
5595 OpLoc));
5596 }
John McCall6e266892010-01-26 03:27:55 +00005597
5598 // FIXME: save results of ADL from here?
John McCallba135432009-11-21 08:51:07 +00005599 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00005600 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5601 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00005602 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump1eb44332009-09-09 15:08:12 +00005603
John McCall6e266892010-01-26 03:27:55 +00005604 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00005605 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00005606 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00005607 Context.DependentTy,
5608 OpLoc));
5609 }
5610
5611 // If this is the .* operator, which is not overloadable, just
5612 // create a built-in binary operator.
5613 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005614 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005615
Sebastian Redl275c2b42009-11-18 23:10:33 +00005616 // If this is the assignment operator, we only perform overload resolution
5617 // if the left-hand side is a class or enumeration type. This is actually
5618 // a hack. The standard requires that we do overload resolution between the
5619 // various built-in candidates, but as DR507 points out, this can lead to
5620 // problems. So we do it this way, which pretty much follows what GCC does.
5621 // Note that we go the traditional code path for compound assignment forms.
5622 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005623 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005624
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005625 // Build an empty overload set.
5626 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00005627
5628 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00005629 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00005630
5631 // Add operator candidates that are member functions.
5632 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5633
John McCall6e266892010-01-26 03:27:55 +00005634 // Add candidates from ADL.
5635 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5636 Args, 2,
5637 /*ExplicitTemplateArgs*/ 0,
5638 CandidateSet);
5639
Douglas Gregor063daf62009-03-13 18:40:31 +00005640 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005641 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00005642
5643 // Perform overload resolution.
5644 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005645 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005646 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00005647 // We found a built-in operator or an overloaded operator.
5648 FunctionDecl *FnDecl = Best->Function;
5649
5650 if (FnDecl) {
5651 // We matched an overloaded operator. Build a call to that
5652 // operator.
5653
5654 // Convert the arguments.
5655 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005656 OwningExprResult Arg1
5657 = PerformCopyInitialization(
5658 InitializedEntity::InitializeParameter(
5659 FnDecl->getParamDecl(0)),
5660 SourceLocation(),
5661 Owned(Args[1]));
5662 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00005663 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005664
5665 if (PerformObjectArgumentInitialization(Args[0], Method))
5666 return ExprError();
5667
5668 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00005669 } else {
5670 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005671 OwningExprResult Arg0
5672 = PerformCopyInitialization(
5673 InitializedEntity::InitializeParameter(
5674 FnDecl->getParamDecl(0)),
5675 SourceLocation(),
5676 Owned(Args[0]));
5677 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00005678 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005679
5680 OwningExprResult Arg1
5681 = PerformCopyInitialization(
5682 InitializedEntity::InitializeParameter(
5683 FnDecl->getParamDecl(1)),
5684 SourceLocation(),
5685 Owned(Args[1]));
5686 if (Arg1.isInvalid())
5687 return ExprError();
5688 Args[0] = LHS = Arg0.takeAs<Expr>();
5689 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00005690 }
5691
5692 // Determine the result type
5693 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00005694 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00005695 ResultTy = ResultTy.getNonReferenceType();
5696
5697 // Build the actual expression node.
5698 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00005699 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005700 UsualUnaryConversions(FnExpr);
5701
Anders Carlsson15ea3782009-10-13 22:43:21 +00005702 ExprOwningPtr<CXXOperatorCallExpr>
5703 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5704 Args, 2, ResultTy,
5705 OpLoc));
5706
5707 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5708 FnDecl))
5709 return ExprError();
5710
5711 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00005712 } else {
5713 // We matched a built-in operator. Convert the arguments, then
5714 // break out so that we will build the appropriate built-in
5715 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005716 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005717 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005718 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005719 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00005720 return ExprError();
5721
5722 break;
5723 }
5724 }
5725
Douglas Gregor33074752009-09-30 21:46:01 +00005726 case OR_No_Viable_Function: {
5727 // C++ [over.match.oper]p9:
5728 // If the operator is the operator , [...] and there are no
5729 // viable functions, then the operator is assumed to be the
5730 // built-in operator and interpreted according to clause 5.
5731 if (Opc == BinaryOperator::Comma)
5732 break;
5733
Sebastian Redl8593c782009-05-21 11:50:50 +00005734 // For class as left operand for assignment or compound assigment operator
5735 // do not fall through to handling in built-in, but report that no overloaded
5736 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00005737 OwningExprResult Result = ExprError();
5738 if (Args[0]->getType()->isRecordType() &&
5739 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00005740 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5741 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005742 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00005743 } else {
5744 // No viable function; try to create a built-in operation, which will
5745 // produce an error. Then, show the non-viable candidates.
5746 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00005747 }
Douglas Gregor33074752009-09-30 21:46:01 +00005748 assert(Result.isInvalid() &&
5749 "C++ binary operator overloading is missing candidates!");
5750 if (Result.isInvalid())
John McCallcbce6062010-01-12 07:18:19 +00005751 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005752 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00005753 return move(Result);
5754 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005755
5756 case OR_Ambiguous:
5757 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5758 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005759 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005760 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005761 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005762 return ExprError();
5763
5764 case OR_Deleted:
5765 Diag(OpLoc, diag::err_ovl_deleted_oper)
5766 << Best->Function->isDeleted()
5767 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005768 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005769 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00005770 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00005771 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005772
Douglas Gregor33074752009-09-30 21:46:01 +00005773 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005774 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005775}
5776
Sebastian Redlf322ed62009-10-29 20:17:01 +00005777Action::OwningExprResult
5778Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5779 SourceLocation RLoc,
5780 ExprArg Base, ExprArg Idx) {
5781 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5782 static_cast<Expr*>(Idx.get()) };
5783 DeclarationName OpName =
5784 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5785
5786 // If either side is type-dependent, create an appropriate dependent
5787 // expression.
5788 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5789
John McCallba135432009-11-21 08:51:07 +00005790 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00005791 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5792 0, SourceRange(), OpName, LLoc,
John McCall7453ed42009-11-22 00:44:51 +00005793 /*ADL*/ true, /*Overloaded*/ false);
John McCallf7a1a742009-11-24 19:00:30 +00005794 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00005795
5796 Base.release();
5797 Idx.release();
5798 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5799 Args, 2,
5800 Context.DependentTy,
5801 RLoc));
5802 }
5803
5804 // Build an empty overload set.
5805 OverloadCandidateSet CandidateSet;
5806
5807 // Subscript can only be overloaded as a member function.
5808
5809 // Add operator candidates that are member functions.
5810 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5811
5812 // Add builtin operator candidates.
5813 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5814
5815 // Perform overload resolution.
5816 OverloadCandidateSet::iterator Best;
5817 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5818 case OR_Success: {
5819 // We found a built-in operator or an overloaded operator.
5820 FunctionDecl *FnDecl = Best->Function;
5821
5822 if (FnDecl) {
5823 // We matched an overloaded operator. Build a call to that
5824 // operator.
5825
5826 // Convert the arguments.
5827 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5828 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5829 PerformCopyInitialization(Args[1],
5830 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +00005831 AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005832 return ExprError();
5833
5834 // Determine the result type
5835 QualType ResultTy
5836 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5837 ResultTy = ResultTy.getNonReferenceType();
5838
5839 // Build the actual expression node.
5840 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5841 LLoc);
5842 UsualUnaryConversions(FnExpr);
5843
5844 Base.release();
5845 Idx.release();
5846 ExprOwningPtr<CXXOperatorCallExpr>
5847 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5848 FnExpr, Args, 2,
5849 ResultTy, RLoc));
5850
5851 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5852 FnDecl))
5853 return ExprError();
5854
5855 return MaybeBindToTemporary(TheCall.release());
5856 } else {
5857 // We matched a built-in operator. Convert the arguments, then
5858 // break out so that we will build the appropriate built-in
5859 // operator node.
5860 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005861 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00005862 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005863 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005864 return ExprError();
5865
5866 break;
5867 }
5868 }
5869
5870 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00005871 if (CandidateSet.empty())
5872 Diag(LLoc, diag::err_ovl_no_oper)
5873 << Args[0]->getType() << /*subscript*/ 0
5874 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5875 else
5876 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5877 << Args[0]->getType()
5878 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005879 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall1eb3e102010-01-07 02:04:15 +00005880 "[]", LLoc);
5881 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00005882 }
5883
5884 case OR_Ambiguous:
5885 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5886 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005887 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redlf322ed62009-10-29 20:17:01 +00005888 "[]", LLoc);
5889 return ExprError();
5890
5891 case OR_Deleted:
5892 Diag(LLoc, diag::err_ovl_deleted_oper)
5893 << Best->Function->isDeleted() << "[]"
5894 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005895 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall81201622010-01-08 04:41:39 +00005896 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00005897 return ExprError();
5898 }
5899
5900 // We matched a built-in operator; build it.
5901 Base.release();
5902 Idx.release();
5903 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5904 Owned(Args[1]), RLoc);
5905}
5906
Douglas Gregor88a35142008-12-22 05:46:06 +00005907/// BuildCallToMemberFunction - Build a call to a member
5908/// function. MemExpr is the expression that refers to the member
5909/// function (and includes the object parameter), Args/NumArgs are the
5910/// arguments to the function call (not including the object
5911/// parameter). The caller needs to validate that the member
5912/// expression refers to a member function or an overloaded member
5913/// function.
John McCallaa81e162009-12-01 22:10:20 +00005914Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00005915Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5916 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00005917 unsigned NumArgs, SourceLocation *CommaLocs,
5918 SourceLocation RParenLoc) {
5919 // Dig out the member expression. This holds both the object
5920 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00005921 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5922
John McCall129e2df2009-11-30 22:42:35 +00005923 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00005924 CXXMethodDecl *Method = 0;
John McCall129e2df2009-11-30 22:42:35 +00005925 if (isa<MemberExpr>(NakedMemExpr)) {
5926 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00005927 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5928 } else {
5929 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCallaa81e162009-12-01 22:10:20 +00005930
John McCall701c89e2009-12-03 04:06:58 +00005931 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00005932
Douglas Gregor88a35142008-12-22 05:46:06 +00005933 // Add overload candidates
5934 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00005935
John McCallaa81e162009-12-01 22:10:20 +00005936 // FIXME: avoid copy.
5937 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5938 if (UnresExpr->hasExplicitTemplateArgs()) {
5939 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5940 TemplateArgs = &TemplateArgsBuffer;
5941 }
5942
John McCall129e2df2009-11-30 22:42:35 +00005943 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5944 E = UnresExpr->decls_end(); I != E; ++I) {
5945
John McCall701c89e2009-12-03 04:06:58 +00005946 NamedDecl *Func = *I;
5947 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5948 if (isa<UsingShadowDecl>(Func))
5949 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5950
John McCall129e2df2009-11-30 22:42:35 +00005951 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005952 // If explicit template arguments were provided, we can't call a
5953 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00005954 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005955 continue;
5956
John McCall86820f52010-01-26 01:37:31 +00005957 AddMethodCandidate(Method, I.getAccess(), ActingDC, ObjectType,
5958 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00005959 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00005960 } else {
John McCall129e2df2009-11-30 22:42:35 +00005961 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall86820f52010-01-26 01:37:31 +00005962 I.getAccess(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005963 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00005964 CandidateSet,
5965 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00005966 }
Douglas Gregordec06662009-08-21 18:42:58 +00005967 }
Mike Stump1eb44332009-09-09 15:08:12 +00005968
John McCall129e2df2009-11-30 22:42:35 +00005969 DeclarationName DeclName = UnresExpr->getMemberName();
5970
Douglas Gregor88a35142008-12-22 05:46:06 +00005971 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00005972 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005973 case OR_Success:
5974 Method = cast<CXXMethodDecl>(Best->Function);
5975 break;
5976
5977 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00005978 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00005979 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005980 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005981 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00005982 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005983 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005984
5985 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00005986 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005987 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005988 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00005989 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005990 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005991
5992 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00005993 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005994 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00005995 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005996 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005997 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005998 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005999 }
6000
Douglas Gregor699ee522009-11-20 19:42:02 +00006001 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCallaa81e162009-12-01 22:10:20 +00006002
John McCallaa81e162009-12-01 22:10:20 +00006003 // If overload resolution picked a static member, build a
6004 // non-member call based on that function.
6005 if (Method->isStatic()) {
6006 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6007 Args, NumArgs, RParenLoc);
6008 }
6009
John McCall129e2df2009-11-30 22:42:35 +00006010 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00006011 }
6012
6013 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00006014 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00006015 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00006016 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006017 Method->getResultType().getNonReferenceType(),
6018 RParenLoc));
6019
Anders Carlssoneed3e692009-10-10 00:06:20 +00006020 // Check for a valid return type.
6021 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6022 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00006023 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00006024
Douglas Gregor88a35142008-12-22 05:46:06 +00006025 // Convert the object argument (for a non-static member function call).
John McCallaa81e162009-12-01 22:10:20 +00006026 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00006027 if (!Method->isStatic() &&
Douglas Gregor88a35142008-12-22 05:46:06 +00006028 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCallaa81e162009-12-01 22:10:20 +00006029 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006030 MemExpr->setBase(ObjectArg);
6031
6032 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00006033 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00006034 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006035 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00006036 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006037
Anders Carlssond406bf02009-08-16 01:56:34 +00006038 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00006039 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00006040
John McCallaa81e162009-12-01 22:10:20 +00006041 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00006042}
6043
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006044/// BuildCallToObjectOfClassType - Build a call to an object of class
6045/// type (C++ [over.call.object]), which can end up invoking an
6046/// overloaded function call operator (@c operator()) or performing a
6047/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006048Sema::ExprResult
6049Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00006050 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006051 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00006052 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006053 SourceLocation RParenLoc) {
6054 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00006055 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006056
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006057 // C++ [over.call.object]p1:
6058 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00006059 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006060 // candidate functions includes at least the function call
6061 // operators of T. The function call operators of T are obtained by
6062 // ordinary lookup of the name operator() in the context of
6063 // (E).operator().
6064 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00006065 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00006066
6067 if (RequireCompleteType(LParenLoc, Object->getType(),
6068 PartialDiagnostic(diag::err_incomplete_object_call)
6069 << Object->getSourceRange()))
6070 return true;
6071
John McCalla24dc2e2009-11-17 02:14:36 +00006072 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6073 LookupQualifiedName(R, Record->getDecl());
6074 R.suppressDiagnostics();
6075
Douglas Gregor593564b2009-11-15 07:48:03 +00006076 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00006077 Oper != OperEnd; ++Oper) {
John McCall86820f52010-01-26 01:37:31 +00006078 AddMethodCandidate(*Oper, Oper.getAccess(), Object->getType(),
6079 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006080 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00006081 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00006082
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006083 // C++ [over.call.object]p2:
6084 // In addition, for each conversion function declared in T of the
6085 // form
6086 //
6087 // operator conversion-type-id () cv-qualifier;
6088 //
6089 // where cv-qualifier is the same cv-qualification as, or a
6090 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00006091 // denotes the type "pointer to function of (P1,...,Pn) returning
6092 // R", or the type "reference to pointer to function of
6093 // (P1,...,Pn) returning R", or the type "reference to function
6094 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006095 // is also considered as a candidate function. Similarly,
6096 // surrogate call functions are added to the set of candidate
6097 // functions for each conversion function declared in an
6098 // accessible base class provided the function is not hidden
6099 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00006100 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00006101 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00006102 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006103 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00006104 NamedDecl *D = *I;
6105 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6106 if (isa<UsingShadowDecl>(D))
6107 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6108
Douglas Gregor4a27d702009-10-21 06:18:39 +00006109 // Skip over templated conversion functions; they aren't
6110 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00006111 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00006112 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006113
John McCall701c89e2009-12-03 04:06:58 +00006114 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00006115
Douglas Gregor4a27d702009-10-21 06:18:39 +00006116 // Strip the reference type (if any) and then the pointer type (if
6117 // any) to get down to what might be a function type.
6118 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6119 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6120 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006121
Douglas Gregor4a27d702009-10-21 06:18:39 +00006122 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall86820f52010-01-26 01:37:31 +00006123 AddSurrogateCandidate(Conv, I.getAccess(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00006124 Object->getType(), Args, NumArgs,
6125 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006126 }
Mike Stump1eb44332009-09-09 15:08:12 +00006127
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006128 // Perform overload resolution.
6129 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006130 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006131 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006132 // Overload resolution succeeded; we'll build the appropriate call
6133 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006134 break;
6135
6136 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00006137 if (CandidateSet.empty())
6138 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6139 << Object->getType() << /*call*/ 1
6140 << Object->getSourceRange();
6141 else
6142 Diag(Object->getSourceRange().getBegin(),
6143 diag::err_ovl_no_viable_object_call)
6144 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006145 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006146 break;
6147
6148 case OR_Ambiguous:
6149 Diag(Object->getSourceRange().getBegin(),
6150 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00006151 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006152 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006153 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006154
6155 case OR_Deleted:
6156 Diag(Object->getSourceRange().getBegin(),
6157 diag::err_ovl_deleted_object_call)
6158 << Best->Function->isDeleted()
6159 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006160 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006161 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006162 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006163
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006164 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006165 // We had an error; delete all of the subexpressions and return
6166 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006167 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006168 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00006169 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006170 return true;
6171 }
6172
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006173 if (Best->Function == 0) {
6174 // Since there is no function declaration, this is one of the
6175 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00006176 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006177 = cast<CXXConversionDecl>(
6178 Best->Conversions[0].UserDefined.ConversionFunction);
6179
6180 // We selected one of the surrogate functions that converts the
6181 // object parameter to a function pointer. Perform the conversion
6182 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006183
6184 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006185 // and then call it.
Eli Friedmanc8c771e2009-12-09 04:52:43 +00006186 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006187
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006188 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00006189 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6190 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006191 }
6192
6193 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6194 // that calls this method, using Object for the implicit object
6195 // parameter and passing along the remaining arguments.
6196 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00006197 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006198
6199 unsigned NumArgsInProto = Proto->getNumArgs();
6200 unsigned NumArgsToCheck = NumArgs;
6201
6202 // Build the full argument list for the method call (the
6203 // implicit object parameter is placed at the beginning of the
6204 // list).
6205 Expr **MethodArgs;
6206 if (NumArgs < NumArgsInProto) {
6207 NumArgsToCheck = NumArgsInProto;
6208 MethodArgs = new Expr*[NumArgsInProto + 1];
6209 } else {
6210 MethodArgs = new Expr*[NumArgs + 1];
6211 }
6212 MethodArgs[0] = Object;
6213 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6214 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00006215
6216 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00006217 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006218 UsualUnaryConversions(NewFn);
6219
6220 // Once we've built TheCall, all of the expressions are properly
6221 // owned.
6222 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00006223 ExprOwningPtr<CXXOperatorCallExpr>
6224 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00006225 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00006226 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006227 delete [] MethodArgs;
6228
Anders Carlsson07d68f12009-10-13 21:49:31 +00006229 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6230 Method))
6231 return true;
6232
Douglas Gregor518fda12009-01-13 05:10:00 +00006233 // We may have default arguments. If so, we need to allocate more
6234 // slots in the call for them.
6235 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00006236 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00006237 else if (NumArgs > NumArgsInProto)
6238 NumArgsToCheck = NumArgsInProto;
6239
Chris Lattner312531a2009-04-12 08:11:20 +00006240 bool IsError = false;
6241
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006242 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00006243 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006244 TheCall->setArg(0, Object);
6245
Chris Lattner312531a2009-04-12 08:11:20 +00006246
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006247 // Check the argument types.
6248 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006249 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00006250 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006251 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00006252
Douglas Gregor518fda12009-01-13 05:10:00 +00006253 // Pass the argument.
6254 QualType ProtoArgType = Proto->getArgType(i);
Douglas Gregor68647482009-12-16 03:45:30 +00006255 IsError |= PerformCopyInitialization(Arg, ProtoArgType, AA_Passing);
Douglas Gregor518fda12009-01-13 05:10:00 +00006256 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00006257 OwningExprResult DefArg
6258 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6259 if (DefArg.isInvalid()) {
6260 IsError = true;
6261 break;
6262 }
6263
6264 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00006265 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006266
6267 TheCall->setArg(i + 1, Arg);
6268 }
6269
6270 // If this is a variadic call, handle args passed through "...".
6271 if (Proto->isVariadic()) {
6272 // Promote the arguments (C99 6.5.2.2p7).
6273 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6274 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00006275 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006276 TheCall->setArg(i + 1, Arg);
6277 }
6278 }
6279
Chris Lattner312531a2009-04-12 08:11:20 +00006280 if (IsError) return true;
6281
Anders Carlssond406bf02009-08-16 01:56:34 +00006282 if (CheckFunctionCall(Method, TheCall.get()))
6283 return true;
6284
Anders Carlssona303f9e2009-08-16 03:53:54 +00006285 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006286}
6287
Douglas Gregor8ba10742008-11-20 16:27:02 +00006288/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00006289/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00006290/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006291Sema::OwningExprResult
6292Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6293 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00006294 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00006295
Douglas Gregor8ba10742008-11-20 16:27:02 +00006296 // C++ [over.ref]p1:
6297 //
6298 // [...] An expression x->m is interpreted as (x.operator->())->m
6299 // for a class object x of type T if T::operator->() exists and if
6300 // the operator is selected as the best match function by the
6301 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00006302 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
6303 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00006304 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006305
Eli Friedmanf43fb722009-11-18 01:28:03 +00006306 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
6307 PDiag(diag::err_typecheck_incomplete_tag)
6308 << Base->getSourceRange()))
6309 return ExprError();
6310
John McCalla24dc2e2009-11-17 02:14:36 +00006311 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6312 LookupQualifiedName(R, BaseRecord->getDecl());
6313 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00006314
6315 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00006316 Oper != OperEnd; ++Oper) {
6317 NamedDecl *D = *Oper;
6318 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6319 if (isa<UsingShadowDecl>(D))
6320 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6321
John McCall86820f52010-01-26 01:37:31 +00006322 AddMethodCandidate(cast<CXXMethodDecl>(D), Oper.getAccess(), ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00006323 Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00006324 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00006325 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00006326
6327 // Perform overload resolution.
6328 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006329 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00006330 case OR_Success:
6331 // Overload resolution succeeded; we'll build the call below.
6332 break;
6333
6334 case OR_No_Viable_Function:
6335 if (CandidateSet.empty())
6336 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006337 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006338 else
6339 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006340 << "operator->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006341 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006342 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006343
6344 case OR_Ambiguous:
6345 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00006346 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006347 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006348 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006349
6350 case OR_Deleted:
6351 Diag(OpLoc, diag::err_ovl_deleted_oper)
6352 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00006353 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006354 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006355 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006356 }
6357
6358 // Convert the object parameter.
6359 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00006360 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006361 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00006362
6363 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006364 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006365
6366 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006367 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6368 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00006369 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00006370
6371 QualType ResultTy = Method->getResultType().getNonReferenceType();
6372 ExprOwningPtr<CXXOperatorCallExpr>
6373 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6374 &Base, 1, ResultTy, OpLoc));
6375
6376 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6377 Method))
6378 return ExprError();
6379 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00006380}
6381
Douglas Gregor904eed32008-11-10 20:40:00 +00006382/// FixOverloadedFunctionReference - E is an expression that refers to
6383/// a C++ overloaded function (possibly with some parentheses and
6384/// perhaps a '&' around it). We have resolved the overloaded function
6385/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00006386/// refer (possibly indirectly) to Fn. Returns the new expr.
6387Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006388 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor699ee522009-11-20 19:42:02 +00006389 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6390 if (SubExpr == PE->getSubExpr())
6391 return PE->Retain();
6392
6393 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6394 }
6395
6396 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6397 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00006398 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00006399 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00006400 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00006401 if (SubExpr == ICE->getSubExpr())
6402 return ICE->Retain();
6403
6404 return new (Context) ImplicitCastExpr(ICE->getType(),
6405 ICE->getCastKind(),
6406 SubExpr,
6407 ICE->isLvalueCast());
6408 }
6409
6410 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006411 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00006412 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00006413 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6414 if (Method->isStatic()) {
6415 // Do nothing: static member functions aren't any different
6416 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00006417 } else {
John McCallf7a1a742009-11-24 19:00:30 +00006418 // Fix the sub expression, which really has to be an
6419 // UnresolvedLookupExpr holding an overloaded member function
6420 // or template.
John McCallba135432009-11-21 08:51:07 +00006421 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6422 if (SubExpr == UnOp->getSubExpr())
6423 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00006424
John McCallba135432009-11-21 08:51:07 +00006425 assert(isa<DeclRefExpr>(SubExpr)
6426 && "fixed to something other than a decl ref");
6427 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6428 && "fixed to a member ref with no nested name qualifier");
6429
6430 // We have taken the address of a pointer to member
6431 // function. Perform the computation here so that we get the
6432 // appropriate pointer to member type.
6433 QualType ClassType
6434 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6435 QualType MemPtrType
6436 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6437
6438 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6439 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00006440 }
6441 }
Douglas Gregor699ee522009-11-20 19:42:02 +00006442 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6443 if (SubExpr == UnOp->getSubExpr())
6444 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00006445
Douglas Gregor699ee522009-11-20 19:42:02 +00006446 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6447 Context.getPointerType(SubExpr->getType()),
6448 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00006449 }
John McCallba135432009-11-21 08:51:07 +00006450
6451 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00006452 // FIXME: avoid copy.
6453 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00006454 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00006455 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6456 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00006457 }
6458
John McCallba135432009-11-21 08:51:07 +00006459 return DeclRefExpr::Create(Context,
6460 ULE->getQualifier(),
6461 ULE->getQualifierRange(),
6462 Fn,
6463 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006464 Fn->getType(),
6465 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00006466 }
6467
John McCall129e2df2009-11-30 22:42:35 +00006468 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00006469 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00006470 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6471 if (MemExpr->hasExplicitTemplateArgs()) {
6472 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6473 TemplateArgs = &TemplateArgsBuffer;
6474 }
John McCalld5532b62009-11-23 01:53:49 +00006475
John McCallaa81e162009-12-01 22:10:20 +00006476 Expr *Base;
6477
6478 // If we're filling in
6479 if (MemExpr->isImplicitAccess()) {
6480 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6481 return DeclRefExpr::Create(Context,
6482 MemExpr->getQualifier(),
6483 MemExpr->getQualifierRange(),
6484 Fn,
6485 MemExpr->getMemberLoc(),
6486 Fn->getType(),
6487 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00006488 } else {
6489 SourceLocation Loc = MemExpr->getMemberLoc();
6490 if (MemExpr->getQualifier())
6491 Loc = MemExpr->getQualifierRange().getBegin();
6492 Base = new (Context) CXXThisExpr(Loc,
6493 MemExpr->getBaseType(),
6494 /*isImplicit=*/true);
6495 }
John McCallaa81e162009-12-01 22:10:20 +00006496 } else
6497 Base = MemExpr->getBase()->Retain();
6498
6499 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00006500 MemExpr->isArrow(),
6501 MemExpr->getQualifier(),
6502 MemExpr->getQualifierRange(),
6503 Fn,
John McCalld5532b62009-11-23 01:53:49 +00006504 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006505 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00006506 Fn->getType());
6507 }
6508
Douglas Gregor699ee522009-11-20 19:42:02 +00006509 assert(false && "Invalid reference to overloaded function");
6510 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00006511}
6512
Douglas Gregor20093b42009-12-09 23:02:17 +00006513Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6514 FunctionDecl *Fn) {
6515 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6516}
6517
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006518} // end namespace clang