blob: d1d9bda93e552cc82c3a930a2112c45c7b1ad246 [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.
Douglas Gregorad323a82010-01-27 03:51:04 +0000151 if (getToType(1)->isBooleanType() &&
John McCall1d318332010-01-12 00:44:57 +0000152 (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();
Douglas Gregorad323a82010-01-27 03:51:04 +0000167 QualType ToType = getToType(1);
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());
Douglas Gregorad323a82010-01-27 03:51:04 +0000480 ICS.Standard.setAllToTypes(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;
Douglas Gregorad323a82010-01-27 03:51:04 +0000598 SCS.setAllToTypes(FromType);
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 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000637 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000638
639 // The second conversion can be an integral promotion, floating
640 // point promotion, integral conversion, floating point conversion,
641 // floating-integral conversion, pointer conversion,
642 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000643 // For overloading in C, this can also be a "compatible-type"
644 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000645 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000646 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000647 // The unqualified versions of the types are the same: there's no
648 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000649 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000650 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000651 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000652 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000653 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000654 } else if (IsFloatingPointPromotion(FromType, ToType)) {
655 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000656 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000657 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000658 } else if (IsComplexPromotion(FromType, ToType)) {
659 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000660 SCS.Second = ICK_Complex_Promotion;
661 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000662 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000663 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000664 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000665 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000666 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000667 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
668 // Floating point conversions (C++ 4.8).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000669 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000670 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000671 } else if (FromType->isComplexType() && ToType->isComplexType()) {
672 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000673 SCS.Second = ICK_Complex_Conversion;
674 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000675 } else if ((FromType->isFloatingType() &&
676 ToType->isIntegralType() && (!ToType->isBooleanType() &&
677 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000678 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000679 ToType->isFloatingType())) {
680 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000681 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000682 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000683 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
684 (ToType->isComplexType() && FromType->isArithmeticType())) {
685 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000686 SCS.Second = ICK_Complex_Real;
687 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000688 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
689 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000690 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000691 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000692 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000693 } else if (IsMemberPointerConversion(From, FromType, ToType,
694 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000695 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000696 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000697 } else if (ToType->isBooleanType() &&
698 (FromType->isArithmeticType() ||
699 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +0000700 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000701 FromType->isBlockPointerType() ||
702 FromType->isMemberPointerType() ||
703 FromType->isNullPtrType())) {
704 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000705 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000706 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000707 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000708 Context.typesAreCompatible(ToType, FromType)) {
709 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000710 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000711 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
712 // Treat a conversion that strips "noreturn" as an identity conversion.
713 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000714 } else {
715 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000716 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000717 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000718 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000719
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000720 QualType CanonFrom;
721 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000722 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000723 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000724 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000725 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000726 CanonFrom = Context.getCanonicalType(FromType);
727 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000728 } else {
729 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000730 SCS.Third = ICK_Identity;
731
Mike Stump1eb44332009-09-09 15:08:12 +0000732 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000733 // [...] Any difference in top-level cv-qualification is
734 // subsumed by the initialization itself and does not constitute
735 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000736 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000737 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +0000738 if (CanonFrom.getLocalUnqualifiedType()
739 == CanonTo.getLocalUnqualifiedType() &&
740 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000741 FromType = ToType;
742 CanonFrom = CanonTo;
743 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000744 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000745 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000746
747 // If we have not converted the argument type to the parameter type,
748 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000749 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000750 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000751
Douglas Gregor60d62c22008-10-31 16:23:19 +0000752 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000753}
754
755/// IsIntegralPromotion - Determines whether the conversion from the
756/// expression From (whose potentially-adjusted type is FromType) to
757/// ToType is an integral promotion (C++ 4.5). If so, returns true and
758/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000759bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000760 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000761 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000762 if (!To) {
763 return false;
764 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000765
766 // An rvalue of type char, signed char, unsigned char, short int, or
767 // unsigned short int can be converted to an rvalue of type int if
768 // int can represent all the values of the source type; otherwise,
769 // the source rvalue can be converted to an rvalue of type unsigned
770 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000771 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
772 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000773 if (// We can promote any signed, promotable integer type to an int
774 (FromType->isSignedIntegerType() ||
775 // We can promote any unsigned integer type whose size is
776 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +0000777 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000778 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000779 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000780 }
781
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000782 return To->getKind() == BuiltinType::UInt;
783 }
784
785 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
786 // can be converted to an rvalue of the first of the following types
787 // that can represent all the values of its underlying type: int,
788 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +0000789
790 // We pre-calculate the promotion type for enum types.
791 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
792 if (ToType->isIntegerType())
793 return Context.hasSameUnqualifiedType(ToType,
794 FromEnumType->getDecl()->getPromotionType());
795
796 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000797 // Determine whether the type we're converting from is signed or
798 // unsigned.
799 bool FromIsSigned;
800 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +0000801
802 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
803 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000804
805 // The types we'll try to promote to, in the appropriate
806 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +0000807 QualType PromoteTypes[6] = {
808 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000809 Context.LongTy, Context.UnsignedLongTy ,
810 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000811 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000812 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000813 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
814 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000815 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000816 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
817 // We found the type that we can promote to. If this is the
818 // type we wanted, we have a promotion. Otherwise, no
819 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000820 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000821 }
822 }
823 }
824
825 // An rvalue for an integral bit-field (9.6) can be converted to an
826 // rvalue of type int if int can represent all the values of the
827 // bit-field; otherwise, it can be converted to unsigned int if
828 // unsigned int can represent all the values of the bit-field. If
829 // the bit-field is larger yet, no integral promotion applies to
830 // it. If the bit-field has an enumerated type, it is treated as any
831 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000832 // FIXME: We should delay checking of bit-fields until we actually perform the
833 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000834 using llvm::APSInt;
835 if (From)
836 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000837 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000838 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
839 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
840 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
841 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +0000842
Douglas Gregor86f19402008-12-20 23:49:58 +0000843 // Are we promoting to an int from a bitfield that fits in an int?
844 if (BitWidth < ToSize ||
845 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
846 return To->getKind() == BuiltinType::Int;
847 }
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Douglas Gregor86f19402008-12-20 23:49:58 +0000849 // Are we promoting to an unsigned int from an unsigned bitfield
850 // that fits into an unsigned int?
851 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
852 return To->getKind() == BuiltinType::UInt;
853 }
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Douglas Gregor86f19402008-12-20 23:49:58 +0000855 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000856 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000857 }
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000859 // An rvalue of type bool can be converted to an rvalue of type int,
860 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000861 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000862 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000863 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000864
865 return false;
866}
867
868/// IsFloatingPointPromotion - Determines whether the conversion from
869/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
870/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000871bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000872 /// An rvalue of type float can be converted to an rvalue of type
873 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +0000874 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
875 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000876 if (FromBuiltin->getKind() == BuiltinType::Float &&
877 ToBuiltin->getKind() == BuiltinType::Double)
878 return true;
879
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000880 // C99 6.3.1.5p1:
881 // When a float is promoted to double or long double, or a
882 // double is promoted to long double [...].
883 if (!getLangOptions().CPlusPlus &&
884 (FromBuiltin->getKind() == BuiltinType::Float ||
885 FromBuiltin->getKind() == BuiltinType::Double) &&
886 (ToBuiltin->getKind() == BuiltinType::LongDouble))
887 return true;
888 }
889
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000890 return false;
891}
892
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000893/// \brief Determine if a conversion is a complex promotion.
894///
895/// A complex promotion is defined as a complex -> complex conversion
896/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000897/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000898bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000899 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000900 if (!FromComplex)
901 return false;
902
John McCall183700f2009-09-21 23:43:11 +0000903 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000904 if (!ToComplex)
905 return false;
906
907 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000908 ToComplex->getElementType()) ||
909 IsIntegralPromotion(0, FromComplex->getElementType(),
910 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000911}
912
Douglas Gregorcb7de522008-11-26 23:31:11 +0000913/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
914/// the pointer type FromPtr to a pointer to type ToPointee, with the
915/// same type qualifiers as FromPtr has on its pointee type. ToType,
916/// if non-empty, will be a pointer to ToType that may or may not have
917/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000918static QualType
919BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000920 QualType ToPointee, QualType ToType,
921 ASTContext &Context) {
922 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
923 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +0000924 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000925
926 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000927 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +0000928 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +0000929 if (!ToType.isNull())
Douglas Gregorcb7de522008-11-26 23:31:11 +0000930 return ToType;
931
932 // Build a pointer to ToPointee. It has the right qualifiers
933 // already.
934 return Context.getPointerType(ToPointee);
935 }
936
937 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +0000938 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +0000939 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
940 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +0000941}
942
Fariborz Jahanianadcfab12009-12-16 23:13:33 +0000943/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
944/// the FromType, which is an objective-c pointer, to ToType, which may or may
945/// not have the right set of qualifiers.
946static QualType
947BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
948 QualType ToType,
949 ASTContext &Context) {
950 QualType CanonFromType = Context.getCanonicalType(FromType);
951 QualType CanonToType = Context.getCanonicalType(ToType);
952 Qualifiers Quals = CanonFromType.getQualifiers();
953
954 // Exact qualifier match -> return the pointer type we're converting to.
955 if (CanonToType.getLocalQualifiers() == Quals)
956 return ToType;
957
958 // Just build a canonical type that has the right qualifiers.
959 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
960}
961
Mike Stump1eb44332009-09-09 15:08:12 +0000962static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000963 bool InOverloadResolution,
964 ASTContext &Context) {
965 // Handle value-dependent integral null pointer constants correctly.
966 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
967 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
968 Expr->getType()->isIntegralType())
969 return !InOverloadResolution;
970
Douglas Gregorce940492009-09-25 04:25:58 +0000971 return Expr->isNullPointerConstant(Context,
972 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
973 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000974}
Mike Stump1eb44332009-09-09 15:08:12 +0000975
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000976/// IsPointerConversion - Determines whether the conversion of the
977/// expression From, which has the (possibly adjusted) type FromType,
978/// can be converted to the type ToType via a pointer conversion (C++
979/// 4.10). If so, returns true and places the converted type (that
980/// might differ from ToType in its cv-qualifiers at some level) into
981/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000982///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000983/// This routine also supports conversions to and from block pointers
984/// and conversions with Objective-C's 'id', 'id<protocols...>', and
985/// pointers to interfaces. FIXME: Once we've determined the
986/// appropriate overloading rules for Objective-C, we may want to
987/// split the Objective-C checks into a different routine; however,
988/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000989/// conversions, so for now they live here. IncompatibleObjC will be
990/// set if the conversion is an allowed Objective-C conversion that
991/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000992bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000993 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +0000994 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +0000995 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +0000996 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000997 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
998 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000999
Mike Stump1eb44332009-09-09 15:08:12 +00001000 // Conversion from a null pointer constant to any Objective-C pointer type.
1001 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001002 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001003 ConvertedType = ToType;
1004 return true;
1005 }
1006
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001007 // Blocks: Block pointers can be converted to void*.
1008 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001009 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001010 ConvertedType = ToType;
1011 return true;
1012 }
1013 // Blocks: A null pointer constant can be converted to a block
1014 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001015 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001016 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001017 ConvertedType = ToType;
1018 return true;
1019 }
1020
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001021 // If the left-hand-side is nullptr_t, the right side can be a null
1022 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001023 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001024 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001025 ConvertedType = ToType;
1026 return true;
1027 }
1028
Ted Kremenek6217b802009-07-29 21:53:49 +00001029 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001030 if (!ToTypePtr)
1031 return false;
1032
1033 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001034 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001035 ConvertedType = ToType;
1036 return true;
1037 }
Sebastian Redl07779722008-10-31 14:43:28 +00001038
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001039 // Beyond this point, both types need to be pointers
1040 // , including objective-c pointers.
1041 QualType ToPointeeType = ToTypePtr->getPointeeType();
1042 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1043 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1044 ToType, Context);
1045 return true;
1046
1047 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001048 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001049 if (!FromTypePtr)
1050 return false;
1051
1052 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001053
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001054 // An rvalue of type "pointer to cv T," where T is an object type,
1055 // can be converted to an rvalue of type "pointer to cv void" (C++
1056 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +00001057 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001058 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001059 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001060 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001061 return true;
1062 }
1063
Douglas Gregorf9201e02009-02-11 23:02:49 +00001064 // When we're overloading in C, we allow a special kind of pointer
1065 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001066 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001067 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001068 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001069 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001070 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001071 return true;
1072 }
1073
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001074 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001075 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001076 // An rvalue of type "pointer to cv D," where D is a class type,
1077 // can be converted to an rvalue of type "pointer to cv B," where
1078 // B is a base class (clause 10) of D. If B is an inaccessible
1079 // (clause 11) or ambiguous (10.2) base class of D, a program that
1080 // necessitates this conversion is ill-formed. The result of the
1081 // conversion is a pointer to the base class sub-object of the
1082 // derived class object. The null pointer value is converted to
1083 // the null pointer value of the destination type.
1084 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001085 // Note that we do not check for ambiguity or inaccessibility
1086 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001087 if (getLangOptions().CPlusPlus &&
1088 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001089 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001090 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001091 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001092 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001093 ToType, Context);
1094 return true;
1095 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001096
Douglas Gregorc7887512008-12-19 19:13:09 +00001097 return false;
1098}
1099
1100/// isObjCPointerConversion - Determines whether this is an
1101/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1102/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001103bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001104 QualType& ConvertedType,
1105 bool &IncompatibleObjC) {
1106 if (!getLangOptions().ObjC1)
1107 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001108
Steve Naroff14108da2009-07-10 23:34:53 +00001109 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001110 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001111 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001112 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001113
Steve Naroff14108da2009-07-10 23:34:53 +00001114 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001115 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001116 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001117 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001118 ConvertedType = ToType;
1119 return true;
1120 }
1121 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001122 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001123 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001124 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001125 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001126 ConvertedType = ToType;
1127 return true;
1128 }
1129 // Objective C++: We're able to convert from a pointer to an
1130 // interface to a pointer to a different interface.
1131 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1132 ConvertedType = ToType;
1133 return true;
1134 }
1135
1136 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1137 // Okay: this is some kind of implicit downcast of Objective-C
1138 // interfaces, which is permitted. However, we're going to
1139 // complain about it.
1140 IncompatibleObjC = true;
1141 ConvertedType = FromType;
1142 return true;
1143 }
Mike Stump1eb44332009-09-09 15:08:12 +00001144 }
Steve Naroff14108da2009-07-10 23:34:53 +00001145 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001146 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001147 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001148 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001149 else if (const BlockPointerType *ToBlockPtr =
1150 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001151 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001152 // to a block pointer type.
1153 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1154 ConvertedType = ToType;
1155 return true;
1156 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001157 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001158 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001159 else if (FromType->getAs<BlockPointerType>() &&
1160 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1161 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001162 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001163 ConvertedType = ToType;
1164 return true;
1165 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001166 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001167 return false;
1168
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001169 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001170 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001171 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001172 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001173 FromPointeeType = FromBlockPtr->getPointeeType();
1174 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001175 return false;
1176
Douglas Gregorc7887512008-12-19 19:13:09 +00001177 // If we have pointers to pointers, recursively check whether this
1178 // is an Objective-C conversion.
1179 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1180 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1181 IncompatibleObjC)) {
1182 // We always complain about this conversion.
1183 IncompatibleObjC = true;
1184 ConvertedType = ToType;
1185 return true;
1186 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001187 // Allow conversion of pointee being objective-c pointer to another one;
1188 // as in I* to id.
1189 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1190 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1191 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1192 IncompatibleObjC)) {
1193 ConvertedType = ToType;
1194 return true;
1195 }
1196
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001197 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001198 // differences in the argument and result types are in Objective-C
1199 // pointer conversions. If so, we permit the conversion (but
1200 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001201 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001202 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001203 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001204 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001205 if (FromFunctionType && ToFunctionType) {
1206 // If the function types are exactly the same, this isn't an
1207 // Objective-C pointer conversion.
1208 if (Context.getCanonicalType(FromPointeeType)
1209 == Context.getCanonicalType(ToPointeeType))
1210 return false;
1211
1212 // Perform the quick checks that will tell us whether these
1213 // function types are obviously different.
1214 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1215 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1216 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1217 return false;
1218
1219 bool HasObjCConversion = false;
1220 if (Context.getCanonicalType(FromFunctionType->getResultType())
1221 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1222 // Okay, the types match exactly. Nothing to do.
1223 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1224 ToFunctionType->getResultType(),
1225 ConvertedType, IncompatibleObjC)) {
1226 // Okay, we have an Objective-C pointer conversion.
1227 HasObjCConversion = true;
1228 } else {
1229 // Function types are too different. Abort.
1230 return false;
1231 }
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Douglas Gregorc7887512008-12-19 19:13:09 +00001233 // Check argument types.
1234 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1235 ArgIdx != NumArgs; ++ArgIdx) {
1236 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1237 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1238 if (Context.getCanonicalType(FromArgType)
1239 == Context.getCanonicalType(ToArgType)) {
1240 // Okay, the types match exactly. Nothing to do.
1241 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1242 ConvertedType, IncompatibleObjC)) {
1243 // Okay, we have an Objective-C pointer conversion.
1244 HasObjCConversion = true;
1245 } else {
1246 // Argument types are too different. Abort.
1247 return false;
1248 }
1249 }
1250
1251 if (HasObjCConversion) {
1252 // We had an Objective-C conversion. Allow this pointer
1253 // conversion, but complain about it.
1254 ConvertedType = ToType;
1255 IncompatibleObjC = true;
1256 return true;
1257 }
1258 }
1259
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001260 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001261}
1262
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001263/// CheckPointerConversion - Check the pointer conversion from the
1264/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001265/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001266/// conversions for which IsPointerConversion has already returned
1267/// true. It returns true and produces a diagnostic if there was an
1268/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001269bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001270 CastExpr::CastKind &Kind,
1271 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001272 QualType FromType = From->getType();
1273
Ted Kremenek6217b802009-07-29 21:53:49 +00001274 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1275 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001276 QualType FromPointeeType = FromPtrType->getPointeeType(),
1277 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001278
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001279 if (FromPointeeType->isRecordType() &&
1280 ToPointeeType->isRecordType()) {
1281 // We must have a derived-to-base conversion. Check an
1282 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001283 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1284 From->getExprLoc(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001285 From->getSourceRange(),
1286 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001287 return true;
1288
1289 // The conversion was successful.
1290 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001291 }
1292 }
Mike Stump1eb44332009-09-09 15:08:12 +00001293 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001294 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001295 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001296 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001297 // Objective-C++ conversions are always okay.
1298 // FIXME: We should have a different class of conversions for the
1299 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001300 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001301 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001302
Steve Naroff14108da2009-07-10 23:34:53 +00001303 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001304 return false;
1305}
1306
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001307/// IsMemberPointerConversion - Determines whether the conversion of the
1308/// expression From, which has the (possibly adjusted) type FromType, can be
1309/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1310/// If so, returns true and places the converted type (that might differ from
1311/// ToType in its cv-qualifiers at some level) into ConvertedType.
1312bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001313 QualType ToType,
1314 bool InOverloadResolution,
1315 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001316 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001317 if (!ToTypePtr)
1318 return false;
1319
1320 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001321 if (From->isNullPointerConstant(Context,
1322 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1323 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001324 ConvertedType = ToType;
1325 return true;
1326 }
1327
1328 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001329 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001330 if (!FromTypePtr)
1331 return false;
1332
1333 // A pointer to member of B can be converted to a pointer to member of D,
1334 // where D is derived from B (C++ 4.11p2).
1335 QualType FromClass(FromTypePtr->getClass(), 0);
1336 QualType ToClass(ToTypePtr->getClass(), 0);
1337 // FIXME: What happens when these are dependent? Is this function even called?
1338
1339 if (IsDerivedFrom(ToClass, FromClass)) {
1340 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1341 ToClass.getTypePtr());
1342 return true;
1343 }
1344
1345 return false;
1346}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001347
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001348/// CheckMemberPointerConversion - Check the member pointer conversion from the
1349/// expression From to the type ToType. This routine checks for ambiguous or
1350/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1351/// for which IsMemberPointerConversion has already returned true. It returns
1352/// true and produces a diagnostic if there was an error, or returns false
1353/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001354bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001355 CastExpr::CastKind &Kind,
1356 bool IgnoreBaseAccess) {
1357 (void)IgnoreBaseAccess;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001358 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001359 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001360 if (!FromPtrType) {
1361 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001362 assert(From->isNullPointerConstant(Context,
1363 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001364 "Expr must be null pointer constant!");
1365 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001366 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001367 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001368
Ted Kremenek6217b802009-07-29 21:53:49 +00001369 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001370 assert(ToPtrType && "No member pointer cast has a target type "
1371 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001372
Sebastian Redl21593ac2009-01-28 18:33:18 +00001373 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1374 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001375
Sebastian Redl21593ac2009-01-28 18:33:18 +00001376 // FIXME: What about dependent types?
1377 assert(FromClass->isRecordType() && "Pointer into non-class.");
1378 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001379
Douglas Gregora8f32e02009-10-06 17:59:45 +00001380 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1381 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001382 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1383 assert(DerivationOkay &&
1384 "Should not have been called if derivation isn't OK.");
1385 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001386
Sebastian Redl21593ac2009-01-28 18:33:18 +00001387 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1388 getUnqualifiedType())) {
1389 // Derivation is ambiguous. Redo the check to find the exact paths.
1390 Paths.clear();
1391 Paths.setRecordingPaths(true);
1392 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1393 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1394 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001395
Sebastian Redl21593ac2009-01-28 18:33:18 +00001396 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1397 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1398 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1399 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001400 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001401
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001402 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001403 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1404 << FromClass << ToClass << QualType(VBase, 0)
1405 << From->getSourceRange();
1406 return true;
1407 }
1408
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001409 // Must be a base to derived member conversion.
1410 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001411 return false;
1412}
1413
Douglas Gregor98cd5992008-10-21 23:43:52 +00001414/// IsQualificationConversion - Determines whether the conversion from
1415/// an rvalue of type FromType to ToType is a qualification conversion
1416/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001417bool
1418Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001419 FromType = Context.getCanonicalType(FromType);
1420 ToType = Context.getCanonicalType(ToType);
1421
1422 // If FromType and ToType are the same type, this is not a
1423 // qualification conversion.
1424 if (FromType == ToType)
1425 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001426
Douglas Gregor98cd5992008-10-21 23:43:52 +00001427 // (C++ 4.4p4):
1428 // A conversion can add cv-qualifiers at levels other than the first
1429 // in multi-level pointers, subject to the following rules: [...]
1430 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001431 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001432 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001433 // Within each iteration of the loop, we check the qualifiers to
1434 // determine if this still looks like a qualification
1435 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001436 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001437 // until there are no more pointers or pointers-to-members left to
1438 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001439 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001440
1441 // -- for every j > 0, if const is in cv 1,j then const is in cv
1442 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001443 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001444 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Douglas Gregor98cd5992008-10-21 23:43:52 +00001446 // -- if the cv 1,j and cv 2,j are different, then const is in
1447 // every cv for 0 < k < j.
1448 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001449 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001450 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Douglas Gregor98cd5992008-10-21 23:43:52 +00001452 // Keep track of whether all prior cv-qualifiers in the "to" type
1453 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001454 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001455 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001456 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001457
1458 // We are left with FromType and ToType being the pointee types
1459 // after unwrapping the original FromType and ToType the same number
1460 // of types. If we unwrapped any pointers, and if FromType and
1461 // ToType have the same unqualified type (since we checked
1462 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001463 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001464}
1465
Douglas Gregor734d9862009-01-30 23:27:23 +00001466/// Determines whether there is a user-defined conversion sequence
1467/// (C++ [over.ics.user]) that converts expression From to the type
1468/// ToType. If such a conversion exists, User will contain the
1469/// user-defined conversion sequence that performs such a conversion
1470/// and this routine will return true. Otherwise, this routine returns
1471/// false and User is unspecified.
1472///
1473/// \param AllowConversionFunctions true if the conversion should
1474/// consider conversion functions at all. If false, only constructors
1475/// will be considered.
1476///
1477/// \param AllowExplicit true if the conversion should consider C++0x
1478/// "explicit" conversion functions as well as non-explicit conversion
1479/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001480///
1481/// \param ForceRValue true if the expression should be treated as an rvalue
1482/// for overload resolution.
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001483/// \param UserCast true if looking for user defined conversion for a static
1484/// cast.
Douglas Gregor20093b42009-12-09 23:02:17 +00001485OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1486 UserDefinedConversionSequence& User,
1487 OverloadCandidateSet& CandidateSet,
1488 bool AllowConversionFunctions,
1489 bool AllowExplicit,
1490 bool ForceRValue,
1491 bool UserCast) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001492 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001493 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1494 // We're not going to find any constructors.
1495 } else if (CXXRecordDecl *ToRecordDecl
1496 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001497 // C++ [over.match.ctor]p1:
1498 // When objects of class type are direct-initialized (8.5), or
1499 // copy-initialized from an expression of the same or a
1500 // derived class type (8.5), overload resolution selects the
1501 // constructor. [...] For copy-initialization, the candidate
1502 // functions are all the converting constructors (12.3.1) of
1503 // that class. The argument list is the expression-list within
1504 // the parentheses of the initializer.
Douglas Gregor79b680e2009-11-13 18:44:21 +00001505 bool SuppressUserConversions = !UserCast;
1506 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1507 IsDerivedFrom(From->getType(), ToType)) {
1508 SuppressUserConversions = false;
1509 AllowConversionFunctions = false;
1510 }
1511
Mike Stump1eb44332009-09-09 15:08:12 +00001512 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001513 = Context.DeclarationNames.getCXXConstructorName(
1514 Context.getCanonicalType(ToType).getUnqualifiedType());
1515 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001516 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001517 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001518 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00001519 // Find the constructor (which may be a template).
1520 CXXConstructorDecl *Constructor = 0;
1521 FunctionTemplateDecl *ConstructorTmpl
1522 = dyn_cast<FunctionTemplateDecl>(*Con);
1523 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001524 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001525 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1526 else
1527 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001528
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001529 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001530 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001531 if (ConstructorTmpl)
John McCall86820f52010-01-26 01:37:31 +00001532 AddTemplateOverloadCandidate(ConstructorTmpl,
1533 ConstructorTmpl->getAccess(),
1534 /*ExplicitArgs*/ 0,
John McCalld5532b62009-11-23 01:53:49 +00001535 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001536 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001537 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001538 // Allow one user-defined conversion when user specifies a
1539 // From->ToType conversion via an static cast (c-style, etc).
John McCall86820f52010-01-26 01:37:31 +00001540 AddOverloadCandidate(Constructor, Constructor->getAccess(),
1541 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001542 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001543 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001544 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001545 }
1546 }
1547
Douglas Gregor734d9862009-01-30 23:27:23 +00001548 if (!AllowConversionFunctions) {
1549 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001550 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1551 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001552 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001553 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001554 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001555 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001556 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001557 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1558 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00001559 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001560 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001561 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001562 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00001563 NamedDecl *D = *I;
1564 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1565 if (isa<UsingShadowDecl>(D))
1566 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1567
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001568 CXXConversionDecl *Conv;
1569 FunctionTemplateDecl *ConvTemplate;
John McCallba135432009-11-21 08:51:07 +00001570 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001571 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1572 else
John McCallba135432009-11-21 08:51:07 +00001573 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001574
1575 if (AllowExplicit || !Conv->isExplicit()) {
1576 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00001577 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
1578 ActingContext, From, ToType,
1579 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001580 else
John McCall86820f52010-01-26 01:37:31 +00001581 AddConversionCandidate(Conv, I.getAccess(), ActingContext,
1582 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001583 }
1584 }
1585 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001586 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001587
1588 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001589 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001590 case OR_Success:
1591 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001592 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001593 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1594 // C++ [over.ics.user]p1:
1595 // If the user-defined conversion is specified by a
1596 // constructor (12.3.1), the initial standard conversion
1597 // sequence converts the source type to the type required by
1598 // the argument of the constructor.
1599 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001600 QualType ThisType = Constructor->getThisType(Context);
John McCall1d318332010-01-12 00:44:57 +00001601 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001602 User.EllipsisConversion = true;
1603 else {
1604 User.Before = Best->Conversions[0].Standard;
1605 User.EllipsisConversion = false;
1606 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001607 User.ConversionFunction = Constructor;
1608 User.After.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00001609 User.After.setFromType(
1610 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregorad323a82010-01-27 03:51:04 +00001611 User.After.setAllToTypes(ToType);
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001612 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001613 } else if (CXXConversionDecl *Conversion
1614 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1615 // C++ [over.ics.user]p1:
1616 //
1617 // [...] If the user-defined conversion is specified by a
1618 // conversion function (12.3.2), the initial standard
1619 // conversion sequence converts the source type to the
1620 // implicit object parameter of the conversion function.
1621 User.Before = Best->Conversions[0].Standard;
1622 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001623 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001624
1625 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001626 // The second standard conversion sequence converts the
1627 // result of the user-defined conversion to the target type
1628 // for the sequence. Since an implicit conversion sequence
1629 // is an initialization, the special rules for
1630 // initialization by user-defined conversion apply when
1631 // selecting the best user-defined conversion for a
1632 // user-defined conversion sequence (see 13.3.3 and
1633 // 13.3.3.1).
1634 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001635 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001636 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001637 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001638 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001639 }
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Douglas Gregor60d62c22008-10-31 16:23:19 +00001641 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001642 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001643 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001644 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001645 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001646
1647 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001648 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001649 }
1650
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001651 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001652}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001653
1654bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001655Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001656 ImplicitConversionSequence ICS;
1657 OverloadCandidateSet CandidateSet;
1658 OverloadingResult OvResult =
1659 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1660 CandidateSet, true, false, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001661 if (OvResult == OR_Ambiguous)
1662 Diag(From->getSourceRange().getBegin(),
1663 diag::err_typecheck_ambiguous_condition)
1664 << From->getType() << ToType << From->getSourceRange();
1665 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1666 Diag(From->getSourceRange().getBegin(),
1667 diag::err_typecheck_nonviable_condition)
1668 << From->getType() << ToType << From->getSourceRange();
1669 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001670 return false;
John McCallcbce6062010-01-12 07:18:19 +00001671 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001672 return true;
1673}
Douglas Gregor60d62c22008-10-31 16:23:19 +00001674
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001675/// CompareImplicitConversionSequences - Compare two implicit
1676/// conversion sequences to determine whether one is better than the
1677/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001678ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001679Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1680 const ImplicitConversionSequence& ICS2)
1681{
1682 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1683 // conversion sequences (as defined in 13.3.3.1)
1684 // -- a standard conversion sequence (13.3.3.1.1) is a better
1685 // conversion sequence than a user-defined conversion sequence or
1686 // an ellipsis conversion sequence, and
1687 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1688 // conversion sequence than an ellipsis conversion sequence
1689 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001690 //
John McCall1d318332010-01-12 00:44:57 +00001691 // C++0x [over.best.ics]p10:
1692 // For the purpose of ranking implicit conversion sequences as
1693 // described in 13.3.3.2, the ambiguous conversion sequence is
1694 // treated as a user-defined sequence that is indistinguishable
1695 // from any other user-defined conversion sequence.
1696 if (ICS1.getKind() < ICS2.getKind()) {
1697 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1698 return ImplicitConversionSequence::Better;
1699 } else if (ICS2.getKind() < ICS1.getKind()) {
1700 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1701 return ImplicitConversionSequence::Worse;
1702 }
1703
1704 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1705 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001706
1707 // Two implicit conversion sequences of the same form are
1708 // indistinguishable conversion sequences unless one of the
1709 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00001710 if (ICS1.isStandard())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001711 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00001712 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001713 // User-defined conversion sequence U1 is a better conversion
1714 // sequence than another user-defined conversion sequence U2 if
1715 // they contain the same user-defined conversion function or
1716 // constructor and if the second standard conversion sequence of
1717 // U1 is better than the second standard conversion sequence of
1718 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001719 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001720 ICS2.UserDefined.ConversionFunction)
1721 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1722 ICS2.UserDefined.After);
1723 }
1724
1725 return ImplicitConversionSequence::Indistinguishable;
1726}
1727
Douglas Gregorad323a82010-01-27 03:51:04 +00001728// Per 13.3.3.2p3, compare the given standard conversion sequences to
1729// determine if one is a proper subset of the other.
1730static ImplicitConversionSequence::CompareKind
1731compareStandardConversionSubsets(ASTContext &Context,
1732 const StandardConversionSequence& SCS1,
1733 const StandardConversionSequence& SCS2) {
1734 ImplicitConversionSequence::CompareKind Result
1735 = ImplicitConversionSequence::Indistinguishable;
1736
1737 if (SCS1.Second != SCS2.Second) {
1738 if (SCS1.Second == ICK_Identity)
1739 Result = ImplicitConversionSequence::Better;
1740 else if (SCS2.Second == ICK_Identity)
1741 Result = ImplicitConversionSequence::Worse;
1742 else
1743 return ImplicitConversionSequence::Indistinguishable;
1744 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1745 return ImplicitConversionSequence::Indistinguishable;
1746
1747 if (SCS1.Third == SCS2.Third) {
1748 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1749 : ImplicitConversionSequence::Indistinguishable;
1750 }
1751
1752 if (SCS1.Third == ICK_Identity)
1753 return Result == ImplicitConversionSequence::Worse
1754 ? ImplicitConversionSequence::Indistinguishable
1755 : ImplicitConversionSequence::Better;
1756
1757 if (SCS2.Third == ICK_Identity)
1758 return Result == ImplicitConversionSequence::Better
1759 ? ImplicitConversionSequence::Indistinguishable
1760 : ImplicitConversionSequence::Worse;
1761
1762 return ImplicitConversionSequence::Indistinguishable;
1763}
1764
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001765/// CompareStandardConversionSequences - Compare two standard
1766/// conversion sequences to determine whether one is better than the
1767/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001768ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001769Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1770 const StandardConversionSequence& SCS2)
1771{
1772 // Standard conversion sequence S1 is a better conversion sequence
1773 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1774
1775 // -- S1 is a proper subsequence of S2 (comparing the conversion
1776 // sequences in the canonical form defined by 13.3.3.1.1,
1777 // excluding any Lvalue Transformation; the identity conversion
1778 // sequence is considered to be a subsequence of any
1779 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00001780 if (ImplicitConversionSequence::CompareKind CK
1781 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1782 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001783
1784 // -- the rank of S1 is better than the rank of S2 (by the rules
1785 // defined below), or, if not that,
1786 ImplicitConversionRank Rank1 = SCS1.getRank();
1787 ImplicitConversionRank Rank2 = SCS2.getRank();
1788 if (Rank1 < Rank2)
1789 return ImplicitConversionSequence::Better;
1790 else if (Rank2 < Rank1)
1791 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001792
Douglas Gregor57373262008-10-22 14:17:15 +00001793 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1794 // are indistinguishable unless one of the following rules
1795 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Douglas Gregor57373262008-10-22 14:17:15 +00001797 // A conversion that is not a conversion of a pointer, or
1798 // pointer to member, to bool is better than another conversion
1799 // that is such a conversion.
1800 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1801 return SCS2.isPointerConversionToBool()
1802 ? ImplicitConversionSequence::Better
1803 : ImplicitConversionSequence::Worse;
1804
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001805 // C++ [over.ics.rank]p4b2:
1806 //
1807 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001808 // conversion of B* to A* is better than conversion of B* to
1809 // void*, and conversion of A* to void* is better than conversion
1810 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001811 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001812 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001813 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001814 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001815 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1816 // Exactly one of the conversion sequences is a conversion to
1817 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001818 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1819 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001820 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1821 // Neither conversion sequence converts to a void pointer; compare
1822 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001823 if (ImplicitConversionSequence::CompareKind DerivedCK
1824 = CompareDerivedToBaseConversions(SCS1, SCS2))
1825 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001826 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1827 // Both conversion sequences are conversions to void
1828 // pointers. Compare the source types to determine if there's an
1829 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00001830 QualType FromType1 = SCS1.getFromType();
1831 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001832
1833 // Adjust the types we're converting from via the array-to-pointer
1834 // conversion, if we need to.
1835 if (SCS1.First == ICK_Array_To_Pointer)
1836 FromType1 = Context.getArrayDecayedType(FromType1);
1837 if (SCS2.First == ICK_Array_To_Pointer)
1838 FromType2 = Context.getArrayDecayedType(FromType2);
1839
Douglas Gregor01919692009-12-13 21:37:05 +00001840 QualType FromPointee1
1841 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1842 QualType FromPointee2
1843 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001844
Douglas Gregor01919692009-12-13 21:37:05 +00001845 if (IsDerivedFrom(FromPointee2, FromPointee1))
1846 return ImplicitConversionSequence::Better;
1847 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1848 return ImplicitConversionSequence::Worse;
1849
1850 // Objective-C++: If one interface is more specific than the
1851 // other, it is the better one.
1852 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1853 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1854 if (FromIface1 && FromIface1) {
1855 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1856 return ImplicitConversionSequence::Better;
1857 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1858 return ImplicitConversionSequence::Worse;
1859 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001860 }
Douglas Gregor57373262008-10-22 14:17:15 +00001861
1862 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1863 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001864 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001865 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001866 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001867
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001868 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001869 // C++0x [over.ics.rank]p3b4:
1870 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1871 // implicit object parameter of a non-static member function declared
1872 // without a ref-qualifier, and S1 binds an rvalue reference to an
1873 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001874 // FIXME: We don't know if we're dealing with the implicit object parameter,
1875 // or if the member function in this case has a ref qualifier.
1876 // (Of course, we don't have ref qualifiers yet.)
1877 if (SCS1.RRefBinding != SCS2.RRefBinding)
1878 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1879 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001880
1881 // C++ [over.ics.rank]p3b4:
1882 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1883 // which the references refer are the same type except for
1884 // top-level cv-qualifiers, and the type to which the reference
1885 // initialized by S2 refers is more cv-qualified than the type
1886 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00001887 QualType T1 = SCS1.getToType(2);
1888 QualType T2 = SCS2.getToType(2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001889 T1 = Context.getCanonicalType(T1);
1890 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001891 Qualifiers T1Quals, T2Quals;
1892 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1893 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1894 if (UnqualT1 == UnqualT2) {
1895 // If the type is an array type, promote the element qualifiers to the type
1896 // for comparison.
1897 if (isa<ArrayType>(T1) && T1Quals)
1898 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1899 if (isa<ArrayType>(T2) && T2Quals)
1900 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001901 if (T2.isMoreQualifiedThan(T1))
1902 return ImplicitConversionSequence::Better;
1903 else if (T1.isMoreQualifiedThan(T2))
1904 return ImplicitConversionSequence::Worse;
1905 }
1906 }
Douglas Gregor57373262008-10-22 14:17:15 +00001907
1908 return ImplicitConversionSequence::Indistinguishable;
1909}
1910
1911/// CompareQualificationConversions - Compares two standard conversion
1912/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001913/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1914ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001915Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001916 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001917 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001918 // -- S1 and S2 differ only in their qualification conversion and
1919 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1920 // cv-qualification signature of type T1 is a proper subset of
1921 // the cv-qualification signature of type T2, and S1 is not the
1922 // deprecated string literal array-to-pointer conversion (4.2).
1923 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1924 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1925 return ImplicitConversionSequence::Indistinguishable;
1926
1927 // FIXME: the example in the standard doesn't use a qualification
1928 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00001929 QualType T1 = SCS1.getToType(2);
1930 QualType T2 = SCS2.getToType(2);
Douglas Gregor57373262008-10-22 14:17:15 +00001931 T1 = Context.getCanonicalType(T1);
1932 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001933 Qualifiers T1Quals, T2Quals;
1934 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1935 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00001936
1937 // If the types are the same, we won't learn anything by unwrapped
1938 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00001939 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00001940 return ImplicitConversionSequence::Indistinguishable;
1941
Chandler Carruth28e318c2009-12-29 07:16:59 +00001942 // If the type is an array type, promote the element qualifiers to the type
1943 // for comparison.
1944 if (isa<ArrayType>(T1) && T1Quals)
1945 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1946 if (isa<ArrayType>(T2) && T2Quals)
1947 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1948
Mike Stump1eb44332009-09-09 15:08:12 +00001949 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001950 = ImplicitConversionSequence::Indistinguishable;
1951 while (UnwrapSimilarPointerTypes(T1, T2)) {
1952 // Within each iteration of the loop, we check the qualifiers to
1953 // determine if this still looks like a qualification
1954 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001955 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001956 // until there are no more pointers or pointers-to-members left
1957 // to unwrap. This essentially mimics what
1958 // IsQualificationConversion does, but here we're checking for a
1959 // strict subset of qualifiers.
1960 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1961 // The qualifiers are the same, so this doesn't tell us anything
1962 // about how the sequences rank.
1963 ;
1964 else if (T2.isMoreQualifiedThan(T1)) {
1965 // T1 has fewer qualifiers, so it could be the better sequence.
1966 if (Result == ImplicitConversionSequence::Worse)
1967 // Neither has qualifiers that are a subset of the other's
1968 // qualifiers.
1969 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Douglas Gregor57373262008-10-22 14:17:15 +00001971 Result = ImplicitConversionSequence::Better;
1972 } else if (T1.isMoreQualifiedThan(T2)) {
1973 // T2 has fewer qualifiers, so it could be the better sequence.
1974 if (Result == ImplicitConversionSequence::Better)
1975 // Neither has qualifiers that are a subset of the other's
1976 // qualifiers.
1977 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Douglas Gregor57373262008-10-22 14:17:15 +00001979 Result = ImplicitConversionSequence::Worse;
1980 } else {
1981 // Qualifiers are disjoint.
1982 return ImplicitConversionSequence::Indistinguishable;
1983 }
1984
1985 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001986 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00001987 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001988 }
1989
Douglas Gregor57373262008-10-22 14:17:15 +00001990 // Check that the winning standard conversion sequence isn't using
1991 // the deprecated string literal array to pointer conversion.
1992 switch (Result) {
1993 case ImplicitConversionSequence::Better:
1994 if (SCS1.Deprecated)
1995 Result = ImplicitConversionSequence::Indistinguishable;
1996 break;
1997
1998 case ImplicitConversionSequence::Indistinguishable:
1999 break;
2000
2001 case ImplicitConversionSequence::Worse:
2002 if (SCS2.Deprecated)
2003 Result = ImplicitConversionSequence::Indistinguishable;
2004 break;
2005 }
2006
2007 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002008}
2009
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002010/// CompareDerivedToBaseConversions - Compares two standard conversion
2011/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002012/// various kinds of derived-to-base conversions (C++
2013/// [over.ics.rank]p4b3). As part of these checks, we also look at
2014/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002015ImplicitConversionSequence::CompareKind
2016Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2017 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002018 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002019 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002020 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002021 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002022
2023 // Adjust the types we're converting from via the array-to-pointer
2024 // conversion, if we need to.
2025 if (SCS1.First == ICK_Array_To_Pointer)
2026 FromType1 = Context.getArrayDecayedType(FromType1);
2027 if (SCS2.First == ICK_Array_To_Pointer)
2028 FromType2 = Context.getArrayDecayedType(FromType2);
2029
2030 // Canonicalize all of the types.
2031 FromType1 = Context.getCanonicalType(FromType1);
2032 ToType1 = Context.getCanonicalType(ToType1);
2033 FromType2 = Context.getCanonicalType(FromType2);
2034 ToType2 = Context.getCanonicalType(ToType2);
2035
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002036 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002037 //
2038 // If class B is derived directly or indirectly from class A and
2039 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002040 //
2041 // For Objective-C, we let A, B, and C also be Objective-C
2042 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002043
2044 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002045 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002046 SCS2.Second == ICK_Pointer_Conversion &&
2047 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2048 FromType1->isPointerType() && FromType2->isPointerType() &&
2049 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002050 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002051 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002052 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002053 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002054 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002055 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002056 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002057 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002058
John McCall183700f2009-09-21 23:43:11 +00002059 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2060 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2061 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2062 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002063
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002064 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002065 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2066 if (IsDerivedFrom(ToPointee1, ToPointee2))
2067 return ImplicitConversionSequence::Better;
2068 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2069 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002070
2071 if (ToIface1 && ToIface2) {
2072 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2073 return ImplicitConversionSequence::Better;
2074 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2075 return ImplicitConversionSequence::Worse;
2076 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002077 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002078
2079 // -- conversion of B* to A* is better than conversion of C* to A*,
2080 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2081 if (IsDerivedFrom(FromPointee2, FromPointee1))
2082 return ImplicitConversionSequence::Better;
2083 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2084 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Douglas Gregorcb7de522008-11-26 23:31:11 +00002086 if (FromIface1 && FromIface2) {
2087 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2088 return ImplicitConversionSequence::Better;
2089 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2090 return ImplicitConversionSequence::Worse;
2091 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002092 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002093 }
2094
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002095 // Compare based on reference bindings.
2096 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
2097 SCS1.Second == ICK_Derived_To_Base) {
2098 // -- binding of an expression of type C to a reference of type
2099 // B& is better than binding an expression of type C to a
2100 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002101 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2102 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002103 if (IsDerivedFrom(ToType1, ToType2))
2104 return ImplicitConversionSequence::Better;
2105 else if (IsDerivedFrom(ToType2, ToType1))
2106 return ImplicitConversionSequence::Worse;
2107 }
2108
Douglas Gregor225c41e2008-11-03 19:09:14 +00002109 // -- binding of an expression of type B to a reference of type
2110 // A& is better than binding an expression of type C to a
2111 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002112 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2113 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002114 if (IsDerivedFrom(FromType2, FromType1))
2115 return ImplicitConversionSequence::Better;
2116 else if (IsDerivedFrom(FromType1, FromType2))
2117 return ImplicitConversionSequence::Worse;
2118 }
2119 }
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002120
2121 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002122 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2123 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2124 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2125 const MemberPointerType * FromMemPointer1 =
2126 FromType1->getAs<MemberPointerType>();
2127 const MemberPointerType * ToMemPointer1 =
2128 ToType1->getAs<MemberPointerType>();
2129 const MemberPointerType * FromMemPointer2 =
2130 FromType2->getAs<MemberPointerType>();
2131 const MemberPointerType * ToMemPointer2 =
2132 ToType2->getAs<MemberPointerType>();
2133 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2134 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2135 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2136 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2137 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2138 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2139 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2140 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002141 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002142 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2143 if (IsDerivedFrom(ToPointee1, ToPointee2))
2144 return ImplicitConversionSequence::Worse;
2145 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2146 return ImplicitConversionSequence::Better;
2147 }
2148 // conversion of B::* to C::* is better than conversion of A::* to C::*
2149 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2150 if (IsDerivedFrom(FromPointee1, FromPointee2))
2151 return ImplicitConversionSequence::Better;
2152 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2153 return ImplicitConversionSequence::Worse;
2154 }
2155 }
2156
Douglas Gregor225c41e2008-11-03 19:09:14 +00002157 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2158 SCS1.Second == ICK_Derived_To_Base) {
2159 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002160 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2161 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002162 if (IsDerivedFrom(ToType1, ToType2))
2163 return ImplicitConversionSequence::Better;
2164 else if (IsDerivedFrom(ToType2, ToType1))
2165 return ImplicitConversionSequence::Worse;
2166 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002167
Douglas Gregor225c41e2008-11-03 19:09:14 +00002168 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002169 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2170 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002171 if (IsDerivedFrom(FromType2, FromType1))
2172 return ImplicitConversionSequence::Better;
2173 else if (IsDerivedFrom(FromType1, FromType2))
2174 return ImplicitConversionSequence::Worse;
2175 }
2176 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002177
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002178 return ImplicitConversionSequence::Indistinguishable;
2179}
2180
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002181/// TryCopyInitialization - Try to copy-initialize a value of type
2182/// ToType from the expression From. Return the implicit conversion
2183/// sequence required to pass this argument, which may be a bad
2184/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002185/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00002186/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2187/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00002188ImplicitConversionSequence
2189Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002190 bool SuppressUserConversions, bool ForceRValue,
2191 bool InOverloadResolution) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00002192 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002193 ImplicitConversionSequence ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002194 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00002195 CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002196 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002197 SuppressUserConversions,
2198 /*AllowExplicit=*/false,
2199 ForceRValue,
2200 &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002201 return ICS;
2202 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002203 return TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002204 SuppressUserConversions,
2205 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002206 ForceRValue,
2207 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002208 }
2209}
2210
Sebastian Redle2b68332009-04-12 17:16:29 +00002211/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2212/// the expression @p From. Returns true (and emits a diagnostic) if there was
2213/// an error, returns false if the initialization succeeded. Elidable should
2214/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2215/// differently in C++0x for this case.
Mike Stump1eb44332009-09-09 15:08:12 +00002216bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00002217 AssignmentAction Action, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002218 if (!getLangOptions().CPlusPlus) {
2219 // In C, argument passing is the same as performing an assignment.
2220 QualType FromType = From->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002221
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002222 AssignConvertType ConvTy =
2223 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00002224 if (ConvTy != Compatible &&
2225 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2226 ConvTy = Compatible;
Mike Stump1eb44332009-09-09 15:08:12 +00002227
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002228 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00002229 FromType, From, Action);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002230 }
Sebastian Redle2b68332009-04-12 17:16:29 +00002231
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002232 if (ToType->isReferenceType())
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002233 return CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002234 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002235 /*SuppressUserConversions=*/false,
2236 /*AllowExplicit=*/false,
2237 /*ForceRValue=*/false);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002238
Douglas Gregor68647482009-12-16 03:45:30 +00002239 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redle2b68332009-04-12 17:16:29 +00002240 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002241 return false;
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002242 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002243 return Diag(From->getSourceRange().getBegin(),
2244 diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00002245 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002246 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002247}
2248
Douglas Gregor96176b32008-11-18 23:14:02 +00002249/// TryObjectArgumentInitialization - Try to initialize the object
2250/// parameter of the given member function (@c Method) from the
2251/// expression @p From.
2252ImplicitConversionSequence
John McCall651f3ee2010-01-14 03:28:57 +00002253Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall701c89e2009-12-03 04:06:58 +00002254 CXXMethodDecl *Method,
2255 CXXRecordDecl *ActingContext) {
2256 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002257 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2258 // const volatile object.
2259 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2260 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2261 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002262
2263 // Set up the conversion sequence as a "bad" conversion, to allow us
2264 // to exit early.
2265 ImplicitConversionSequence ICS;
2266 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00002267 ICS.setBad();
Douglas Gregor96176b32008-11-18 23:14:02 +00002268
2269 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00002270 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002271 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002272 FromType = PT->getPointeeType();
2273
2274 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002275
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002276 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002277 // where X is the class of which the function is a member
2278 // (C++ [over.match.funcs]p4). However, when finding an implicit
2279 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002280 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002281 // (C++ [over.match.funcs]p5). We perform a simplified version of
2282 // reference binding here, that allows class rvalues to bind to
2283 // non-constant references.
2284
2285 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2286 // with the implicit object parameter (C++ [over.match.funcs]p5).
2287 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002288 if (ImplicitParamType.getCVRQualifiers()
2289 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00002290 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall651f3ee2010-01-14 03:28:57 +00002291 ICS.Bad.init(BadConversionSequence::bad_qualifiers,
2292 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002293 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002294 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002295
2296 // Check that we have either the same type or a derived type. It
2297 // affects the conversion rank.
2298 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002299 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor96176b32008-11-18 23:14:02 +00002300 ICS.Standard.Second = ICK_Identity;
2301 else if (IsDerivedFrom(FromType, ClassType))
2302 ICS.Standard.Second = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00002303 else {
2304 ICS.Bad.init(BadConversionSequence::unrelated_class, FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002305 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002306 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002307
2308 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00002309 ICS.setStandard();
2310 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00002311 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002312 ICS.Standard.ReferenceBinding = true;
2313 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002314 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002315 return ICS;
2316}
2317
2318/// PerformObjectArgumentInitialization - Perform initialization of
2319/// the implicit object parameter for the given Method with the given
2320/// expression.
2321bool
2322Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002323 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002324 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002325 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002326
Ted Kremenek6217b802009-07-29 21:53:49 +00002327 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002328 FromRecordType = PT->getPointeeType();
2329 DestType = Method->getThisType(Context);
2330 } else {
2331 FromRecordType = From->getType();
2332 DestType = ImplicitParamRecordType;
2333 }
2334
John McCall701c89e2009-12-03 04:06:58 +00002335 // Note that we always use the true parent context when performing
2336 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002337 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00002338 = TryObjectArgumentInitialization(From->getType(), Method,
2339 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00002340 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00002341 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002342 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002343 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002344
Douglas Gregor96176b32008-11-18 23:14:02 +00002345 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssona552f7c2009-05-01 18:34:30 +00002346 CheckDerivedToBaseConversion(FromRecordType,
2347 ImplicitParamRecordType,
Douglas Gregor96176b32008-11-18 23:14:02 +00002348 From->getSourceRange().getBegin(),
2349 From->getSourceRange()))
2350 return true;
2351
Mike Stump1eb44332009-09-09 15:08:12 +00002352 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson116b7d92009-08-07 18:45:49 +00002353 /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002354 return false;
2355}
2356
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002357/// TryContextuallyConvertToBool - Attempt to contextually convert the
2358/// expression From to bool (C++0x [conv]p3).
2359ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002360 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002361 // FIXME: Are these flags correct?
2362 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002363 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002364 /*ForceRValue=*/false,
2365 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002366}
2367
2368/// PerformContextuallyConvertToBool - Perform a contextual conversion
2369/// of the expression From to bool (C++0x [conv]p3).
2370bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2371 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall1d318332010-01-12 00:44:57 +00002372 if (!ICS.isBad())
2373 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002374
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002375 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002376 return Diag(From->getSourceRange().getBegin(),
2377 diag::err_typecheck_bool_condition)
2378 << From->getType() << From->getSourceRange();
2379 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002380}
2381
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002382/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002383/// candidate functions, using the given function call arguments. If
2384/// @p SuppressUserConversions, then don't allow user-defined
2385/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002386/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2387/// hacky way to implement the overloading rules for elidable copy
2388/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002389///
2390/// \para PartialOverloading true if we are performing "partial" overloading
2391/// based on an incomplete set of function arguments. This feature is used by
2392/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00002393void
2394Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall86820f52010-01-26 01:37:31 +00002395 AccessSpecifier Access,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002396 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002397 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002398 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002399 bool ForceRValue,
2400 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00002401 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002402 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002403 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002404 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002405 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002406
Douglas Gregor88a35142008-12-22 05:46:06 +00002407 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002408 if (!isa<CXXConstructorDecl>(Method)) {
2409 // If we get here, it's because we're calling a member function
2410 // that is named without a member access expression (e.g.,
2411 // "this->f") that was either written explicitly or created
2412 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00002413 // function, e.g., X::f(). We use an empty type for the implied
2414 // object argument (C++ [over.call.func]p3), and the acting context
2415 // is irrelevant.
John McCall86820f52010-01-26 01:37:31 +00002416 AddMethodCandidate(Method, Access, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00002417 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002418 SuppressUserConversions, ForceRValue);
2419 return;
2420 }
2421 // We treat a constructor like a non-member function, since its object
2422 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002423 }
2424
Douglas Gregorfd476482009-11-13 23:59:09 +00002425 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00002426 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00002427
Douglas Gregor7edfb692009-11-23 12:27:39 +00002428 // Overload resolution is always an unevaluated context.
2429 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2430
Douglas Gregor66724ea2009-11-14 01:20:54 +00002431 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2432 // C++ [class.copy]p3:
2433 // A member function template is never instantiated to perform the copy
2434 // of a class object to an object of its class type.
2435 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2436 if (NumArgs == 1 &&
2437 Constructor->isCopyConstructorLikeSpecialization() &&
2438 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2439 return;
2440 }
2441
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002442 // Add this candidate
2443 CandidateSet.push_back(OverloadCandidate());
2444 OverloadCandidate& Candidate = CandidateSet.back();
2445 Candidate.Function = Function;
John McCall86820f52010-01-26 01:37:31 +00002446 Candidate.Access = Access;
Douglas Gregor88a35142008-12-22 05:46:06 +00002447 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002448 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002449 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002450
2451 unsigned NumArgsInProto = Proto->getNumArgs();
2452
2453 // (C++ 13.3.2p2): A candidate function having fewer than m
2454 // parameters is viable only if it has an ellipsis in its parameter
2455 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00002456 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2457 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002458 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002459 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002460 return;
2461 }
2462
2463 // (C++ 13.3.2p2): A candidate function having more than m parameters
2464 // is viable only if the (m+1)st parameter has a default argument
2465 // (8.3.6). For the purposes of overload resolution, the
2466 // parameter list is truncated on the right, so that there are
2467 // exactly m parameters.
2468 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002469 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002470 // Not enough arguments.
2471 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002472 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002473 return;
2474 }
2475
2476 // Determine the implicit conversion sequences for each of the
2477 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002478 Candidate.Conversions.resize(NumArgs);
2479 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2480 if (ArgIdx < NumArgsInProto) {
2481 // (C++ 13.3.2p3): for F to be a viable function, there shall
2482 // exist for each argument an implicit conversion sequence
2483 // (13.3.3.1) that converts that argument to the corresponding
2484 // parameter of F.
2485 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002486 Candidate.Conversions[ArgIdx]
2487 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002488 SuppressUserConversions, ForceRValue,
2489 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00002490 if (Candidate.Conversions[ArgIdx].isBad()) {
2491 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002492 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00002493 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00002494 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002495 } else {
2496 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2497 // argument for which there is no corresponding parameter is
2498 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002499 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002500 }
2501 }
2502}
2503
Douglas Gregor063daf62009-03-13 18:40:31 +00002504/// \brief Add all of the function declarations in the given function set to
2505/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00002506void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00002507 Expr **Args, unsigned NumArgs,
2508 OverloadCandidateSet& CandidateSet,
2509 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00002510 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall701c89e2009-12-03 04:06:58 +00002511 // FIXME: using declarations
Douglas Gregor3f396022009-09-28 04:47:19 +00002512 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2513 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall6e266892010-01-26 03:27:55 +00002514 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getAccess(),
John McCall701c89e2009-12-03 04:06:58 +00002515 cast<CXXMethodDecl>(FD)->getParent(),
2516 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002517 CandidateSet, SuppressUserConversions);
2518 else
John McCall86820f52010-01-26 01:37:31 +00002519 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00002520 SuppressUserConversions);
2521 } else {
2522 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2523 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2524 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall6e266892010-01-26 03:27:55 +00002525 AddMethodTemplateCandidate(FunTmpl, F.getAccess(),
John McCall701c89e2009-12-03 04:06:58 +00002526 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00002527 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00002528 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002529 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002530 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00002531 else
John McCall86820f52010-01-26 01:37:31 +00002532 AddTemplateOverloadCandidate(FunTmpl, AS_none,
John McCalld5532b62009-11-23 01:53:49 +00002533 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00002534 Args, NumArgs, CandidateSet,
2535 SuppressUserConversions);
2536 }
Douglas Gregor364e0212009-06-27 21:05:07 +00002537 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002538}
2539
John McCall314be4e2009-11-17 07:50:12 +00002540/// AddMethodCandidate - Adds a named decl (which is some kind of
2541/// method) as a method candidate to the given overload set.
John McCall701c89e2009-12-03 04:06:58 +00002542void Sema::AddMethodCandidate(NamedDecl *Decl,
John McCall86820f52010-01-26 01:37:31 +00002543 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002544 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00002545 Expr **Args, unsigned NumArgs,
2546 OverloadCandidateSet& CandidateSet,
2547 bool SuppressUserConversions, bool ForceRValue) {
John McCall701c89e2009-12-03 04:06:58 +00002548 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00002549
2550 if (isa<UsingShadowDecl>(Decl))
2551 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2552
2553 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2554 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2555 "Expected a member function template");
John McCall86820f52010-01-26 01:37:31 +00002556 AddMethodTemplateCandidate(TD, Access, ActingContext, /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00002557 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002558 CandidateSet,
2559 SuppressUserConversions,
2560 ForceRValue);
2561 } else {
John McCall86820f52010-01-26 01:37:31 +00002562 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Access, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00002563 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002564 CandidateSet, SuppressUserConversions, ForceRValue);
2565 }
2566}
2567
Douglas Gregor96176b32008-11-18 23:14:02 +00002568/// AddMethodCandidate - Adds the given C++ member function to the set
2569/// of candidate functions, using the given function call arguments
2570/// and the object argument (@c Object). For example, in a call
2571/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2572/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2573/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002574/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2575/// a slightly hacky way to implement the overloading rules for elidable copy
2576/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002577void
John McCall86820f52010-01-26 01:37:31 +00002578Sema::AddMethodCandidate(CXXMethodDecl *Method, AccessSpecifier Access,
2579 CXXRecordDecl *ActingContext, QualType ObjectType,
2580 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00002581 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002582 bool SuppressUserConversions, bool ForceRValue) {
2583 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002584 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002585 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002586 assert(!isa<CXXConstructorDecl>(Method) &&
2587 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002588
Douglas Gregor3f396022009-09-28 04:47:19 +00002589 if (!CandidateSet.isNewCandidate(Method))
2590 return;
2591
Douglas Gregor7edfb692009-11-23 12:27:39 +00002592 // Overload resolution is always an unevaluated context.
2593 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2594
Douglas Gregor96176b32008-11-18 23:14:02 +00002595 // Add this candidate
2596 CandidateSet.push_back(OverloadCandidate());
2597 OverloadCandidate& Candidate = CandidateSet.back();
2598 Candidate.Function = Method;
John McCall86820f52010-01-26 01:37:31 +00002599 Candidate.Access = Access;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002600 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002601 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002602
2603 unsigned NumArgsInProto = Proto->getNumArgs();
2604
2605 // (C++ 13.3.2p2): A candidate function having fewer than m
2606 // parameters is viable only if it has an ellipsis in its parameter
2607 // list (8.3.5).
2608 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2609 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002610 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00002611 return;
2612 }
2613
2614 // (C++ 13.3.2p2): A candidate function having more than m parameters
2615 // is viable only if the (m+1)st parameter has a default argument
2616 // (8.3.6). For the purposes of overload resolution, the
2617 // parameter list is truncated on the right, so that there are
2618 // exactly m parameters.
2619 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2620 if (NumArgs < MinRequiredArgs) {
2621 // Not enough arguments.
2622 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002623 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00002624 return;
2625 }
2626
2627 Candidate.Viable = true;
2628 Candidate.Conversions.resize(NumArgs + 1);
2629
John McCall701c89e2009-12-03 04:06:58 +00002630 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00002631 // The implicit object argument is ignored.
2632 Candidate.IgnoreObjectArgument = true;
2633 else {
2634 // Determine the implicit conversion sequence for the object
2635 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00002636 Candidate.Conversions[0]
2637 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00002638 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002639 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002640 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00002641 return;
2642 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002643 }
2644
2645 // Determine the implicit conversion sequences for each of the
2646 // arguments.
2647 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2648 if (ArgIdx < NumArgsInProto) {
2649 // (C++ 13.3.2p3): for F to be a viable function, there shall
2650 // exist for each argument an implicit conversion sequence
2651 // (13.3.3.1) that converts that argument to the corresponding
2652 // parameter of F.
2653 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002654 Candidate.Conversions[ArgIdx + 1]
2655 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002656 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002657 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00002658 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002659 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002660 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00002661 break;
2662 }
2663 } else {
2664 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2665 // argument for which there is no corresponding parameter is
2666 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002667 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00002668 }
2669 }
2670}
2671
Douglas Gregor6b906862009-08-21 00:16:32 +00002672/// \brief Add a C++ member function template as a candidate to the candidate
2673/// set, using template argument deduction to produce an appropriate member
2674/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002675void
Douglas Gregor6b906862009-08-21 00:16:32 +00002676Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall86820f52010-01-26 01:37:31 +00002677 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002678 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00002679 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00002680 QualType ObjectType,
2681 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002682 OverloadCandidateSet& CandidateSet,
2683 bool SuppressUserConversions,
2684 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002685 if (!CandidateSet.isNewCandidate(MethodTmpl))
2686 return;
2687
Douglas Gregor6b906862009-08-21 00:16:32 +00002688 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002689 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002690 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002691 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002692 // candidate functions in the usual way.113) A given name can refer to one
2693 // or more function templates and also to a set of overloaded non-template
2694 // functions. In such a case, the candidate functions generated from each
2695 // function template are combined with the set of non-template candidate
2696 // functions.
2697 TemplateDeductionInfo Info(Context);
2698 FunctionDecl *Specialization = 0;
2699 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002700 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002701 Args, NumArgs, Specialization, Info)) {
2702 // FIXME: Record what happened with template argument deduction, so
2703 // that we can give the user a beautiful diagnostic.
2704 (void)Result;
2705 return;
2706 }
Mike Stump1eb44332009-09-09 15:08:12 +00002707
Douglas Gregor6b906862009-08-21 00:16:32 +00002708 // Add the function template specialization produced by template argument
2709 // deduction as a candidate.
2710 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002711 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002712 "Specialization is not a member function?");
John McCall86820f52010-01-26 01:37:31 +00002713 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Access,
2714 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002715 CandidateSet, SuppressUserConversions, ForceRValue);
2716}
2717
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002718/// \brief Add a C++ function template specialization as a candidate
2719/// in the candidate set, using template argument deduction to produce
2720/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002721void
Douglas Gregore53060f2009-06-25 22:08:12 +00002722Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall86820f52010-01-26 01:37:31 +00002723 AccessSpecifier Access,
John McCalld5532b62009-11-23 01:53:49 +00002724 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002725 Expr **Args, unsigned NumArgs,
2726 OverloadCandidateSet& CandidateSet,
2727 bool SuppressUserConversions,
2728 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002729 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2730 return;
2731
Douglas Gregore53060f2009-06-25 22:08:12 +00002732 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002733 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00002734 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002735 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00002736 // candidate functions in the usual way.113) A given name can refer to one
2737 // or more function templates and also to a set of overloaded non-template
2738 // functions. In such a case, the candidate functions generated from each
2739 // function template are combined with the set of non-template candidate
2740 // functions.
2741 TemplateDeductionInfo Info(Context);
2742 FunctionDecl *Specialization = 0;
2743 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002744 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002745 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00002746 CandidateSet.push_back(OverloadCandidate());
2747 OverloadCandidate &Candidate = CandidateSet.back();
2748 Candidate.Function = FunctionTemplate->getTemplatedDecl();
John McCall86820f52010-01-26 01:37:31 +00002749 Candidate.Access = Access;
John McCall578b69b2009-12-16 08:11:27 +00002750 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002751 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00002752 Candidate.IsSurrogate = false;
2753 Candidate.IgnoreObjectArgument = false;
John McCall342fec42010-02-01 18:53:26 +00002754
2755 // TODO: record more information about failed template arguments
2756 Candidate.DeductionFailure.Result = Result;
2757 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregore53060f2009-06-25 22:08:12 +00002758 return;
2759 }
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Douglas Gregore53060f2009-06-25 22:08:12 +00002761 // Add the function template specialization produced by template argument
2762 // deduction as a candidate.
2763 assert(Specialization && "Missing function template specialization?");
John McCall86820f52010-01-26 01:37:31 +00002764 AddOverloadCandidate(Specialization, Access, Args, NumArgs, CandidateSet,
Douglas Gregore53060f2009-06-25 22:08:12 +00002765 SuppressUserConversions, ForceRValue);
2766}
Mike Stump1eb44332009-09-09 15:08:12 +00002767
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002768/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002769/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002770/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002771/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002772/// (which may or may not be the same type as the type that the
2773/// conversion function produces).
2774void
2775Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall86820f52010-01-26 01:37:31 +00002776 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002777 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002778 Expr *From, QualType ToType,
2779 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002780 assert(!Conversion->getDescribedFunctionTemplate() &&
2781 "Conversion function templates use AddTemplateConversionCandidate");
2782
Douglas Gregor3f396022009-09-28 04:47:19 +00002783 if (!CandidateSet.isNewCandidate(Conversion))
2784 return;
2785
Douglas Gregor7edfb692009-11-23 12:27:39 +00002786 // Overload resolution is always an unevaluated context.
2787 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2788
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002789 // Add this candidate
2790 CandidateSet.push_back(OverloadCandidate());
2791 OverloadCandidate& Candidate = CandidateSet.back();
2792 Candidate.Function = Conversion;
John McCall86820f52010-01-26 01:37:31 +00002793 Candidate.Access = Access;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002794 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002795 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002796 Candidate.FinalConversion.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00002797 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
Douglas Gregorad323a82010-01-27 03:51:04 +00002798 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002799
Douglas Gregor96176b32008-11-18 23:14:02 +00002800 // Determine the implicit conversion sequence for the implicit
2801 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002802 Candidate.Viable = true;
2803 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00002804 Candidate.Conversions[0]
2805 = TryObjectArgumentInitialization(From->getType(), Conversion,
2806 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002807 // Conversion functions to a different type in the base class is visible in
2808 // the derived class. So, a derived to base conversion should not participate
2809 // in overload resolution.
2810 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2811 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall1d318332010-01-12 00:44:57 +00002812 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002813 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002814 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002815 return;
2816 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002817
2818 // We won't go through a user-define type conversion function to convert a
2819 // derived to base as such conversions are given Conversion Rank. They only
2820 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2821 QualType FromCanon
2822 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2823 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2824 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2825 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00002826 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002827 return;
2828 }
2829
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002830
2831 // To determine what the conversion from the result of calling the
2832 // conversion function to the type we're eventually trying to
2833 // convert to (ToType), we need to synthesize a call to the
2834 // conversion function and attempt copy initialization from it. This
2835 // makes sure that we get the right semantics with respect to
2836 // lvalues/rvalues and the type. Fortunately, we can allocate this
2837 // call on the stack and we don't need its arguments to be
2838 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002839 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002840 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002841 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00002842 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002843 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002844
2845 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002846 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2847 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002848 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002849 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002850 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00002851 ImplicitConversionSequence ICS =
2852 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002853 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002854 /*ForceRValue=*/false,
2855 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002856
John McCall1d318332010-01-12 00:44:57 +00002857 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002858 case ImplicitConversionSequence::StandardConversion:
2859 Candidate.FinalConversion = ICS.Standard;
2860 break;
2861
2862 case ImplicitConversionSequence::BadConversion:
2863 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00002864 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002865 break;
2866
2867 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002868 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002869 "Can only end up with a standard conversion sequence or failure");
2870 }
2871}
2872
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002873/// \brief Adds a conversion function template specialization
2874/// candidate to the overload set, using template argument deduction
2875/// to deduce the template arguments of the conversion function
2876/// template from the type that we are converting to (C++
2877/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002878void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002879Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall86820f52010-01-26 01:37:31 +00002880 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002881 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002882 Expr *From, QualType ToType,
2883 OverloadCandidateSet &CandidateSet) {
2884 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2885 "Only conversion function templates permitted here");
2886
Douglas Gregor3f396022009-09-28 04:47:19 +00002887 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2888 return;
2889
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002890 TemplateDeductionInfo Info(Context);
2891 CXXConversionDecl *Specialization = 0;
2892 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002893 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002894 Specialization, Info)) {
2895 // FIXME: Record what happened with template argument deduction, so
2896 // that we can give the user a beautiful diagnostic.
2897 (void)Result;
2898 return;
2899 }
Mike Stump1eb44332009-09-09 15:08:12 +00002900
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002901 // Add the conversion function template specialization produced by
2902 // template argument deduction as a candidate.
2903 assert(Specialization && "Missing function template specialization?");
John McCall86820f52010-01-26 01:37:31 +00002904 AddConversionCandidate(Specialization, Access, ActingDC, From, ToType,
2905 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002906}
2907
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002908/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2909/// converts the given @c Object to a function pointer via the
2910/// conversion function @c Conversion, and then attempts to call it
2911/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2912/// the type of function that we'll eventually be calling.
2913void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall86820f52010-01-26 01:37:31 +00002914 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002915 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00002916 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00002917 QualType ObjectType,
2918 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002919 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002920 if (!CandidateSet.isNewCandidate(Conversion))
2921 return;
2922
Douglas Gregor7edfb692009-11-23 12:27:39 +00002923 // Overload resolution is always an unevaluated context.
2924 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2925
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002926 CandidateSet.push_back(OverloadCandidate());
2927 OverloadCandidate& Candidate = CandidateSet.back();
2928 Candidate.Function = 0;
John McCall86820f52010-01-26 01:37:31 +00002929 Candidate.Access = Access;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002930 Candidate.Surrogate = Conversion;
2931 Candidate.Viable = true;
2932 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002933 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002934 Candidate.Conversions.resize(NumArgs + 1);
2935
2936 // Determine the implicit conversion sequence for the implicit
2937 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002938 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00002939 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00002940 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002941 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002942 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00002943 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002944 return;
2945 }
2946
2947 // The first conversion is actually a user-defined conversion whose
2948 // first conversion is ObjectInit's standard conversion (which is
2949 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00002950 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002951 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002952 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002953 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002954 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002955 = Candidate.Conversions[0].UserDefined.Before;
2956 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2957
Mike Stump1eb44332009-09-09 15:08:12 +00002958 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002959 unsigned NumArgsInProto = Proto->getNumArgs();
2960
2961 // (C++ 13.3.2p2): A candidate function having fewer than m
2962 // parameters is viable only if it has an ellipsis in its parameter
2963 // list (8.3.5).
2964 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2965 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002966 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002967 return;
2968 }
2969
2970 // Function types don't have any default arguments, so just check if
2971 // we have enough arguments.
2972 if (NumArgs < NumArgsInProto) {
2973 // Not enough arguments.
2974 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002975 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002976 return;
2977 }
2978
2979 // Determine the implicit conversion sequences for each of the
2980 // arguments.
2981 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2982 if (ArgIdx < NumArgsInProto) {
2983 // (C++ 13.3.2p3): for F to be a viable function, there shall
2984 // exist for each argument an implicit conversion sequence
2985 // (13.3.3.1) that converts that argument to the corresponding
2986 // parameter of F.
2987 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002988 Candidate.Conversions[ArgIdx + 1]
2989 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002990 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002991 /*ForceRValue=*/false,
2992 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00002993 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002994 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002995 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002996 break;
2997 }
2998 } else {
2999 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3000 // argument for which there is no corresponding parameter is
3001 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003002 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003003 }
3004 }
3005}
3006
Mike Stump390b4cc2009-05-16 07:39:55 +00003007// FIXME: This will eventually be removed, once we've migrated all of the
3008// operator overloading logic over to the scheme used by binary operators, which
3009// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00003010void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00003011 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00003012 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00003013 OverloadCandidateSet& CandidateSet,
3014 SourceRange OpRange) {
John McCall6e266892010-01-26 03:27:55 +00003015 UnresolvedSet<16> Fns;
Douglas Gregor063daf62009-03-13 18:40:31 +00003016
3017 QualType T1 = Args[0]->getType();
3018 QualType T2;
3019 if (NumArgs > 1)
3020 T2 = Args[1]->getType();
3021
3022 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003023 if (S)
John McCall6e266892010-01-26 03:27:55 +00003024 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3025 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3026 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3027 CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00003028 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregor573d9c32009-10-21 23:19:44 +00003029 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00003030}
3031
3032/// \brief Add overload candidates for overloaded operators that are
3033/// member functions.
3034///
3035/// Add the overloaded operator candidates that are member functions
3036/// for the operator Op that was used in an operator expression such
3037/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3038/// CandidateSet will store the added overload candidates. (C++
3039/// [over.match.oper]).
3040void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3041 SourceLocation OpLoc,
3042 Expr **Args, unsigned NumArgs,
3043 OverloadCandidateSet& CandidateSet,
3044 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003045 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3046
3047 // C++ [over.match.oper]p3:
3048 // For a unary operator @ with an operand of a type whose
3049 // cv-unqualified version is T1, and for a binary operator @ with
3050 // a left operand of a type whose cv-unqualified version is T1 and
3051 // a right operand of a type whose cv-unqualified version is T2,
3052 // three sets of candidate functions, designated member
3053 // candidates, non-member candidates and built-in candidates, are
3054 // constructed as follows:
3055 QualType T1 = Args[0]->getType();
3056 QualType T2;
3057 if (NumArgs > 1)
3058 T2 = Args[1]->getType();
3059
3060 // -- If T1 is a class type, the set of member candidates is the
3061 // result of the qualified lookup of T1::operator@
3062 // (13.3.1.1.1); otherwise, the set of member candidates is
3063 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00003064 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003065 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003066 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003067 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003068
John McCalla24dc2e2009-11-17 02:14:36 +00003069 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3070 LookupQualifiedName(Operators, T1Rec->getDecl());
3071 Operators.suppressDiagnostics();
3072
Mike Stump1eb44332009-09-09 15:08:12 +00003073 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003074 OperEnd = Operators.end();
3075 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00003076 ++Oper)
John McCall86820f52010-01-26 01:37:31 +00003077 AddMethodCandidate(*Oper, Oper.getAccess(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00003078 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00003079 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00003080 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003081}
3082
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003083/// AddBuiltinCandidate - Add a candidate for a built-in
3084/// operator. ResultTy and ParamTys are the result and parameter types
3085/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003086/// arguments being passed to the candidate. IsAssignmentOperator
3087/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003088/// operator. NumContextualBoolArguments is the number of arguments
3089/// (at the beginning of the argument list) that will be contextually
3090/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00003091void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003092 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003093 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003094 bool IsAssignmentOperator,
3095 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00003096 // Overload resolution is always an unevaluated context.
3097 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3098
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003099 // Add this candidate
3100 CandidateSet.push_back(OverloadCandidate());
3101 OverloadCandidate& Candidate = CandidateSet.back();
3102 Candidate.Function = 0;
John McCall86820f52010-01-26 01:37:31 +00003103 Candidate.Access = AS_none;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003104 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003105 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003106 Candidate.BuiltinTypes.ResultTy = ResultTy;
3107 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3108 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3109
3110 // Determine the implicit conversion sequences for each of the
3111 // arguments.
3112 Candidate.Viable = true;
3113 Candidate.Conversions.resize(NumArgs);
3114 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003115 // C++ [over.match.oper]p4:
3116 // For the built-in assignment operators, conversions of the
3117 // left operand are restricted as follows:
3118 // -- no temporaries are introduced to hold the left operand, and
3119 // -- no user-defined conversions are applied to the left
3120 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00003121 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003122 //
3123 // We block these conversions by turning off user-defined
3124 // conversions, since that is the only way that initialization of
3125 // a reference to a non-class type can occur from something that
3126 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003127 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00003128 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003129 "Contextual conversion to bool requires bool type");
3130 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3131 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003132 Candidate.Conversions[ArgIdx]
3133 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00003134 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003135 /*ForceRValue=*/false,
3136 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003137 }
John McCall1d318332010-01-12 00:44:57 +00003138 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003139 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003140 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003141 break;
3142 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003143 }
3144}
3145
3146/// BuiltinCandidateTypeSet - A set of types that will be used for the
3147/// candidate operator functions for built-in operators (C++
3148/// [over.built]). The types are separated into pointer types and
3149/// enumeration types.
3150class BuiltinCandidateTypeSet {
3151 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003152 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003153
3154 /// PointerTypes - The set of pointer types that will be used in the
3155 /// built-in candidates.
3156 TypeSet PointerTypes;
3157
Sebastian Redl78eb8742009-04-19 21:53:20 +00003158 /// MemberPointerTypes - The set of member pointer types that will be
3159 /// used in the built-in candidates.
3160 TypeSet MemberPointerTypes;
3161
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003162 /// EnumerationTypes - The set of enumeration types that will be
3163 /// used in the built-in candidates.
3164 TypeSet EnumerationTypes;
3165
Douglas Gregor5842ba92009-08-24 15:23:48 +00003166 /// Sema - The semantic analysis instance where we are building the
3167 /// candidate type set.
3168 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003169
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003170 /// Context - The AST context in which we will build the type sets.
3171 ASTContext &Context;
3172
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003173 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3174 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003175 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003176
3177public:
3178 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003179 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003180
Mike Stump1eb44332009-09-09 15:08:12 +00003181 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003182 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003183
Douglas Gregor573d9c32009-10-21 23:19:44 +00003184 void AddTypesConvertedFrom(QualType Ty,
3185 SourceLocation Loc,
3186 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003187 bool AllowExplicitConversions,
3188 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003189
3190 /// pointer_begin - First pointer type found;
3191 iterator pointer_begin() { return PointerTypes.begin(); }
3192
Sebastian Redl78eb8742009-04-19 21:53:20 +00003193 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003194 iterator pointer_end() { return PointerTypes.end(); }
3195
Sebastian Redl78eb8742009-04-19 21:53:20 +00003196 /// member_pointer_begin - First member pointer type found;
3197 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3198
3199 /// member_pointer_end - Past the last member pointer type found;
3200 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3201
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003202 /// enumeration_begin - First enumeration type found;
3203 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3204
Sebastian Redl78eb8742009-04-19 21:53:20 +00003205 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003206 iterator enumeration_end() { return EnumerationTypes.end(); }
3207};
3208
Sebastian Redl78eb8742009-04-19 21:53:20 +00003209/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003210/// the set of pointer types along with any more-qualified variants of
3211/// that type. For example, if @p Ty is "int const *", this routine
3212/// will add "int const *", "int const volatile *", "int const
3213/// restrict *", and "int const volatile restrict *" to the set of
3214/// pointer types. Returns true if the add of @p Ty itself succeeded,
3215/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003216///
3217/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003218bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003219BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3220 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003221
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003222 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003223 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003224 return false;
3225
John McCall0953e762009-09-24 19:53:00 +00003226 const PointerType *PointerTy = Ty->getAs<PointerType>();
3227 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003228
John McCall0953e762009-09-24 19:53:00 +00003229 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003230 // Don't add qualified variants of arrays. For one, they're not allowed
3231 // (the qualifier would sink to the element type), and for another, the
3232 // only overload situation where it matters is subscript or pointer +- int,
3233 // and those shouldn't have qualifier variants anyway.
3234 if (PointeeTy->isArrayType())
3235 return true;
John McCall0953e762009-09-24 19:53:00 +00003236 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003237 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003238 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003239 bool hasVolatile = VisibleQuals.hasVolatile();
3240 bool hasRestrict = VisibleQuals.hasRestrict();
3241
John McCall0953e762009-09-24 19:53:00 +00003242 // Iterate through all strict supersets of BaseCVR.
3243 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3244 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003245 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3246 // in the types.
3247 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3248 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003249 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3250 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003251 }
3252
3253 return true;
3254}
3255
Sebastian Redl78eb8742009-04-19 21:53:20 +00003256/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3257/// to the set of pointer types along with any more-qualified variants of
3258/// that type. For example, if @p Ty is "int const *", this routine
3259/// will add "int const *", "int const volatile *", "int const
3260/// restrict *", and "int const volatile restrict *" to the set of
3261/// pointer types. Returns true if the add of @p Ty itself succeeded,
3262/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003263///
3264/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003265bool
3266BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3267 QualType Ty) {
3268 // Insert this type.
3269 if (!MemberPointerTypes.insert(Ty))
3270 return false;
3271
John McCall0953e762009-09-24 19:53:00 +00003272 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3273 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003274
John McCall0953e762009-09-24 19:53:00 +00003275 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003276 // Don't add qualified variants of arrays. For one, they're not allowed
3277 // (the qualifier would sink to the element type), and for another, the
3278 // only overload situation where it matters is subscript or pointer +- int,
3279 // and those shouldn't have qualifier variants anyway.
3280 if (PointeeTy->isArrayType())
3281 return true;
John McCall0953e762009-09-24 19:53:00 +00003282 const Type *ClassTy = PointerTy->getClass();
3283
3284 // Iterate through all strict supersets of the pointee type's CVR
3285 // qualifiers.
3286 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3287 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3288 if ((CVR | BaseCVR) != CVR) continue;
3289
3290 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3291 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003292 }
3293
3294 return true;
3295}
3296
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003297/// AddTypesConvertedFrom - Add each of the types to which the type @p
3298/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003299/// primarily interested in pointer types and enumeration types. We also
3300/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003301/// AllowUserConversions is true if we should look at the conversion
3302/// functions of a class type, and AllowExplicitConversions if we
3303/// should also include the explicit conversion functions of a class
3304/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003305void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003306BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003307 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003308 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003309 bool AllowExplicitConversions,
3310 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003311 // Only deal with canonical types.
3312 Ty = Context.getCanonicalType(Ty);
3313
3314 // Look through reference types; they aren't part of the type of an
3315 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003316 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003317 Ty = RefTy->getPointeeType();
3318
3319 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003320 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003321
Sebastian Redla65b5512009-11-05 16:36:20 +00003322 // If we're dealing with an array type, decay to the pointer.
3323 if (Ty->isArrayType())
3324 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3325
Ted Kremenek6217b802009-07-29 21:53:49 +00003326 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003327 QualType PointeeTy = PointerTy->getPointeeType();
3328
3329 // Insert our type, and its more-qualified variants, into the set
3330 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003331 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003332 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003333 } else if (Ty->isMemberPointerType()) {
3334 // Member pointers are far easier, since the pointee can't be converted.
3335 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3336 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003337 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003338 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003339 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003340 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003341 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003342 // No conversion functions in incomplete types.
3343 return;
3344 }
Mike Stump1eb44332009-09-09 15:08:12 +00003345
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003346 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00003347 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003348 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003349 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003350 E = Conversions->end(); I != E; ++I) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003351
Mike Stump1eb44332009-09-09 15:08:12 +00003352 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003353 // about which builtin types we can convert to.
John McCallba135432009-11-21 08:51:07 +00003354 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003355 continue;
3356
John McCallba135432009-11-21 08:51:07 +00003357 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003358 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003359 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003360 VisibleQuals);
3361 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003362 }
3363 }
3364 }
3365}
3366
Douglas Gregor19b7b152009-08-24 13:43:27 +00003367/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3368/// the volatile- and non-volatile-qualified assignment operators for the
3369/// given type to the candidate set.
3370static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3371 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003372 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003373 unsigned NumArgs,
3374 OverloadCandidateSet &CandidateSet) {
3375 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003376
Douglas Gregor19b7b152009-08-24 13:43:27 +00003377 // T& operator=(T&, T)
3378 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3379 ParamTypes[1] = T;
3380 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3381 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003382
Douglas Gregor19b7b152009-08-24 13:43:27 +00003383 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3384 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003385 ParamTypes[0]
3386 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003387 ParamTypes[1] = T;
3388 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003389 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003390 }
3391}
Mike Stump1eb44332009-09-09 15:08:12 +00003392
Sebastian Redl9994a342009-10-25 17:03:50 +00003393/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3394/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003395static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3396 Qualifiers VRQuals;
3397 const RecordType *TyRec;
3398 if (const MemberPointerType *RHSMPType =
3399 ArgExpr->getType()->getAs<MemberPointerType>())
3400 TyRec = cast<RecordType>(RHSMPType->getClass());
3401 else
3402 TyRec = ArgExpr->getType()->getAs<RecordType>();
3403 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003404 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003405 VRQuals.addVolatile();
3406 VRQuals.addRestrict();
3407 return VRQuals;
3408 }
3409
3410 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00003411 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00003412 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003413
John McCalleec51cf2010-01-20 00:46:10 +00003414 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003415 E = Conversions->end(); I != E; ++I) {
3416 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003417 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3418 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3419 CanTy = ResTypeRef->getPointeeType();
3420 // Need to go down the pointer/mempointer chain and add qualifiers
3421 // as see them.
3422 bool done = false;
3423 while (!done) {
3424 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3425 CanTy = ResTypePtr->getPointeeType();
3426 else if (const MemberPointerType *ResTypeMPtr =
3427 CanTy->getAs<MemberPointerType>())
3428 CanTy = ResTypeMPtr->getPointeeType();
3429 else
3430 done = true;
3431 if (CanTy.isVolatileQualified())
3432 VRQuals.addVolatile();
3433 if (CanTy.isRestrictQualified())
3434 VRQuals.addRestrict();
3435 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3436 return VRQuals;
3437 }
3438 }
3439 }
3440 return VRQuals;
3441}
3442
Douglas Gregor74253732008-11-19 15:42:04 +00003443/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3444/// operator overloads to the candidate set (C++ [over.built]), based
3445/// on the operator @p Op and the arguments given. For example, if the
3446/// operator is a binary '+', this routine might add "int
3447/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003448void
Mike Stump1eb44332009-09-09 15:08:12 +00003449Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003450 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00003451 Expr **Args, unsigned NumArgs,
3452 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003453 // The set of "promoted arithmetic types", which are the arithmetic
3454 // types are that preserved by promotion (C++ [over.built]p2). Note
3455 // that the first few of these types are the promoted integral
3456 // types; these types need to be first.
3457 // FIXME: What about complex?
3458 const unsigned FirstIntegralType = 0;
3459 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00003460 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003461 LastPromotedIntegralType = 13;
3462 const unsigned FirstPromotedArithmeticType = 7,
3463 LastPromotedArithmeticType = 16;
3464 const unsigned NumArithmeticTypes = 16;
3465 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003466 Context.BoolTy, Context.CharTy, Context.WCharTy,
3467// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003468 Context.SignedCharTy, Context.ShortTy,
3469 Context.UnsignedCharTy, Context.UnsignedShortTy,
3470 Context.IntTy, Context.LongTy, Context.LongLongTy,
3471 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3472 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3473 };
Douglas Gregor652371a2009-10-21 22:01:30 +00003474 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3475 "Invalid first promoted integral type");
3476 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3477 == Context.UnsignedLongLongTy &&
3478 "Invalid last promoted integral type");
3479 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3480 "Invalid first promoted arithmetic type");
3481 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3482 == Context.LongDoubleTy &&
3483 "Invalid last promoted arithmetic type");
3484
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003485 // Find all of the types that the arguments can convert to, but only
3486 // if the operator we're looking at has built-in operator candidates
3487 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003488 Qualifiers VisibleTypeConversionsQuals;
3489 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003490 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3491 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3492
Douglas Gregor5842ba92009-08-24 15:23:48 +00003493 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003494 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3495 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003496 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003497 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003498 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003499 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003500 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003501 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregor573d9c32009-10-21 23:19:44 +00003502 OpLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003503 true,
3504 (Op == OO_Exclaim ||
3505 Op == OO_AmpAmp ||
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003506 Op == OO_PipePipe),
3507 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003508 }
3509
3510 bool isComparison = false;
3511 switch (Op) {
3512 case OO_None:
3513 case NUM_OVERLOADED_OPERATORS:
3514 assert(false && "Expected an overloaded operator");
3515 break;
3516
Douglas Gregor74253732008-11-19 15:42:04 +00003517 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003518 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003519 goto UnaryStar;
3520 else
3521 goto BinaryStar;
3522 break;
3523
3524 case OO_Plus: // '+' is either unary or binary
3525 if (NumArgs == 1)
3526 goto UnaryPlus;
3527 else
3528 goto BinaryPlus;
3529 break;
3530
3531 case OO_Minus: // '-' is either unary or binary
3532 if (NumArgs == 1)
3533 goto UnaryMinus;
3534 else
3535 goto BinaryMinus;
3536 break;
3537
3538 case OO_Amp: // '&' is either unary or binary
3539 if (NumArgs == 1)
3540 goto UnaryAmp;
3541 else
3542 goto BinaryAmp;
3543
3544 case OO_PlusPlus:
3545 case OO_MinusMinus:
3546 // C++ [over.built]p3:
3547 //
3548 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3549 // is either volatile or empty, there exist candidate operator
3550 // functions of the form
3551 //
3552 // VQ T& operator++(VQ T&);
3553 // T operator++(VQ T&, int);
3554 //
3555 // C++ [over.built]p4:
3556 //
3557 // For every pair (T, VQ), where T is an arithmetic type other
3558 // than bool, and VQ is either volatile or empty, there exist
3559 // candidate operator functions of the form
3560 //
3561 // VQ T& operator--(VQ T&);
3562 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003563 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003564 Arith < NumArithmeticTypes; ++Arith) {
3565 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003566 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003567 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003568
3569 // Non-volatile version.
3570 if (NumArgs == 1)
3571 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3572 else
3573 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003574 // heuristic to reduce number of builtin candidates in the set.
3575 // Add volatile version only if there are conversions to a volatile type.
3576 if (VisibleTypeConversionsQuals.hasVolatile()) {
3577 // Volatile version
3578 ParamTypes[0]
3579 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3580 if (NumArgs == 1)
3581 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3582 else
3583 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3584 }
Douglas Gregor74253732008-11-19 15:42:04 +00003585 }
3586
3587 // C++ [over.built]p5:
3588 //
3589 // For every pair (T, VQ), where T is a cv-qualified or
3590 // cv-unqualified object type, and VQ is either volatile or
3591 // empty, there exist candidate operator functions of the form
3592 //
3593 // T*VQ& operator++(T*VQ&);
3594 // T*VQ& operator--(T*VQ&);
3595 // T* operator++(T*VQ&, int);
3596 // T* operator--(T*VQ&, int);
3597 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3598 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3599 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003600 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003601 continue;
3602
Mike Stump1eb44332009-09-09 15:08:12 +00003603 QualType ParamTypes[2] = {
3604 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003605 };
Mike Stump1eb44332009-09-09 15:08:12 +00003606
Douglas Gregor74253732008-11-19 15:42:04 +00003607 // Without volatile
3608 if (NumArgs == 1)
3609 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3610 else
3611 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3612
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003613 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3614 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003615 // With volatile
John McCall0953e762009-09-24 19:53:00 +00003616 ParamTypes[0]
3617 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00003618 if (NumArgs == 1)
3619 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3620 else
3621 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3622 }
3623 }
3624 break;
3625
3626 UnaryStar:
3627 // C++ [over.built]p6:
3628 // For every cv-qualified or cv-unqualified object type T, there
3629 // exist candidate operator functions of the form
3630 //
3631 // T& operator*(T*);
3632 //
3633 // C++ [over.built]p7:
3634 // For every function type T, there exist candidate operator
3635 // functions of the form
3636 // T& operator*(T*);
3637 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3638 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3639 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003640 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003641 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003642 &ParamTy, Args, 1, CandidateSet);
3643 }
3644 break;
3645
3646 UnaryPlus:
3647 // C++ [over.built]p8:
3648 // For every type T, there exist candidate operator functions of
3649 // the form
3650 //
3651 // T* operator+(T*);
3652 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3653 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3654 QualType ParamTy = *Ptr;
3655 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3656 }
Mike Stump1eb44332009-09-09 15:08:12 +00003657
Douglas Gregor74253732008-11-19 15:42:04 +00003658 // Fall through
3659
3660 UnaryMinus:
3661 // C++ [over.built]p9:
3662 // For every promoted arithmetic type T, there exist candidate
3663 // operator functions of the form
3664 //
3665 // T operator+(T);
3666 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003667 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003668 Arith < LastPromotedArithmeticType; ++Arith) {
3669 QualType ArithTy = ArithmeticTypes[Arith];
3670 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3671 }
3672 break;
3673
3674 case OO_Tilde:
3675 // C++ [over.built]p10:
3676 // For every promoted integral type T, there exist candidate
3677 // operator functions of the form
3678 //
3679 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003680 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003681 Int < LastPromotedIntegralType; ++Int) {
3682 QualType IntTy = ArithmeticTypes[Int];
3683 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3684 }
3685 break;
3686
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003687 case OO_New:
3688 case OO_Delete:
3689 case OO_Array_New:
3690 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003691 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003692 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003693 break;
3694
3695 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003696 UnaryAmp:
3697 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003698 // C++ [over.match.oper]p3:
3699 // -- For the operator ',', the unary operator '&', or the
3700 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003701 break;
3702
Douglas Gregor19b7b152009-08-24 13:43:27 +00003703 case OO_EqualEqual:
3704 case OO_ExclaimEqual:
3705 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003706 // For every pointer to member type T, there exist candidate operator
3707 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003708 //
3709 // bool operator==(T,T);
3710 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003711 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003712 MemPtr = CandidateTypes.member_pointer_begin(),
3713 MemPtrEnd = CandidateTypes.member_pointer_end();
3714 MemPtr != MemPtrEnd;
3715 ++MemPtr) {
3716 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3717 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3718 }
Mike Stump1eb44332009-09-09 15:08:12 +00003719
Douglas Gregor19b7b152009-08-24 13:43:27 +00003720 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003721
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003722 case OO_Less:
3723 case OO_Greater:
3724 case OO_LessEqual:
3725 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003726 // C++ [over.built]p15:
3727 //
3728 // For every pointer or enumeration type T, there exist
3729 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003730 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003731 // bool operator<(T, T);
3732 // bool operator>(T, T);
3733 // bool operator<=(T, T);
3734 // bool operator>=(T, T);
3735 // bool operator==(T, T);
3736 // bool operator!=(T, T);
3737 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3738 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3739 QualType ParamTypes[2] = { *Ptr, *Ptr };
3740 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3741 }
Mike Stump1eb44332009-09-09 15:08:12 +00003742 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003743 = CandidateTypes.enumeration_begin();
3744 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3745 QualType ParamTypes[2] = { *Enum, *Enum };
3746 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3747 }
3748
3749 // Fall through.
3750 isComparison = true;
3751
Douglas Gregor74253732008-11-19 15:42:04 +00003752 BinaryPlus:
3753 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003754 if (!isComparison) {
3755 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3756
3757 // C++ [over.built]p13:
3758 //
3759 // For every cv-qualified or cv-unqualified object type T
3760 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003761 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003762 // T* operator+(T*, ptrdiff_t);
3763 // T& operator[](T*, ptrdiff_t); [BELOW]
3764 // T* operator-(T*, ptrdiff_t);
3765 // T* operator+(ptrdiff_t, T*);
3766 // T& operator[](ptrdiff_t, T*); [BELOW]
3767 //
3768 // C++ [over.built]p14:
3769 //
3770 // For every T, where T is a pointer to object type, there
3771 // exist candidate operator functions of the form
3772 //
3773 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003774 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003775 = CandidateTypes.pointer_begin();
3776 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3777 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3778
3779 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3780 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3781
3782 if (Op == OO_Plus) {
3783 // T* operator+(ptrdiff_t, T*);
3784 ParamTypes[0] = ParamTypes[1];
3785 ParamTypes[1] = *Ptr;
3786 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3787 } else {
3788 // ptrdiff_t operator-(T, T);
3789 ParamTypes[1] = *Ptr;
3790 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3791 Args, 2, CandidateSet);
3792 }
3793 }
3794 }
3795 // Fall through
3796
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003797 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003798 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003799 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003800 // C++ [over.built]p12:
3801 //
3802 // For every pair of promoted arithmetic types L and R, there
3803 // exist candidate operator functions of the form
3804 //
3805 // LR operator*(L, R);
3806 // LR operator/(L, R);
3807 // LR operator+(L, R);
3808 // LR operator-(L, R);
3809 // bool operator<(L, R);
3810 // bool operator>(L, R);
3811 // bool operator<=(L, R);
3812 // bool operator>=(L, R);
3813 // bool operator==(L, R);
3814 // bool operator!=(L, R);
3815 //
3816 // where LR is the result of the usual arithmetic conversions
3817 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003818 //
3819 // C++ [over.built]p24:
3820 //
3821 // For every pair of promoted arithmetic types L and R, there exist
3822 // candidate operator functions of the form
3823 //
3824 // LR operator?(bool, L, R);
3825 //
3826 // where LR is the result of the usual arithmetic conversions
3827 // between types L and R.
3828 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003829 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003830 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003831 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003832 Right < LastPromotedArithmeticType; ++Right) {
3833 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003834 QualType Result
3835 = isComparison
3836 ? Context.BoolTy
3837 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003838 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3839 }
3840 }
3841 break;
3842
3843 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003844 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003845 case OO_Caret:
3846 case OO_Pipe:
3847 case OO_LessLess:
3848 case OO_GreaterGreater:
3849 // C++ [over.built]p17:
3850 //
3851 // For every pair of promoted integral types L and R, there
3852 // exist candidate operator functions of the form
3853 //
3854 // LR operator%(L, R);
3855 // LR operator&(L, R);
3856 // LR operator^(L, R);
3857 // LR operator|(L, R);
3858 // L operator<<(L, R);
3859 // L operator>>(L, R);
3860 //
3861 // where LR is the result of the usual arithmetic conversions
3862 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003863 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003864 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003865 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003866 Right < LastPromotedIntegralType; ++Right) {
3867 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3868 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3869 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003870 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003871 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3872 }
3873 }
3874 break;
3875
3876 case OO_Equal:
3877 // C++ [over.built]p20:
3878 //
3879 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003880 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003881 // empty, there exist candidate operator functions of the form
3882 //
3883 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003884 for (BuiltinCandidateTypeSet::iterator
3885 Enum = CandidateTypes.enumeration_begin(),
3886 EnumEnd = CandidateTypes.enumeration_end();
3887 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003888 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003889 CandidateSet);
3890 for (BuiltinCandidateTypeSet::iterator
3891 MemPtr = CandidateTypes.member_pointer_begin(),
3892 MemPtrEnd = CandidateTypes.member_pointer_end();
3893 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003894 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003895 CandidateSet);
3896 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003897
3898 case OO_PlusEqual:
3899 case OO_MinusEqual:
3900 // C++ [over.built]p19:
3901 //
3902 // For every pair (T, VQ), where T is any type and VQ is either
3903 // volatile or empty, there exist candidate operator functions
3904 // of the form
3905 //
3906 // T*VQ& operator=(T*VQ&, T*);
3907 //
3908 // C++ [over.built]p21:
3909 //
3910 // For every pair (T, VQ), where T is a cv-qualified or
3911 // cv-unqualified object type and VQ is either volatile or
3912 // empty, there exist candidate operator functions of the form
3913 //
3914 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3915 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3916 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3917 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3918 QualType ParamTypes[2];
3919 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3920
3921 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003922 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003923 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3924 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003925
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003926 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3927 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003928 // volatile version
John McCall0953e762009-09-24 19:53:00 +00003929 ParamTypes[0]
3930 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003931 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3932 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003933 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003934 }
3935 // Fall through.
3936
3937 case OO_StarEqual:
3938 case OO_SlashEqual:
3939 // C++ [over.built]p18:
3940 //
3941 // For every triple (L, VQ, R), where L is an arithmetic type,
3942 // VQ is either volatile or empty, and R is a promoted
3943 // arithmetic type, there exist candidate operator functions of
3944 // the form
3945 //
3946 // VQ L& operator=(VQ L&, R);
3947 // VQ L& operator*=(VQ L&, R);
3948 // VQ L& operator/=(VQ L&, R);
3949 // VQ L& operator+=(VQ L&, R);
3950 // VQ L& operator-=(VQ L&, R);
3951 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003952 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003953 Right < LastPromotedArithmeticType; ++Right) {
3954 QualType ParamTypes[2];
3955 ParamTypes[1] = ArithmeticTypes[Right];
3956
3957 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003958 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003959 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3960 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003961
3962 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003963 if (VisibleTypeConversionsQuals.hasVolatile()) {
3964 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3965 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3966 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3967 /*IsAssigmentOperator=*/Op == OO_Equal);
3968 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003969 }
3970 }
3971 break;
3972
3973 case OO_PercentEqual:
3974 case OO_LessLessEqual:
3975 case OO_GreaterGreaterEqual:
3976 case OO_AmpEqual:
3977 case OO_CaretEqual:
3978 case OO_PipeEqual:
3979 // C++ [over.built]p22:
3980 //
3981 // For every triple (L, VQ, R), where L is an integral type, VQ
3982 // is either volatile or empty, and R is a promoted integral
3983 // type, there exist candidate operator functions of the form
3984 //
3985 // VQ L& operator%=(VQ L&, R);
3986 // VQ L& operator<<=(VQ L&, R);
3987 // VQ L& operator>>=(VQ L&, R);
3988 // VQ L& operator&=(VQ L&, R);
3989 // VQ L& operator^=(VQ L&, R);
3990 // VQ L& operator|=(VQ L&, R);
3991 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003992 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003993 Right < LastPromotedIntegralType; ++Right) {
3994 QualType ParamTypes[2];
3995 ParamTypes[1] = ArithmeticTypes[Right];
3996
3997 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003998 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003999 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00004000 if (VisibleTypeConversionsQuals.hasVolatile()) {
4001 // Add this built-in operator as a candidate (VQ is 'volatile').
4002 ParamTypes[0] = ArithmeticTypes[Left];
4003 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4004 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4005 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4006 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004007 }
4008 }
4009 break;
4010
Douglas Gregor74253732008-11-19 15:42:04 +00004011 case OO_Exclaim: {
4012 // C++ [over.operator]p23:
4013 //
4014 // There also exist candidate operator functions of the form
4015 //
Mike Stump1eb44332009-09-09 15:08:12 +00004016 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00004017 // bool operator&&(bool, bool); [BELOW]
4018 // bool operator||(bool, bool); [BELOW]
4019 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004020 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4021 /*IsAssignmentOperator=*/false,
4022 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00004023 break;
4024 }
4025
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004026 case OO_AmpAmp:
4027 case OO_PipePipe: {
4028 // C++ [over.operator]p23:
4029 //
4030 // There also exist candidate operator functions of the form
4031 //
Douglas Gregor74253732008-11-19 15:42:04 +00004032 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004033 // bool operator&&(bool, bool);
4034 // bool operator||(bool, bool);
4035 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004036 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4037 /*IsAssignmentOperator=*/false,
4038 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004039 break;
4040 }
4041
4042 case OO_Subscript:
4043 // C++ [over.built]p13:
4044 //
4045 // For every cv-qualified or cv-unqualified object type T there
4046 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004047 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004048 // T* operator+(T*, ptrdiff_t); [ABOVE]
4049 // T& operator[](T*, ptrdiff_t);
4050 // T* operator-(T*, ptrdiff_t); [ABOVE]
4051 // T* operator+(ptrdiff_t, T*); [ABOVE]
4052 // T& operator[](ptrdiff_t, T*);
4053 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4054 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4055 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00004056 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004057 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004058
4059 // T& operator[](T*, ptrdiff_t)
4060 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4061
4062 // T& operator[](ptrdiff_t, T*);
4063 ParamTypes[0] = ParamTypes[1];
4064 ParamTypes[1] = *Ptr;
4065 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4066 }
4067 break;
4068
4069 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004070 // C++ [over.built]p11:
4071 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4072 // C1 is the same type as C2 or is a derived class of C2, T is an object
4073 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4074 // there exist candidate operator functions of the form
4075 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4076 // where CV12 is the union of CV1 and CV2.
4077 {
4078 for (BuiltinCandidateTypeSet::iterator Ptr =
4079 CandidateTypes.pointer_begin();
4080 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4081 QualType C1Ty = (*Ptr);
4082 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004083 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004084 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004085 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004086 if (!isa<RecordType>(C1))
4087 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004088 // heuristic to reduce number of builtin candidates in the set.
4089 // Add volatile/restrict version only if there are conversions to a
4090 // volatile/restrict type.
4091 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4092 continue;
4093 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4094 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004095 }
4096 for (BuiltinCandidateTypeSet::iterator
4097 MemPtr = CandidateTypes.member_pointer_begin(),
4098 MemPtrEnd = CandidateTypes.member_pointer_end();
4099 MemPtr != MemPtrEnd; ++MemPtr) {
4100 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4101 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00004102 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004103 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4104 break;
4105 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4106 // build CV12 T&
4107 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004108 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4109 T.isVolatileQualified())
4110 continue;
4111 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4112 T.isRestrictQualified())
4113 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004114 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004115 QualType ResultTy = Context.getLValueReferenceType(T);
4116 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4117 }
4118 }
4119 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004120 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004121
4122 case OO_Conditional:
4123 // Note that we don't consider the first argument, since it has been
4124 // contextually converted to bool long ago. The candidates below are
4125 // therefore added as binary.
4126 //
4127 // C++ [over.built]p24:
4128 // For every type T, where T is a pointer or pointer-to-member type,
4129 // there exist candidate operator functions of the form
4130 //
4131 // T operator?(bool, T, T);
4132 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004133 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4134 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4135 QualType ParamTypes[2] = { *Ptr, *Ptr };
4136 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4137 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00004138 for (BuiltinCandidateTypeSet::iterator Ptr =
4139 CandidateTypes.member_pointer_begin(),
4140 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4141 QualType ParamTypes[2] = { *Ptr, *Ptr };
4142 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4143 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004144 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004145 }
4146}
4147
Douglas Gregorfa047642009-02-04 00:32:51 +00004148/// \brief Add function candidates found via argument-dependent lookup
4149/// to the set of overloading candidates.
4150///
4151/// This routine performs argument-dependent name lookup based on the
4152/// given function name (which may also be an operator name) and adds
4153/// all of the overload candidates found by ADL to the overload
4154/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004155void
Douglas Gregorfa047642009-02-04 00:32:51 +00004156Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00004157 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00004158 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004159 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004160 OverloadCandidateSet& CandidateSet,
4161 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00004162 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00004163
John McCalla113e722010-01-26 06:04:06 +00004164 // FIXME: This approach for uniquing ADL results (and removing
4165 // redundant candidates from the set) relies on pointer-equality,
4166 // which means we need to key off the canonical decl. However,
4167 // always going back to the canonical decl might not get us the
4168 // right set of default arguments. What default arguments are
4169 // we supposed to consider on ADL candidates, anyway?
4170
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004171 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00004172 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00004173
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004174 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004175 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4176 CandEnd = CandidateSet.end();
4177 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004178 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00004179 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004180 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00004181 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00004182 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004183
4184 // For each of the ADL candidates we found, add it to the overload
4185 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00004186 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00004187 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00004188 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004189 continue;
4190
John McCall86820f52010-01-26 01:37:31 +00004191 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004192 false, false, PartialOverloading);
4193 } else
John McCall6e266892010-01-26 03:27:55 +00004194 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall86820f52010-01-26 01:37:31 +00004195 AS_none, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004196 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004197 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004198}
4199
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004200/// isBetterOverloadCandidate - Determines whether the first overload
4201/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004202bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004203Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump1eb44332009-09-09 15:08:12 +00004204 const OverloadCandidate& Cand2) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004205 // Define viable functions to be better candidates than non-viable
4206 // functions.
4207 if (!Cand2.Viable)
4208 return Cand1.Viable;
4209 else if (!Cand1.Viable)
4210 return false;
4211
Douglas Gregor88a35142008-12-22 05:46:06 +00004212 // C++ [over.match.best]p1:
4213 //
4214 // -- if F is a static member function, ICS1(F) is defined such
4215 // that ICS1(F) is neither better nor worse than ICS1(G) for
4216 // any function G, and, symmetrically, ICS1(G) is neither
4217 // better nor worse than ICS1(F).
4218 unsigned StartArg = 0;
4219 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4220 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004221
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004222 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004223 // A viable function F1 is defined to be a better function than another
4224 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004225 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004226 unsigned NumArgs = Cand1.Conversions.size();
4227 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4228 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004229 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004230 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4231 Cand2.Conversions[ArgIdx])) {
4232 case ImplicitConversionSequence::Better:
4233 // Cand1 has a better conversion sequence.
4234 HasBetterConversion = true;
4235 break;
4236
4237 case ImplicitConversionSequence::Worse:
4238 // Cand1 can't be better than Cand2.
4239 return false;
4240
4241 case ImplicitConversionSequence::Indistinguishable:
4242 // Do nothing.
4243 break;
4244 }
4245 }
4246
Mike Stump1eb44332009-09-09 15:08:12 +00004247 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004248 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004249 if (HasBetterConversion)
4250 return true;
4251
Mike Stump1eb44332009-09-09 15:08:12 +00004252 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004253 // specialization, or, if not that,
4254 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4255 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4256 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004257
4258 // -- F1 and F2 are function template specializations, and the function
4259 // template for F1 is more specialized than the template for F2
4260 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004261 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004262 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4263 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004264 if (FunctionTemplateDecl *BetterTemplate
4265 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4266 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004267 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4268 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004269 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004270
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004271 // -- the context is an initialization by user-defined conversion
4272 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4273 // from the return type of F1 to the destination type (i.e.,
4274 // the type of the entity being initialized) is a better
4275 // conversion sequence than the standard conversion sequence
4276 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004277 if (Cand1.Function && Cand2.Function &&
4278 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004279 isa<CXXConversionDecl>(Cand2.Function)) {
4280 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4281 Cand2.FinalConversion)) {
4282 case ImplicitConversionSequence::Better:
4283 // Cand1 has a better conversion sequence.
4284 return true;
4285
4286 case ImplicitConversionSequence::Worse:
4287 // Cand1 can't be better than Cand2.
4288 return false;
4289
4290 case ImplicitConversionSequence::Indistinguishable:
4291 // Do nothing
4292 break;
4293 }
4294 }
4295
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004296 return false;
4297}
4298
Mike Stump1eb44332009-09-09 15:08:12 +00004299/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004300/// within an overload candidate set.
4301///
4302/// \param CandidateSet the set of candidate functions.
4303///
4304/// \param Loc the location of the function name (or operator symbol) for
4305/// which overload resolution occurs.
4306///
Mike Stump1eb44332009-09-09 15:08:12 +00004307/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004308/// function, Best points to the candidate function found.
4309///
4310/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00004311OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4312 SourceLocation Loc,
4313 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004314 // Find the best viable function.
4315 Best = CandidateSet.end();
4316 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4317 Cand != CandidateSet.end(); ++Cand) {
4318 if (Cand->Viable) {
4319 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4320 Best = Cand;
4321 }
4322 }
4323
4324 // If we didn't find any viable functions, abort.
4325 if (Best == CandidateSet.end())
4326 return OR_No_Viable_Function;
4327
4328 // Make sure that this function is better than every other viable
4329 // function. If not, we have an ambiguity.
4330 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4331 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00004332 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004333 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004334 !isBetterOverloadCandidate(*Best, *Cand)) {
4335 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004336 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004337 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004338 }
Mike Stump1eb44332009-09-09 15:08:12 +00004339
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004340 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004341 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00004342 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004343 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004344 return OR_Deleted;
4345
Douglas Gregore0762c92009-06-19 23:52:42 +00004346 // C++ [basic.def.odr]p2:
4347 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00004348 // when referred to from a potentially-evaluated expression. [Note: this
4349 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00004350 // (clause 13), user-defined conversions (12.3.2), allocation function for
4351 // placement new (5.3.4), as well as non-default initialization (8.5).
4352 if (Best->Function)
4353 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004354 return OR_Success;
4355}
4356
John McCall3c80f572010-01-12 02:15:36 +00004357namespace {
4358
4359enum OverloadCandidateKind {
4360 oc_function,
4361 oc_method,
4362 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004363 oc_function_template,
4364 oc_method_template,
4365 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00004366 oc_implicit_default_constructor,
4367 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004368 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00004369};
4370
John McCall220ccbf2010-01-13 00:25:19 +00004371OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4372 FunctionDecl *Fn,
4373 std::string &Description) {
4374 bool isTemplate = false;
4375
4376 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4377 isTemplate = true;
4378 Description = S.getTemplateArgumentBindingsText(
4379 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4380 }
John McCallb1622a12010-01-06 09:43:14 +00004381
4382 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00004383 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004384 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004385
John McCall3c80f572010-01-12 02:15:36 +00004386 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4387 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004388 }
4389
4390 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4391 // This actually gets spelled 'candidate function' for now, but
4392 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00004393 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004394 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00004395
4396 assert(Meth->isCopyAssignment()
4397 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00004398 return oc_implicit_copy_assignment;
4399 }
4400
John McCall220ccbf2010-01-13 00:25:19 +00004401 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00004402}
4403
4404} // end anonymous namespace
4405
4406// Notes the location of an overload candidate.
4407void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00004408 std::string FnDesc;
4409 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4410 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4411 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00004412}
4413
John McCall1d318332010-01-12 00:44:57 +00004414/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4415/// "lead" diagnostic; it will be given two arguments, the source and
4416/// target types of the conversion.
4417void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4418 SourceLocation CaretLoc,
4419 const PartialDiagnostic &PDiag) {
4420 Diag(CaretLoc, PDiag)
4421 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4422 for (AmbiguousConversionSequence::const_iterator
4423 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4424 NoteOverloadCandidate(*I);
4425 }
John McCall81201622010-01-08 04:41:39 +00004426}
4427
John McCall1d318332010-01-12 00:44:57 +00004428namespace {
4429
John McCalladbb8f82010-01-13 09:16:55 +00004430void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4431 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4432 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00004433 assert(Cand->Function && "for now, candidate must be a function");
4434 FunctionDecl *Fn = Cand->Function;
4435
4436 // There's a conversion slot for the object argument if this is a
4437 // non-constructor method. Note that 'I' corresponds the
4438 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00004439 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00004440 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00004441 if (I == 0)
4442 isObjectArgument = true;
4443 else
4444 I--;
John McCall220ccbf2010-01-13 00:25:19 +00004445 }
4446
John McCall220ccbf2010-01-13 00:25:19 +00004447 std::string FnDesc;
4448 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4449
John McCalladbb8f82010-01-13 09:16:55 +00004450 Expr *FromExpr = Conv.Bad.FromExpr;
4451 QualType FromTy = Conv.Bad.getFromType();
4452 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00004453
John McCall5920dbb2010-02-02 02:42:52 +00004454 if (FromTy == S.Context.OverloadTy) {
4455 assert(FromExpr);
4456 Expr *E = FromExpr->IgnoreParens();
4457 if (isa<UnaryOperator>(E))
4458 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00004459 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00004460
4461 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4462 << (unsigned) FnKind << FnDesc
4463 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4464 << ToTy << Name << I+1;
4465 return;
4466 }
4467
John McCall258b2032010-01-23 08:10:49 +00004468 // Do some hand-waving analysis to see if the non-viability is due
4469 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00004470 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4471 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4472 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4473 CToTy = RT->getPointeeType();
4474 else {
4475 // TODO: detect and diagnose the full richness of const mismatches.
4476 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4477 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4478 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4479 }
4480
4481 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4482 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4483 // It is dumb that we have to do this here.
4484 while (isa<ArrayType>(CFromTy))
4485 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4486 while (isa<ArrayType>(CToTy))
4487 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4488
4489 Qualifiers FromQs = CFromTy.getQualifiers();
4490 Qualifiers ToQs = CToTy.getQualifiers();
4491
4492 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4493 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4494 << (unsigned) FnKind << FnDesc
4495 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4496 << FromTy
4497 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4498 << (unsigned) isObjectArgument << I+1;
4499 return;
4500 }
4501
4502 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4503 assert(CVR && "unexpected qualifiers mismatch");
4504
4505 if (isObjectArgument) {
4506 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4507 << (unsigned) FnKind << FnDesc
4508 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4509 << FromTy << (CVR - 1);
4510 } else {
4511 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4512 << (unsigned) FnKind << FnDesc
4513 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4514 << FromTy << (CVR - 1) << I+1;
4515 }
4516 return;
4517 }
4518
John McCall258b2032010-01-23 08:10:49 +00004519 // Diagnose references or pointers to incomplete types differently,
4520 // since it's far from impossible that the incompleteness triggered
4521 // the failure.
4522 QualType TempFromTy = FromTy.getNonReferenceType();
4523 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4524 TempFromTy = PTy->getPointeeType();
4525 if (TempFromTy->isIncompleteType()) {
4526 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4527 << (unsigned) FnKind << FnDesc
4528 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4529 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4530 return;
4531 }
4532
John McCall651f3ee2010-01-14 03:28:57 +00004533 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00004534 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4535 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00004536 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00004537 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00004538}
4539
4540void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4541 unsigned NumFormalArgs) {
4542 // TODO: treat calls to a missing default constructor as a special case
4543
4544 FunctionDecl *Fn = Cand->Function;
4545 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4546
4547 unsigned MinParams = Fn->getMinRequiredArguments();
4548
4549 // at least / at most / exactly
4550 unsigned mode, modeCount;
4551 if (NumFormalArgs < MinParams) {
4552 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4553 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4554 mode = 0; // "at least"
4555 else
4556 mode = 2; // "exactly"
4557 modeCount = MinParams;
4558 } else {
4559 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4560 if (MinParams != FnTy->getNumArgs())
4561 mode = 1; // "at most"
4562 else
4563 mode = 2; // "exactly"
4564 modeCount = FnTy->getNumArgs();
4565 }
4566
4567 std::string Description;
4568 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4569
4570 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4571 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00004572}
4573
John McCall342fec42010-02-01 18:53:26 +00004574/// Diagnose a failed template-argument deduction.
4575void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4576 Expr **Args, unsigned NumArgs) {
4577 FunctionDecl *Fn = Cand->Function; // pattern
4578
4579 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4580 Cand->DeductionFailure.TemplateParameter);
4581
4582 switch (Cand->DeductionFailure.Result) {
4583 case Sema::TDK_Success:
4584 llvm_unreachable("TDK_success while diagnosing bad deduction");
4585
4586 case Sema::TDK_Incomplete: {
4587 NamedDecl *ParamD;
4588 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4589 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4590 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4591 assert(ParamD && "no parameter found for incomplete deduction result");
4592 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4593 << ParamD->getDeclName();
4594 return;
4595 }
4596
4597 // TODO: diagnose these individually, then kill off
4598 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4599 case Sema::TDK_InstantiationDepth:
4600 case Sema::TDK_Inconsistent:
4601 case Sema::TDK_InconsistentQuals:
4602 case Sema::TDK_SubstitutionFailure:
4603 case Sema::TDK_NonDeducedMismatch:
4604 case Sema::TDK_TooManyArguments:
4605 case Sema::TDK_TooFewArguments:
4606 case Sema::TDK_InvalidExplicitArguments:
4607 case Sema::TDK_FailedOverloadResolution:
4608 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4609 return;
4610 }
4611}
4612
4613/// Generates a 'note' diagnostic for an overload candidate. We've
4614/// already generated a primary error at the call site.
4615///
4616/// It really does need to be a single diagnostic with its caret
4617/// pointed at the candidate declaration. Yes, this creates some
4618/// major challenges of technical writing. Yes, this makes pointing
4619/// out problems with specific arguments quite awkward. It's still
4620/// better than generating twenty screens of text for every failed
4621/// overload.
4622///
4623/// It would be great to be able to express per-candidate problems
4624/// more richly for those diagnostic clients that cared, but we'd
4625/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00004626void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4627 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00004628 FunctionDecl *Fn = Cand->Function;
4629
John McCall81201622010-01-08 04:41:39 +00004630 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00004631 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00004632 std::string FnDesc;
4633 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00004634
4635 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00004636 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00004637 return;
John McCall81201622010-01-08 04:41:39 +00004638 }
4639
John McCall220ccbf2010-01-13 00:25:19 +00004640 // We don't really have anything else to say about viable candidates.
4641 if (Cand->Viable) {
4642 S.NoteOverloadCandidate(Fn);
4643 return;
4644 }
John McCall1d318332010-01-12 00:44:57 +00004645
John McCalladbb8f82010-01-13 09:16:55 +00004646 switch (Cand->FailureKind) {
4647 case ovl_fail_too_many_arguments:
4648 case ovl_fail_too_few_arguments:
4649 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00004650
John McCalladbb8f82010-01-13 09:16:55 +00004651 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00004652 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4653
John McCall717e8912010-01-23 05:17:32 +00004654 case ovl_fail_trivial_conversion:
4655 case ovl_fail_bad_final_conversion:
John McCalladbb8f82010-01-13 09:16:55 +00004656 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00004657
John McCalladbb8f82010-01-13 09:16:55 +00004658 case ovl_fail_bad_conversion:
4659 for (unsigned I = 0, N = Cand->Conversions.size(); I != N; ++I)
4660 if (Cand->Conversions[I].isBad())
4661 return DiagnoseBadConversion(S, Cand, I);
4662
4663 // FIXME: this currently happens when we're called from SemaInit
4664 // when user-conversion overload fails. Figure out how to handle
4665 // those conditions and diagnose them well.
4666 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00004667 }
John McCalla1d7d622010-01-08 00:58:21 +00004668}
4669
4670void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4671 // Desugar the type of the surrogate down to a function type,
4672 // retaining as many typedefs as possible while still showing
4673 // the function type (and, therefore, its parameter types).
4674 QualType FnType = Cand->Surrogate->getConversionType();
4675 bool isLValueReference = false;
4676 bool isRValueReference = false;
4677 bool isPointer = false;
4678 if (const LValueReferenceType *FnTypeRef =
4679 FnType->getAs<LValueReferenceType>()) {
4680 FnType = FnTypeRef->getPointeeType();
4681 isLValueReference = true;
4682 } else if (const RValueReferenceType *FnTypeRef =
4683 FnType->getAs<RValueReferenceType>()) {
4684 FnType = FnTypeRef->getPointeeType();
4685 isRValueReference = true;
4686 }
4687 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4688 FnType = FnTypePtr->getPointeeType();
4689 isPointer = true;
4690 }
4691 // Desugar down to a function type.
4692 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4693 // Reconstruct the pointer/reference as appropriate.
4694 if (isPointer) FnType = S.Context.getPointerType(FnType);
4695 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4696 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4697
4698 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4699 << FnType;
4700}
4701
4702void NoteBuiltinOperatorCandidate(Sema &S,
4703 const char *Opc,
4704 SourceLocation OpLoc,
4705 OverloadCandidate *Cand) {
4706 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4707 std::string TypeStr("operator");
4708 TypeStr += Opc;
4709 TypeStr += "(";
4710 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4711 if (Cand->Conversions.size() == 1) {
4712 TypeStr += ")";
4713 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4714 } else {
4715 TypeStr += ", ";
4716 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4717 TypeStr += ")";
4718 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4719 }
4720}
4721
4722void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4723 OverloadCandidate *Cand) {
4724 unsigned NoOperands = Cand->Conversions.size();
4725 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4726 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00004727 if (ICS.isBad()) break; // all meaningless after first invalid
4728 if (!ICS.isAmbiguous()) continue;
4729
4730 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4731 PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00004732 }
4733}
4734
John McCall1b77e732010-01-15 23:32:50 +00004735SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4736 if (Cand->Function)
4737 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00004738 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00004739 return Cand->Surrogate->getLocation();
4740 return SourceLocation();
4741}
4742
John McCallbf65c0b2010-01-12 00:48:53 +00004743struct CompareOverloadCandidatesForDisplay {
4744 Sema &S;
4745 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00004746
4747 bool operator()(const OverloadCandidate *L,
4748 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00004749 // Fast-path this check.
4750 if (L == R) return false;
4751
John McCall81201622010-01-08 04:41:39 +00004752 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00004753 if (L->Viable) {
4754 if (!R->Viable) return true;
4755
4756 // TODO: introduce a tri-valued comparison for overload
4757 // candidates. Would be more worthwhile if we had a sort
4758 // that could exploit it.
4759 if (S.isBetterOverloadCandidate(*L, *R)) return true;
4760 if (S.isBetterOverloadCandidate(*R, *L)) return false;
4761 } else if (R->Viable)
4762 return false;
John McCall81201622010-01-08 04:41:39 +00004763
John McCall1b77e732010-01-15 23:32:50 +00004764 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00004765
John McCall1b77e732010-01-15 23:32:50 +00004766 // Criteria by which we can sort non-viable candidates:
4767 if (!L->Viable) {
4768 // 1. Arity mismatches come after other candidates.
4769 if (L->FailureKind == ovl_fail_too_many_arguments ||
4770 L->FailureKind == ovl_fail_too_few_arguments)
4771 return false;
4772 if (R->FailureKind == ovl_fail_too_many_arguments ||
4773 R->FailureKind == ovl_fail_too_few_arguments)
4774 return true;
John McCall81201622010-01-08 04:41:39 +00004775
John McCall717e8912010-01-23 05:17:32 +00004776 // 2. Bad conversions come first and are ordered by the number
4777 // of bad conversions and quality of good conversions.
4778 if (L->FailureKind == ovl_fail_bad_conversion) {
4779 if (R->FailureKind != ovl_fail_bad_conversion)
4780 return true;
4781
4782 // If there's any ordering between the defined conversions...
4783 // FIXME: this might not be transitive.
4784 assert(L->Conversions.size() == R->Conversions.size());
4785
4786 int leftBetter = 0;
4787 for (unsigned I = 0, E = L->Conversions.size(); I != E; ++I) {
4788 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
4789 R->Conversions[I])) {
4790 case ImplicitConversionSequence::Better:
4791 leftBetter++;
4792 break;
4793
4794 case ImplicitConversionSequence::Worse:
4795 leftBetter--;
4796 break;
4797
4798 case ImplicitConversionSequence::Indistinguishable:
4799 break;
4800 }
4801 }
4802 if (leftBetter > 0) return true;
4803 if (leftBetter < 0) return false;
4804
4805 } else if (R->FailureKind == ovl_fail_bad_conversion)
4806 return false;
4807
John McCall1b77e732010-01-15 23:32:50 +00004808 // TODO: others?
4809 }
4810
4811 // Sort everything else by location.
4812 SourceLocation LLoc = GetLocationForCandidate(L);
4813 SourceLocation RLoc = GetLocationForCandidate(R);
4814
4815 // Put candidates without locations (e.g. builtins) at the end.
4816 if (LLoc.isInvalid()) return false;
4817 if (RLoc.isInvalid()) return true;
4818
4819 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00004820 }
4821};
4822
John McCall717e8912010-01-23 05:17:32 +00004823/// CompleteNonViableCandidate - Normally, overload resolution only
4824/// computes up to the first
4825void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
4826 Expr **Args, unsigned NumArgs) {
4827 assert(!Cand->Viable);
4828
4829 // Don't do anything on failures other than bad conversion.
4830 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
4831
4832 // Skip forward to the first bad conversion.
4833 unsigned ConvIdx = 0;
4834 unsigned ConvCount = Cand->Conversions.size();
4835 while (true) {
4836 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
4837 ConvIdx++;
4838 if (Cand->Conversions[ConvIdx - 1].isBad())
4839 break;
4840 }
4841
4842 if (ConvIdx == ConvCount)
4843 return;
4844
4845 // FIXME: these should probably be preserved from the overload
4846 // operation somehow.
4847 bool SuppressUserConversions = false;
4848 bool ForceRValue = false;
4849
4850 const FunctionProtoType* Proto;
4851 unsigned ArgIdx = ConvIdx;
4852
4853 if (Cand->IsSurrogate) {
4854 QualType ConvType
4855 = Cand->Surrogate->getConversionType().getNonReferenceType();
4856 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4857 ConvType = ConvPtrType->getPointeeType();
4858 Proto = ConvType->getAs<FunctionProtoType>();
4859 ArgIdx--;
4860 } else if (Cand->Function) {
4861 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
4862 if (isa<CXXMethodDecl>(Cand->Function) &&
4863 !isa<CXXConstructorDecl>(Cand->Function))
4864 ArgIdx--;
4865 } else {
4866 // Builtin binary operator with a bad first conversion.
4867 assert(ConvCount <= 3);
4868 for (; ConvIdx != ConvCount; ++ConvIdx)
4869 Cand->Conversions[ConvIdx]
4870 = S.TryCopyInitialization(Args[ConvIdx],
4871 Cand->BuiltinTypes.ParamTypes[ConvIdx],
4872 SuppressUserConversions, ForceRValue,
4873 /*InOverloadResolution*/ true);
4874 return;
4875 }
4876
4877 // Fill in the rest of the conversions.
4878 unsigned NumArgsInProto = Proto->getNumArgs();
4879 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
4880 if (ArgIdx < NumArgsInProto)
4881 Cand->Conversions[ConvIdx]
4882 = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx),
4883 SuppressUserConversions, ForceRValue,
4884 /*InOverloadResolution=*/true);
4885 else
4886 Cand->Conversions[ConvIdx].setEllipsis();
4887 }
4888}
4889
John McCalla1d7d622010-01-08 00:58:21 +00004890} // end anonymous namespace
4891
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004892/// PrintOverloadCandidates - When overload resolution fails, prints
4893/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00004894/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00004895void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004896Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00004897 OverloadCandidateDisplayKind OCD,
John McCallcbce6062010-01-12 07:18:19 +00004898 Expr **Args, unsigned NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004899 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004900 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00004901 // Sort the candidates by viability and position. Sorting directly would
4902 // be prohibitive, so we make a set of pointers and sort those.
4903 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4904 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4905 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4906 LastCand = CandidateSet.end();
John McCall717e8912010-01-23 05:17:32 +00004907 Cand != LastCand; ++Cand) {
4908 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00004909 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00004910 else if (OCD == OCD_AllCandidates) {
4911 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
4912 Cands.push_back(Cand);
4913 }
4914 }
4915
John McCallbf65c0b2010-01-12 00:48:53 +00004916 std::sort(Cands.begin(), Cands.end(),
4917 CompareOverloadCandidatesForDisplay(*this));
John McCall81201622010-01-08 04:41:39 +00004918
John McCall1d318332010-01-12 00:44:57 +00004919 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00004920
John McCall81201622010-01-08 04:41:39 +00004921 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4922 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4923 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00004924
John McCalla1d7d622010-01-08 00:58:21 +00004925 if (Cand->Function)
John McCall220ccbf2010-01-13 00:25:19 +00004926 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00004927 else if (Cand->IsSurrogate)
4928 NoteSurrogateCandidate(*this, Cand);
4929
4930 // This a builtin candidate. We do not, in general, want to list
4931 // every possible builtin candidate.
John McCall1d318332010-01-12 00:44:57 +00004932 else if (Cand->Viable) {
4933 // Generally we only see ambiguities including viable builtin
4934 // operators if overload resolution got screwed up by an
4935 // ambiguous user-defined conversion.
4936 //
4937 // FIXME: It's quite possible for different conversions to see
4938 // different ambiguities, though.
4939 if (!ReportedAmbiguousConversions) {
4940 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4941 ReportedAmbiguousConversions = true;
4942 }
John McCalla1d7d622010-01-08 00:58:21 +00004943
John McCall1d318332010-01-12 00:44:57 +00004944 // If this is a viable builtin, print it.
John McCalla1d7d622010-01-08 00:58:21 +00004945 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004946 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004947 }
4948}
4949
John McCall7bb12da2010-02-02 06:20:04 +00004950static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, NamedDecl *D,
John McCallc373d482010-01-27 01:50:18 +00004951 AccessSpecifier AS) {
4952 if (isa<UnresolvedLookupExpr>(E))
4953 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D, AS);
4954
4955 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D, AS);
4956}
4957
Douglas Gregor904eed32008-11-10 20:40:00 +00004958/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4959/// an overloaded function (C++ [over.over]), where @p From is an
4960/// expression with overloaded function type and @p ToType is the type
4961/// we're trying to resolve to. For example:
4962///
4963/// @code
4964/// int f(double);
4965/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00004966///
Douglas Gregor904eed32008-11-10 20:40:00 +00004967/// int (*pfd)(double) = f; // selects f(double)
4968/// @endcode
4969///
4970/// This routine returns the resulting FunctionDecl if it could be
4971/// resolved, and NULL otherwise. When @p Complain is true, this
4972/// routine will emit diagnostics if there is an error.
4973FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00004974Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004975 bool Complain) {
4976 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00004977 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00004978 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00004979 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004980 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00004981 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00004982 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00004983 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004984 FunctionType = MemTypePtr->getPointeeType();
4985 IsMember = true;
4986 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004987
4988 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00004989 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00004990 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00004991 return 0;
4992
4993 // Find the actual overloaded function declaration.
John McCall7bb12da2010-02-02 06:20:04 +00004994 if (From->getType() != Context.OverloadTy)
4995 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004996
Douglas Gregor904eed32008-11-10 20:40:00 +00004997 // C++ [over.over]p1:
4998 // [...] [Note: any redundant set of parentheses surrounding the
4999 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00005000 // C++ [over.over]p1:
5001 // [...] The overloaded function name can be preceded by the &
5002 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005003 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5004 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5005 if (OvlExpr->hasExplicitTemplateArgs()) {
5006 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5007 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregor904eed32008-11-10 20:40:00 +00005008 }
5009
Douglas Gregor904eed32008-11-10 20:40:00 +00005010 // Look through all of the overloaded functions, searching for one
5011 // whose type matches exactly.
John McCallc373d482010-01-27 01:50:18 +00005012 UnresolvedSet<4> Matches; // contains only FunctionDecls
Douglas Gregor00aeb522009-07-08 23:33:52 +00005013 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00005014 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5015 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00005016 // Look through any using declarations to find the underlying function.
5017 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5018
Douglas Gregor904eed32008-11-10 20:40:00 +00005019 // C++ [over.over]p3:
5020 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00005021 // targets of type "pointer-to-function" or "reference-to-function."
5022 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00005023 // type "pointer-to-member-function."
5024 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00005025
Mike Stump1eb44332009-09-09 15:08:12 +00005026 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00005027 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005028 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00005029 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005030 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00005031 // static when converting to member pointer.
5032 if (Method->isStatic() == IsMember)
5033 continue;
5034 } else if (IsMember)
5035 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00005036
Douglas Gregor00aeb522009-07-08 23:33:52 +00005037 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005038 // If the name is a function template, template argument deduction is
5039 // done (14.8.2.2), and if the argument deduction succeeds, the
5040 // resulting template argument list is used to generate a single
5041 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00005042 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005043 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00005044 FunctionDecl *Specialization = 0;
5045 TemplateDeductionInfo Info(Context);
5046 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00005047 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00005048 FunctionType, Specialization, Info)) {
5049 // FIXME: make a note of the failed deduction for diagnostics.
5050 (void)Result;
5051 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005052 // FIXME: If the match isn't exact, shouldn't we just drop this as
5053 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00005054 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00005055 == Context.getCanonicalType(Specialization->getType()));
John McCallc373d482010-01-27 01:50:18 +00005056 Matches.addDecl(cast<FunctionDecl>(Specialization->getCanonicalDecl()),
5057 I.getAccess());
Douglas Gregor83314aa2009-07-08 20:55:45 +00005058 }
John McCallba135432009-11-21 08:51:07 +00005059
5060 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00005061 }
Mike Stump1eb44332009-09-09 15:08:12 +00005062
Chandler Carruthbd647292009-12-29 06:17:27 +00005063 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00005064 // Skip non-static functions when converting to pointer, and static
5065 // when converting to member pointer.
5066 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00005067 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005068
5069 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00005070 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005071 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00005072 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00005073 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00005074
Chandler Carruthbd647292009-12-29 06:17:27 +00005075 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00005076 QualType ResultTy;
5077 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5078 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5079 ResultTy)) {
John McCallc373d482010-01-27 01:50:18 +00005080 Matches.addDecl(cast<FunctionDecl>(FunDecl->getCanonicalDecl()),
5081 I.getAccess());
Douglas Gregor00aeb522009-07-08 23:33:52 +00005082 FoundNonTemplateFunction = true;
5083 }
Mike Stump1eb44332009-09-09 15:08:12 +00005084 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005085 }
5086
Douglas Gregor00aeb522009-07-08 23:33:52 +00005087 // If there were 0 or 1 matches, we're done.
5088 if (Matches.empty())
5089 return 0;
Sebastian Redl07ab2022009-10-17 21:12:09 +00005090 else if (Matches.size() == 1) {
John McCallc373d482010-01-27 01:50:18 +00005091 FunctionDecl *Result = cast<FunctionDecl>(*Matches.begin());
Sebastian Redl07ab2022009-10-17 21:12:09 +00005092 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00005093 if (Complain)
5094 CheckUnresolvedAccess(*this, OvlExpr, Result, Matches.begin().getAccess());
Sebastian Redl07ab2022009-10-17 21:12:09 +00005095 return Result;
5096 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00005097
5098 // C++ [over.over]p4:
5099 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00005100 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005101 // [...] and any given function template specialization F1 is
5102 // eliminated if the set contains a second function template
5103 // specialization whose function template is more specialized
5104 // than the function template of F1 according to the partial
5105 // ordering rules of 14.5.5.2.
5106
5107 // The algorithm specified above is quadratic. We instead use a
5108 // two-pass algorithm (similar to the one used to identify the
5109 // best viable function in an overload set) that identifies the
5110 // best function template (if it exists).
John McCallc373d482010-01-27 01:50:18 +00005111
5112 UnresolvedSetIterator Result =
5113 getMostSpecialized(Matches.begin(), Matches.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00005114 TPOC_Other, From->getLocStart(),
5115 PDiag(),
5116 PDiag(diag::err_addr_ovl_ambiguous)
John McCallc373d482010-01-27 01:50:18 +00005117 << Matches[0]->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00005118 PDiag(diag::note_ovl_candidate)
5119 << (unsigned) oc_function_template);
John McCallc373d482010-01-27 01:50:18 +00005120 assert(Result != Matches.end() && "no most-specialized template");
5121 MarkDeclarationReferenced(From->getLocStart(), *Result);
5122 if (Complain)
5123 CheckUnresolvedAccess(*this, OvlExpr, *Result, Result.getAccess());
5124 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00005125 }
Mike Stump1eb44332009-09-09 15:08:12 +00005126
Douglas Gregor312a2022009-09-26 03:56:17 +00005127 // [...] any function template specializations in the set are
5128 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00005129 for (unsigned I = 0, N = Matches.size(); I != N; ) {
5130 if (cast<FunctionDecl>(Matches[I].getDecl())->getPrimaryTemplate() == 0)
5131 ++I;
5132 else {
5133 Matches.erase(I);
5134 --N;
5135 }
5136 }
Douglas Gregor312a2022009-09-26 03:56:17 +00005137
Mike Stump1eb44332009-09-09 15:08:12 +00005138 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00005139 // selected function.
John McCallc373d482010-01-27 01:50:18 +00005140 if (Matches.size() == 1) {
5141 UnresolvedSetIterator Match = Matches.begin();
5142 MarkDeclarationReferenced(From->getLocStart(), *Match);
5143 if (Complain)
5144 CheckUnresolvedAccess(*this, OvlExpr, *Match, Match.getAccess());
5145 return cast<FunctionDecl>(*Match);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005146 }
Mike Stump1eb44332009-09-09 15:08:12 +00005147
Douglas Gregor00aeb522009-07-08 23:33:52 +00005148 // FIXME: We should probably return the same thing that BestViableFunction
5149 // returns (even if we issue the diagnostics here).
5150 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCallc373d482010-01-27 01:50:18 +00005151 << Matches[0]->getDeclName();
5152 for (UnresolvedSetIterator I = Matches.begin(),
5153 E = Matches.end(); I != E; ++I)
5154 NoteOverloadCandidate(cast<FunctionDecl>(*I));
Douglas Gregor904eed32008-11-10 20:40:00 +00005155 return 0;
5156}
5157
Douglas Gregor4b52e252009-12-21 23:17:24 +00005158/// \brief Given an expression that refers to an overloaded function, try to
5159/// resolve that overloaded function expression down to a single function.
5160///
5161/// This routine can only resolve template-ids that refer to a single function
5162/// template, where that template-id refers to a single template whose template
5163/// arguments are either provided by the template-id or have defaults,
5164/// as described in C++0x [temp.arg.explicit]p3.
5165FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5166 // C++ [over.over]p1:
5167 // [...] [Note: any redundant set of parentheses surrounding the
5168 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00005169 // C++ [over.over]p1:
5170 // [...] The overloaded function name can be preceded by the &
5171 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005172
5173 if (From->getType() != Context.OverloadTy)
5174 return 0;
5175
5176 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor4b52e252009-12-21 23:17:24 +00005177
5178 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00005179 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00005180 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00005181
5182 TemplateArgumentListInfo ExplicitTemplateArgs;
5183 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00005184
5185 // Look through all of the overloaded functions, searching for one
5186 // whose type matches exactly.
5187 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00005188 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5189 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00005190 // C++0x [temp.arg.explicit]p3:
5191 // [...] In contexts where deduction is done and fails, or in contexts
5192 // where deduction is not done, if a template argument list is
5193 // specified and it, along with any default template arguments,
5194 // identifies a single function template specialization, then the
5195 // template-id is an lvalue for the function template specialization.
5196 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5197
5198 // C++ [over.over]p2:
5199 // If the name is a function template, template argument deduction is
5200 // done (14.8.2.2), and if the argument deduction succeeds, the
5201 // resulting template argument list is used to generate a single
5202 // function template specialization, which is added to the set of
5203 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00005204 FunctionDecl *Specialization = 0;
5205 TemplateDeductionInfo Info(Context);
5206 if (TemplateDeductionResult Result
5207 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5208 Specialization, Info)) {
5209 // FIXME: make a note of the failed deduction for diagnostics.
5210 (void)Result;
5211 continue;
5212 }
5213
5214 // Multiple matches; we can't resolve to a single declaration.
5215 if (Matched)
5216 return 0;
5217
5218 Matched = Specialization;
5219 }
5220
5221 return Matched;
5222}
5223
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005224/// \brief Add a single candidate to the overload set.
5225static void AddOverloadedCallCandidate(Sema &S,
John McCallba135432009-11-21 08:51:07 +00005226 NamedDecl *Callee,
John McCall86820f52010-01-26 01:37:31 +00005227 AccessSpecifier Access,
John McCalld5532b62009-11-23 01:53:49 +00005228 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005229 Expr **Args, unsigned NumArgs,
5230 OverloadCandidateSet &CandidateSet,
5231 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00005232 if (isa<UsingShadowDecl>(Callee))
5233 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5234
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005235 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00005236 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall86820f52010-01-26 01:37:31 +00005237 S.AddOverloadCandidate(Func, Access, Args, NumArgs, CandidateSet,
5238 false, false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005239 return;
John McCallba135432009-11-21 08:51:07 +00005240 }
5241
5242 if (FunctionTemplateDecl *FuncTemplate
5243 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall86820f52010-01-26 01:37:31 +00005244 S.AddTemplateOverloadCandidate(FuncTemplate, Access, ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005245 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00005246 return;
5247 }
5248
5249 assert(false && "unhandled case in overloaded call candidate");
5250
5251 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005252}
5253
5254/// \brief Add the overload candidates named by callee and/or found by argument
5255/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00005256void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005257 Expr **Args, unsigned NumArgs,
5258 OverloadCandidateSet &CandidateSet,
5259 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00005260
5261#ifndef NDEBUG
5262 // Verify that ArgumentDependentLookup is consistent with the rules
5263 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005264 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005265 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5266 // and let Y be the lookup set produced by argument dependent
5267 // lookup (defined as follows). If X contains
5268 //
5269 // -- a declaration of a class member, or
5270 //
5271 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00005272 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005273 //
5274 // -- a declaration that is neither a function or a function
5275 // template
5276 //
5277 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00005278
John McCall3b4294e2009-12-16 12:17:52 +00005279 if (ULE->requiresADL()) {
5280 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5281 E = ULE->decls_end(); I != E; ++I) {
5282 assert(!(*I)->getDeclContext()->isRecord());
5283 assert(isa<UsingShadowDecl>(*I) ||
5284 !(*I)->getDeclContext()->isFunctionOrMethod());
5285 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00005286 }
5287 }
5288#endif
5289
John McCall3b4294e2009-12-16 12:17:52 +00005290 // It would be nice to avoid this copy.
5291 TemplateArgumentListInfo TABuffer;
5292 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5293 if (ULE->hasExplicitTemplateArgs()) {
5294 ULE->copyTemplateArgumentsInto(TABuffer);
5295 ExplicitTemplateArgs = &TABuffer;
5296 }
5297
5298 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5299 E = ULE->decls_end(); I != E; ++I)
John McCall86820f52010-01-26 01:37:31 +00005300 AddOverloadedCallCandidate(*this, *I, I.getAccess(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005301 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005302 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00005303
John McCall3b4294e2009-12-16 12:17:52 +00005304 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00005305 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5306 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005307 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005308 CandidateSet,
5309 PartialOverloading);
5310}
John McCall578b69b2009-12-16 08:11:27 +00005311
John McCall3b4294e2009-12-16 12:17:52 +00005312static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5313 Expr **Args, unsigned NumArgs) {
5314 Fn->Destroy(SemaRef.Context);
5315 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5316 Args[Arg]->Destroy(SemaRef.Context);
5317 return SemaRef.ExprError();
5318}
5319
John McCall578b69b2009-12-16 08:11:27 +00005320/// Attempts to recover from a call where no functions were found.
5321///
5322/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00005323static Sema::OwningExprResult
5324BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5325 UnresolvedLookupExpr *ULE,
5326 SourceLocation LParenLoc,
5327 Expr **Args, unsigned NumArgs,
5328 SourceLocation *CommaLocs,
5329 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00005330
5331 CXXScopeSpec SS;
5332 if (ULE->getQualifier()) {
5333 SS.setScopeRep(ULE->getQualifier());
5334 SS.setRange(ULE->getQualifierRange());
5335 }
5336
John McCall3b4294e2009-12-16 12:17:52 +00005337 TemplateArgumentListInfo TABuffer;
5338 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5339 if (ULE->hasExplicitTemplateArgs()) {
5340 ULE->copyTemplateArgumentsInto(TABuffer);
5341 ExplicitTemplateArgs = &TABuffer;
5342 }
5343
John McCall578b69b2009-12-16 08:11:27 +00005344 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5345 Sema::LookupOrdinaryName);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00005346 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall3b4294e2009-12-16 12:17:52 +00005347 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCall578b69b2009-12-16 08:11:27 +00005348
John McCall3b4294e2009-12-16 12:17:52 +00005349 assert(!R.empty() && "lookup results empty despite recovery");
5350
5351 // Build an implicit member call if appropriate. Just drop the
5352 // casts and such from the call, we don't really care.
5353 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5354 if ((*R.begin())->isCXXClassMember())
5355 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5356 else if (ExplicitTemplateArgs)
5357 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5358 else
5359 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5360
5361 if (NewFn.isInvalid())
5362 return Destroy(SemaRef, Fn, Args, NumArgs);
5363
5364 Fn->Destroy(SemaRef.Context);
5365
5366 // This shouldn't cause an infinite loop because we're giving it
5367 // an expression with non-empty lookup results, which should never
5368 // end up here.
5369 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5370 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5371 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00005372}
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005373
Douglas Gregorf6b89692008-11-26 05:54:23 +00005374/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00005375/// (which eventually refers to the declaration Func) and the call
5376/// arguments Args/NumArgs, attempt to resolve the function call down
5377/// to a specific function. If overload resolution succeeds, returns
5378/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00005379/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00005380/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00005381Sema::OwningExprResult
5382Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5383 SourceLocation LParenLoc,
5384 Expr **Args, unsigned NumArgs,
5385 SourceLocation *CommaLocs,
5386 SourceLocation RParenLoc) {
5387#ifndef NDEBUG
5388 if (ULE->requiresADL()) {
5389 // To do ADL, we must have found an unqualified name.
5390 assert(!ULE->getQualifier() && "qualified name with ADL");
5391
5392 // We don't perform ADL for implicit declarations of builtins.
5393 // Verify that this was correctly set up.
5394 FunctionDecl *F;
5395 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5396 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5397 F->getBuiltinID() && F->isImplicit())
5398 assert(0 && "performing ADL for builtin");
5399
5400 // We don't perform ADL in C.
5401 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5402 }
5403#endif
5404
Douglas Gregorf6b89692008-11-26 05:54:23 +00005405 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00005406
John McCall3b4294e2009-12-16 12:17:52 +00005407 // Add the functions denoted by the callee to the set of candidate
5408 // functions, including those from argument-dependent lookup.
5409 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00005410
5411 // If we found nothing, try to recover.
5412 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5413 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00005414 if (CandidateSet.empty())
5415 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5416 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00005417
Douglas Gregorf6b89692008-11-26 05:54:23 +00005418 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005419 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00005420 case OR_Success: {
5421 FunctionDecl *FDecl = Best->Function;
John McCallc373d482010-01-27 01:50:18 +00005422 CheckUnresolvedLookupAccess(ULE, FDecl, Best->getAccess());
John McCall3b4294e2009-12-16 12:17:52 +00005423 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5424 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5425 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00005426
5427 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00005428 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00005429 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00005430 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005431 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005432 break;
5433
5434 case OR_Ambiguous:
5435 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00005436 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005437 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005438 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005439
5440 case OR_Deleted:
5441 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5442 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00005443 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005444 << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005445 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005446 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00005447 }
5448
5449 // Overload resolution failed. Destroy all of the subexpressions and
5450 // return NULL.
5451 Fn->Destroy(Context);
5452 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5453 Args[Arg]->Destroy(Context);
John McCall3b4294e2009-12-16 12:17:52 +00005454 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00005455}
5456
John McCall6e266892010-01-26 03:27:55 +00005457static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00005458 return Functions.size() > 1 ||
5459 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5460}
5461
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005462/// \brief Create a unary operation that may resolve to an overloaded
5463/// operator.
5464///
5465/// \param OpLoc The location of the operator itself (e.g., '*').
5466///
5467/// \param OpcIn The UnaryOperator::Opcode that describes this
5468/// operator.
5469///
5470/// \param Functions The set of non-member functions that will be
5471/// considered by overload resolution. The caller needs to build this
5472/// set based on the context using, e.g.,
5473/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5474/// set should not contain any member functions; those will be added
5475/// by CreateOverloadedUnaryOp().
5476///
5477/// \param input The input argument.
John McCall6e266892010-01-26 03:27:55 +00005478Sema::OwningExprResult
5479Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5480 const UnresolvedSetImpl &Fns,
5481 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005482 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5483 Expr *Input = (Expr *)input.get();
5484
5485 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5486 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5487 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5488
5489 Expr *Args[2] = { Input, 0 };
5490 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00005491
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005492 // For post-increment and post-decrement, add the implicit '0' as
5493 // the second argument, so that we know this is a post-increment or
5494 // post-decrement.
5495 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5496 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00005497 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005498 SourceLocation());
5499 NumArgs = 2;
5500 }
5501
5502 if (Input->isTypeDependent()) {
John McCallc373d482010-01-27 01:50:18 +00005503 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005504 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005505 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005506 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00005507 /*ADL*/ true, IsOverloaded(Fns));
5508 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump1eb44332009-09-09 15:08:12 +00005509
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005510 input.release();
5511 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5512 &Args[0], NumArgs,
5513 Context.DependentTy,
5514 OpLoc));
5515 }
5516
5517 // Build an empty overload set.
5518 OverloadCandidateSet CandidateSet;
5519
5520 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00005521 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005522
5523 // Add operator candidates that are member functions.
5524 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5525
John McCall6e266892010-01-26 03:27:55 +00005526 // Add candidates from ADL.
5527 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5528 Args, 1,
5529 /*ExplicitTemplateArgs*/ 0,
5530 CandidateSet);
5531
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005532 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005533 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005534
5535 // Perform overload resolution.
5536 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005537 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005538 case OR_Success: {
5539 // We found a built-in operator or an overloaded operator.
5540 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00005541
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005542 if (FnDecl) {
5543 // We matched an overloaded operator. Build a call to that
5544 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00005545
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005546 // Convert the arguments.
5547 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00005548 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5549
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005550 if (PerformObjectArgumentInitialization(Input, Method))
5551 return ExprError();
5552 } else {
5553 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00005554 OwningExprResult InputInit
5555 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005556 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00005557 SourceLocation(),
5558 move(input));
5559 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005560 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005561
Douglas Gregore1a5c172009-12-23 17:40:29 +00005562 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005563 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005564 }
5565
5566 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00005567 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005568
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005569 // Build the actual expression node.
5570 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5571 SourceLocation());
5572 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00005573
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005574 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00005575 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00005576 ExprOwningPtr<CallExpr> TheCall(this,
5577 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00005578 Args, NumArgs, ResultTy, OpLoc));
Anders Carlsson26a2a072009-10-13 21:19:37 +00005579
5580 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5581 FnDecl))
5582 return ExprError();
5583
5584 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005585 } else {
5586 // We matched a built-in operator. Convert the arguments, then
5587 // break out so that we will build the appropriate built-in
5588 // operator node.
5589 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005590 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005591 return ExprError();
5592
5593 break;
5594 }
5595 }
5596
5597 case OR_No_Viable_Function:
5598 // No viable function; fall through to handling this as a
5599 // built-in operator, which will produce an error message for us.
5600 break;
5601
5602 case OR_Ambiguous:
5603 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5604 << UnaryOperator::getOpcodeStr(Opc)
5605 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005606 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005607 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005608 return ExprError();
5609
5610 case OR_Deleted:
5611 Diag(OpLoc, diag::err_ovl_deleted_oper)
5612 << Best->Function->isDeleted()
5613 << UnaryOperator::getOpcodeStr(Opc)
5614 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005615 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005616 return ExprError();
5617 }
5618
5619 // Either we found no viable overloaded operator or we matched a
5620 // built-in operator. In either case, fall through to trying to
5621 // build a built-in operation.
5622 input.release();
5623 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5624}
5625
Douglas Gregor063daf62009-03-13 18:40:31 +00005626/// \brief Create a binary operation that may resolve to an overloaded
5627/// operator.
5628///
5629/// \param OpLoc The location of the operator itself (e.g., '+').
5630///
5631/// \param OpcIn The BinaryOperator::Opcode that describes this
5632/// operator.
5633///
5634/// \param Functions The set of non-member functions that will be
5635/// considered by overload resolution. The caller needs to build this
5636/// set based on the context using, e.g.,
5637/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5638/// set should not contain any member functions; those will be added
5639/// by CreateOverloadedBinOp().
5640///
5641/// \param LHS Left-hand argument.
5642/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005643Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00005644Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005645 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00005646 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00005647 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00005648 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005649 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00005650
5651 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5652 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5653 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5654
5655 // If either side is type-dependent, create an appropriate dependent
5656 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005657 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00005658 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005659 // If there are no functions to store, just build a dependent
5660 // BinaryOperator or CompoundAssignment.
5661 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5662 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5663 Context.DependentTy, OpLoc));
5664
5665 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5666 Context.DependentTy,
5667 Context.DependentTy,
5668 Context.DependentTy,
5669 OpLoc));
5670 }
John McCall6e266892010-01-26 03:27:55 +00005671
5672 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00005673 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005674 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005675 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005676 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00005677 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump1eb44332009-09-09 15:08:12 +00005678
John McCall6e266892010-01-26 03:27:55 +00005679 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00005680 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00005681 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00005682 Context.DependentTy,
5683 OpLoc));
5684 }
5685
5686 // If this is the .* operator, which is not overloadable, just
5687 // create a built-in binary operator.
5688 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005689 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005690
Sebastian Redl275c2b42009-11-18 23:10:33 +00005691 // If this is the assignment operator, we only perform overload resolution
5692 // if the left-hand side is a class or enumeration type. This is actually
5693 // a hack. The standard requires that we do overload resolution between the
5694 // various built-in candidates, but as DR507 points out, this can lead to
5695 // problems. So we do it this way, which pretty much follows what GCC does.
5696 // Note that we go the traditional code path for compound assignment forms.
5697 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005698 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005699
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005700 // Build an empty overload set.
5701 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00005702
5703 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00005704 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00005705
5706 // Add operator candidates that are member functions.
5707 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5708
John McCall6e266892010-01-26 03:27:55 +00005709 // Add candidates from ADL.
5710 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5711 Args, 2,
5712 /*ExplicitTemplateArgs*/ 0,
5713 CandidateSet);
5714
Douglas Gregor063daf62009-03-13 18:40:31 +00005715 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005716 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00005717
5718 // Perform overload resolution.
5719 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005720 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005721 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00005722 // We found a built-in operator or an overloaded operator.
5723 FunctionDecl *FnDecl = Best->Function;
5724
5725 if (FnDecl) {
5726 // We matched an overloaded operator. Build a call to that
5727 // operator.
5728
5729 // Convert the arguments.
5730 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00005731 // Best->Access is only meaningful for class members.
5732 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5733
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005734 OwningExprResult Arg1
5735 = PerformCopyInitialization(
5736 InitializedEntity::InitializeParameter(
5737 FnDecl->getParamDecl(0)),
5738 SourceLocation(),
5739 Owned(Args[1]));
5740 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00005741 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005742
5743 if (PerformObjectArgumentInitialization(Args[0], Method))
5744 return ExprError();
5745
5746 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00005747 } else {
5748 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005749 OwningExprResult Arg0
5750 = PerformCopyInitialization(
5751 InitializedEntity::InitializeParameter(
5752 FnDecl->getParamDecl(0)),
5753 SourceLocation(),
5754 Owned(Args[0]));
5755 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00005756 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005757
5758 OwningExprResult Arg1
5759 = PerformCopyInitialization(
5760 InitializedEntity::InitializeParameter(
5761 FnDecl->getParamDecl(1)),
5762 SourceLocation(),
5763 Owned(Args[1]));
5764 if (Arg1.isInvalid())
5765 return ExprError();
5766 Args[0] = LHS = Arg0.takeAs<Expr>();
5767 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00005768 }
5769
5770 // Determine the result type
5771 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00005772 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00005773 ResultTy = ResultTy.getNonReferenceType();
5774
5775 // Build the actual expression node.
5776 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00005777 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005778 UsualUnaryConversions(FnExpr);
5779
Anders Carlsson15ea3782009-10-13 22:43:21 +00005780 ExprOwningPtr<CXXOperatorCallExpr>
5781 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5782 Args, 2, ResultTy,
5783 OpLoc));
5784
5785 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5786 FnDecl))
5787 return ExprError();
5788
5789 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00005790 } else {
5791 // We matched a built-in operator. Convert the arguments, then
5792 // break out so that we will build the appropriate built-in
5793 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005794 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005795 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005796 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005797 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00005798 return ExprError();
5799
5800 break;
5801 }
5802 }
5803
Douglas Gregor33074752009-09-30 21:46:01 +00005804 case OR_No_Viable_Function: {
5805 // C++ [over.match.oper]p9:
5806 // If the operator is the operator , [...] and there are no
5807 // viable functions, then the operator is assumed to be the
5808 // built-in operator and interpreted according to clause 5.
5809 if (Opc == BinaryOperator::Comma)
5810 break;
5811
Sebastian Redl8593c782009-05-21 11:50:50 +00005812 // For class as left operand for assignment or compound assigment operator
5813 // do not fall through to handling in built-in, but report that no overloaded
5814 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00005815 OwningExprResult Result = ExprError();
5816 if (Args[0]->getType()->isRecordType() &&
5817 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00005818 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5819 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005820 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00005821 } else {
5822 // No viable function; try to create a built-in operation, which will
5823 // produce an error. Then, show the non-viable candidates.
5824 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00005825 }
Douglas Gregor33074752009-09-30 21:46:01 +00005826 assert(Result.isInvalid() &&
5827 "C++ binary operator overloading is missing candidates!");
5828 if (Result.isInvalid())
John McCallcbce6062010-01-12 07:18:19 +00005829 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005830 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00005831 return move(Result);
5832 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005833
5834 case OR_Ambiguous:
5835 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5836 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005837 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005838 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005839 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005840 return ExprError();
5841
5842 case OR_Deleted:
5843 Diag(OpLoc, diag::err_ovl_deleted_oper)
5844 << Best->Function->isDeleted()
5845 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005846 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005847 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00005848 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00005849 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005850
Douglas Gregor33074752009-09-30 21:46:01 +00005851 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005852 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005853}
5854
Sebastian Redlf322ed62009-10-29 20:17:01 +00005855Action::OwningExprResult
5856Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5857 SourceLocation RLoc,
5858 ExprArg Base, ExprArg Idx) {
5859 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5860 static_cast<Expr*>(Idx.get()) };
5861 DeclarationName OpName =
5862 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5863
5864 // If either side is type-dependent, create an appropriate dependent
5865 // expression.
5866 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5867
John McCallc373d482010-01-27 01:50:18 +00005868 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005869 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005870 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005871 0, SourceRange(), OpName, LLoc,
John McCall7453ed42009-11-22 00:44:51 +00005872 /*ADL*/ true, /*Overloaded*/ false);
John McCallf7a1a742009-11-24 19:00:30 +00005873 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00005874
5875 Base.release();
5876 Idx.release();
5877 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5878 Args, 2,
5879 Context.DependentTy,
5880 RLoc));
5881 }
5882
5883 // Build an empty overload set.
5884 OverloadCandidateSet CandidateSet;
5885
5886 // Subscript can only be overloaded as a member function.
5887
5888 // Add operator candidates that are member functions.
5889 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5890
5891 // Add builtin operator candidates.
5892 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5893
5894 // Perform overload resolution.
5895 OverloadCandidateSet::iterator Best;
5896 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5897 case OR_Success: {
5898 // We found a built-in operator or an overloaded operator.
5899 FunctionDecl *FnDecl = Best->Function;
5900
5901 if (FnDecl) {
5902 // We matched an overloaded operator. Build a call to that
5903 // operator.
5904
John McCall5357b612010-01-28 01:42:12 +00005905 CheckMemberOperatorAccess(LLoc, Args[0], FnDecl, Best->getAccess());
John McCallc373d482010-01-27 01:50:18 +00005906
Sebastian Redlf322ed62009-10-29 20:17:01 +00005907 // Convert the arguments.
5908 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Anders Carlsson38f88ab2010-01-29 18:37:50 +00005909 if (PerformObjectArgumentInitialization(Args[0], Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005910 return ExprError();
5911
Anders Carlsson38f88ab2010-01-29 18:37:50 +00005912 // Convert the arguments.
5913 OwningExprResult InputInit
5914 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5915 FnDecl->getParamDecl(0)),
5916 SourceLocation(),
5917 Owned(Args[1]));
5918 if (InputInit.isInvalid())
5919 return ExprError();
5920
5921 Args[1] = InputInit.takeAs<Expr>();
5922
Sebastian Redlf322ed62009-10-29 20:17:01 +00005923 // Determine the result type
5924 QualType ResultTy
5925 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5926 ResultTy = ResultTy.getNonReferenceType();
5927
5928 // Build the actual expression node.
5929 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5930 LLoc);
5931 UsualUnaryConversions(FnExpr);
5932
5933 Base.release();
5934 Idx.release();
5935 ExprOwningPtr<CXXOperatorCallExpr>
5936 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5937 FnExpr, Args, 2,
5938 ResultTy, RLoc));
5939
5940 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5941 FnDecl))
5942 return ExprError();
5943
5944 return MaybeBindToTemporary(TheCall.release());
5945 } else {
5946 // We matched a built-in operator. Convert the arguments, then
5947 // break out so that we will build the appropriate built-in
5948 // operator node.
5949 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005950 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00005951 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005952 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005953 return ExprError();
5954
5955 break;
5956 }
5957 }
5958
5959 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00005960 if (CandidateSet.empty())
5961 Diag(LLoc, diag::err_ovl_no_oper)
5962 << Args[0]->getType() << /*subscript*/ 0
5963 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5964 else
5965 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5966 << Args[0]->getType()
5967 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005968 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall1eb3e102010-01-07 02:04:15 +00005969 "[]", LLoc);
5970 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00005971 }
5972
5973 case OR_Ambiguous:
5974 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5975 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005976 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redlf322ed62009-10-29 20:17:01 +00005977 "[]", LLoc);
5978 return ExprError();
5979
5980 case OR_Deleted:
5981 Diag(LLoc, diag::err_ovl_deleted_oper)
5982 << Best->Function->isDeleted() << "[]"
5983 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005984 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall81201622010-01-08 04:41:39 +00005985 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00005986 return ExprError();
5987 }
5988
5989 // We matched a built-in operator; build it.
5990 Base.release();
5991 Idx.release();
5992 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5993 Owned(Args[1]), RLoc);
5994}
5995
Douglas Gregor88a35142008-12-22 05:46:06 +00005996/// BuildCallToMemberFunction - Build a call to a member
5997/// function. MemExpr is the expression that refers to the member
5998/// function (and includes the object parameter), Args/NumArgs are the
5999/// arguments to the function call (not including the object
6000/// parameter). The caller needs to validate that the member
6001/// expression refers to a member function or an overloaded member
6002/// function.
John McCallaa81e162009-12-01 22:10:20 +00006003Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00006004Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6005 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00006006 unsigned NumArgs, SourceLocation *CommaLocs,
6007 SourceLocation RParenLoc) {
6008 // Dig out the member expression. This holds both the object
6009 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00006010 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6011
John McCall129e2df2009-11-30 22:42:35 +00006012 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00006013 CXXMethodDecl *Method = 0;
John McCall129e2df2009-11-30 22:42:35 +00006014 if (isa<MemberExpr>(NakedMemExpr)) {
6015 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00006016 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
6017 } else {
6018 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCallaa81e162009-12-01 22:10:20 +00006019
John McCall701c89e2009-12-03 04:06:58 +00006020 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00006021
Douglas Gregor88a35142008-12-22 05:46:06 +00006022 // Add overload candidates
6023 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00006024
John McCallaa81e162009-12-01 22:10:20 +00006025 // FIXME: avoid copy.
6026 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6027 if (UnresExpr->hasExplicitTemplateArgs()) {
6028 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6029 TemplateArgs = &TemplateArgsBuffer;
6030 }
6031
John McCall129e2df2009-11-30 22:42:35 +00006032 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6033 E = UnresExpr->decls_end(); I != E; ++I) {
6034
John McCall701c89e2009-12-03 04:06:58 +00006035 NamedDecl *Func = *I;
6036 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6037 if (isa<UsingShadowDecl>(Func))
6038 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6039
John McCall129e2df2009-11-30 22:42:35 +00006040 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006041 // If explicit template arguments were provided, we can't call a
6042 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00006043 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006044 continue;
6045
John McCall86820f52010-01-26 01:37:31 +00006046 AddMethodCandidate(Method, I.getAccess(), ActingDC, ObjectType,
6047 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00006048 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006049 } else {
John McCall129e2df2009-11-30 22:42:35 +00006050 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall86820f52010-01-26 01:37:31 +00006051 I.getAccess(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00006052 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00006053 CandidateSet,
6054 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006055 }
Douglas Gregordec06662009-08-21 18:42:58 +00006056 }
Mike Stump1eb44332009-09-09 15:08:12 +00006057
John McCall129e2df2009-11-30 22:42:35 +00006058 DeclarationName DeclName = UnresExpr->getMemberName();
6059
Douglas Gregor88a35142008-12-22 05:46:06 +00006060 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00006061 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00006062 case OR_Success:
6063 Method = cast<CXXMethodDecl>(Best->Function);
John McCallc373d482010-01-27 01:50:18 +00006064 CheckUnresolvedMemberAccess(UnresExpr, Method, Best->getAccess());
Douglas Gregor88a35142008-12-22 05:46:06 +00006065 break;
6066
6067 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00006068 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00006069 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006070 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006071 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006072 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006073 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006074
6075 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00006076 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006077 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006078 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006079 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006080 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006081
6082 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00006083 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006084 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00006085 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006086 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006087 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006088 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006089 }
6090
Douglas Gregor699ee522009-11-20 19:42:02 +00006091 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCallaa81e162009-12-01 22:10:20 +00006092
John McCallaa81e162009-12-01 22:10:20 +00006093 // If overload resolution picked a static member, build a
6094 // non-member call based on that function.
6095 if (Method->isStatic()) {
6096 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6097 Args, NumArgs, RParenLoc);
6098 }
6099
John McCall129e2df2009-11-30 22:42:35 +00006100 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00006101 }
6102
6103 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00006104 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00006105 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00006106 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006107 Method->getResultType().getNonReferenceType(),
6108 RParenLoc));
6109
Anders Carlssoneed3e692009-10-10 00:06:20 +00006110 // Check for a valid return type.
6111 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6112 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00006113 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00006114
Douglas Gregor88a35142008-12-22 05:46:06 +00006115 // Convert the object argument (for a non-static member function call).
John McCallaa81e162009-12-01 22:10:20 +00006116 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00006117 if (!Method->isStatic() &&
Douglas Gregor88a35142008-12-22 05:46:06 +00006118 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCallaa81e162009-12-01 22:10:20 +00006119 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006120 MemExpr->setBase(ObjectArg);
6121
6122 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00006123 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00006124 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006125 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00006126 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006127
Anders Carlssond406bf02009-08-16 01:56:34 +00006128 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00006129 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00006130
John McCallaa81e162009-12-01 22:10:20 +00006131 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00006132}
6133
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006134/// BuildCallToObjectOfClassType - Build a call to an object of class
6135/// type (C++ [over.call.object]), which can end up invoking an
6136/// overloaded function call operator (@c operator()) or performing a
6137/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006138Sema::ExprResult
6139Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00006140 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006141 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00006142 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006143 SourceLocation RParenLoc) {
6144 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00006145 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006146
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006147 // C++ [over.call.object]p1:
6148 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00006149 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006150 // candidate functions includes at least the function call
6151 // operators of T. The function call operators of T are obtained by
6152 // ordinary lookup of the name operator() in the context of
6153 // (E).operator().
6154 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00006155 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00006156
6157 if (RequireCompleteType(LParenLoc, Object->getType(),
6158 PartialDiagnostic(diag::err_incomplete_object_call)
6159 << Object->getSourceRange()))
6160 return true;
6161
John McCalla24dc2e2009-11-17 02:14:36 +00006162 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6163 LookupQualifiedName(R, Record->getDecl());
6164 R.suppressDiagnostics();
6165
Douglas Gregor593564b2009-11-15 07:48:03 +00006166 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00006167 Oper != OperEnd; ++Oper) {
John McCall86820f52010-01-26 01:37:31 +00006168 AddMethodCandidate(*Oper, Oper.getAccess(), Object->getType(),
6169 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006170 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00006171 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00006172
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006173 // C++ [over.call.object]p2:
6174 // In addition, for each conversion function declared in T of the
6175 // form
6176 //
6177 // operator conversion-type-id () cv-qualifier;
6178 //
6179 // where cv-qualifier is the same cv-qualification as, or a
6180 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00006181 // denotes the type "pointer to function of (P1,...,Pn) returning
6182 // R", or the type "reference to pointer to function of
6183 // (P1,...,Pn) returning R", or the type "reference to function
6184 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006185 // is also considered as a candidate function. Similarly,
6186 // surrogate call functions are added to the set of candidate
6187 // functions for each conversion function declared in an
6188 // accessible base class provided the function is not hidden
6189 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00006190 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00006191 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00006192 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006193 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00006194 NamedDecl *D = *I;
6195 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6196 if (isa<UsingShadowDecl>(D))
6197 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6198
Douglas Gregor4a27d702009-10-21 06:18:39 +00006199 // Skip over templated conversion functions; they aren't
6200 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00006201 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00006202 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006203
John McCall701c89e2009-12-03 04:06:58 +00006204 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00006205
Douglas Gregor4a27d702009-10-21 06:18:39 +00006206 // Strip the reference type (if any) and then the pointer type (if
6207 // any) to get down to what might be a function type.
6208 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6209 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6210 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006211
Douglas Gregor4a27d702009-10-21 06:18:39 +00006212 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall86820f52010-01-26 01:37:31 +00006213 AddSurrogateCandidate(Conv, I.getAccess(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00006214 Object->getType(), Args, NumArgs,
6215 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006216 }
Mike Stump1eb44332009-09-09 15:08:12 +00006217
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006218 // Perform overload resolution.
6219 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006220 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006221 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006222 // Overload resolution succeeded; we'll build the appropriate call
6223 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006224 break;
6225
6226 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00006227 if (CandidateSet.empty())
6228 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6229 << Object->getType() << /*call*/ 1
6230 << Object->getSourceRange();
6231 else
6232 Diag(Object->getSourceRange().getBegin(),
6233 diag::err_ovl_no_viable_object_call)
6234 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006235 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006236 break;
6237
6238 case OR_Ambiguous:
6239 Diag(Object->getSourceRange().getBegin(),
6240 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00006241 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006242 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006243 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006244
6245 case OR_Deleted:
6246 Diag(Object->getSourceRange().getBegin(),
6247 diag::err_ovl_deleted_object_call)
6248 << Best->Function->isDeleted()
6249 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006250 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006251 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006252 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006253
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006254 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006255 // We had an error; delete all of the subexpressions and return
6256 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006257 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006258 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00006259 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006260 return true;
6261 }
6262
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006263 if (Best->Function == 0) {
6264 // Since there is no function declaration, this is one of the
6265 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00006266 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006267 = cast<CXXConversionDecl>(
6268 Best->Conversions[0].UserDefined.ConversionFunction);
6269
John McCall233a6412010-01-28 07:38:46 +00006270 CheckMemberOperatorAccess(LParenLoc, Object, Conv, Best->getAccess());
John McCall41d89032010-01-28 01:54:34 +00006271
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006272 // We selected one of the surrogate functions that converts the
6273 // object parameter to a function pointer. Perform the conversion
6274 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006275
6276 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006277 // and then call it.
Eli Friedmanc8c771e2009-12-09 04:52:43 +00006278 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006279
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006280 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00006281 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6282 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006283 }
6284
John McCall233a6412010-01-28 07:38:46 +00006285 CheckMemberOperatorAccess(LParenLoc, Object,
6286 Best->Function, Best->getAccess());
John McCall41d89032010-01-28 01:54:34 +00006287
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006288 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6289 // that calls this method, using Object for the implicit object
6290 // parameter and passing along the remaining arguments.
6291 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00006292 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006293
6294 unsigned NumArgsInProto = Proto->getNumArgs();
6295 unsigned NumArgsToCheck = NumArgs;
6296
6297 // Build the full argument list for the method call (the
6298 // implicit object parameter is placed at the beginning of the
6299 // list).
6300 Expr **MethodArgs;
6301 if (NumArgs < NumArgsInProto) {
6302 NumArgsToCheck = NumArgsInProto;
6303 MethodArgs = new Expr*[NumArgsInProto + 1];
6304 } else {
6305 MethodArgs = new Expr*[NumArgs + 1];
6306 }
6307 MethodArgs[0] = Object;
6308 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6309 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00006310
6311 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00006312 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006313 UsualUnaryConversions(NewFn);
6314
6315 // Once we've built TheCall, all of the expressions are properly
6316 // owned.
6317 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00006318 ExprOwningPtr<CXXOperatorCallExpr>
6319 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00006320 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00006321 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006322 delete [] MethodArgs;
6323
Anders Carlsson07d68f12009-10-13 21:49:31 +00006324 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6325 Method))
6326 return true;
6327
Douglas Gregor518fda12009-01-13 05:10:00 +00006328 // We may have default arguments. If so, we need to allocate more
6329 // slots in the call for them.
6330 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00006331 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00006332 else if (NumArgs > NumArgsInProto)
6333 NumArgsToCheck = NumArgsInProto;
6334
Chris Lattner312531a2009-04-12 08:11:20 +00006335 bool IsError = false;
6336
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006337 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00006338 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006339 TheCall->setArg(0, Object);
6340
Chris Lattner312531a2009-04-12 08:11:20 +00006341
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006342 // Check the argument types.
6343 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006344 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00006345 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006346 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00006347
Douglas Gregor518fda12009-01-13 05:10:00 +00006348 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00006349
6350 OwningExprResult InputInit
6351 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6352 Method->getParamDecl(i)),
6353 SourceLocation(), Owned(Arg));
6354
6355 IsError |= InputInit.isInvalid();
6356 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00006357 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00006358 OwningExprResult DefArg
6359 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6360 if (DefArg.isInvalid()) {
6361 IsError = true;
6362 break;
6363 }
6364
6365 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00006366 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006367
6368 TheCall->setArg(i + 1, Arg);
6369 }
6370
6371 // If this is a variadic call, handle args passed through "...".
6372 if (Proto->isVariadic()) {
6373 // Promote the arguments (C99 6.5.2.2p7).
6374 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6375 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00006376 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006377 TheCall->setArg(i + 1, Arg);
6378 }
6379 }
6380
Chris Lattner312531a2009-04-12 08:11:20 +00006381 if (IsError) return true;
6382
Anders Carlssond406bf02009-08-16 01:56:34 +00006383 if (CheckFunctionCall(Method, TheCall.get()))
6384 return true;
6385
Anders Carlssona303f9e2009-08-16 03:53:54 +00006386 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006387}
6388
Douglas Gregor8ba10742008-11-20 16:27:02 +00006389/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00006390/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00006391/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006392Sema::OwningExprResult
6393Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6394 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00006395 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00006396
Douglas Gregor8ba10742008-11-20 16:27:02 +00006397 // C++ [over.ref]p1:
6398 //
6399 // [...] An expression x->m is interpreted as (x.operator->())->m
6400 // for a class object x of type T if T::operator->() exists and if
6401 // the operator is selected as the best match function by the
6402 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00006403 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
6404 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00006405 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006406
Eli Friedmanf43fb722009-11-18 01:28:03 +00006407 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
6408 PDiag(diag::err_typecheck_incomplete_tag)
6409 << Base->getSourceRange()))
6410 return ExprError();
6411
John McCalla24dc2e2009-11-17 02:14:36 +00006412 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6413 LookupQualifiedName(R, BaseRecord->getDecl());
6414 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00006415
6416 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00006417 Oper != OperEnd; ++Oper) {
6418 NamedDecl *D = *Oper;
6419 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6420 if (isa<UsingShadowDecl>(D))
6421 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6422
John McCall86820f52010-01-26 01:37:31 +00006423 AddMethodCandidate(cast<CXXMethodDecl>(D), Oper.getAccess(), ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00006424 Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00006425 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00006426 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00006427
6428 // Perform overload resolution.
6429 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006430 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00006431 case OR_Success:
6432 // Overload resolution succeeded; we'll build the call below.
6433 break;
6434
6435 case OR_No_Viable_Function:
6436 if (CandidateSet.empty())
6437 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006438 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006439 else
6440 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006441 << "operator->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006442 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006443 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006444
6445 case OR_Ambiguous:
6446 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00006447 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006448 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006449 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006450
6451 case OR_Deleted:
6452 Diag(OpLoc, diag::err_ovl_deleted_oper)
6453 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00006454 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006455 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006456 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006457 }
6458
6459 // Convert the object parameter.
6460 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00006461 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006462 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00006463
6464 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006465 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006466
6467 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006468 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6469 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00006470 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00006471
6472 QualType ResultTy = Method->getResultType().getNonReferenceType();
6473 ExprOwningPtr<CXXOperatorCallExpr>
6474 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6475 &Base, 1, ResultTy, OpLoc));
6476
6477 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6478 Method))
6479 return ExprError();
6480 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00006481}
6482
Douglas Gregor904eed32008-11-10 20:40:00 +00006483/// FixOverloadedFunctionReference - E is an expression that refers to
6484/// a C++ overloaded function (possibly with some parentheses and
6485/// perhaps a '&' around it). We have resolved the overloaded function
6486/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00006487/// refer (possibly indirectly) to Fn. Returns the new expr.
6488Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006489 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor699ee522009-11-20 19:42:02 +00006490 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6491 if (SubExpr == PE->getSubExpr())
6492 return PE->Retain();
6493
6494 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6495 }
6496
6497 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6498 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00006499 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00006500 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00006501 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00006502 if (SubExpr == ICE->getSubExpr())
6503 return ICE->Retain();
6504
6505 return new (Context) ImplicitCastExpr(ICE->getType(),
6506 ICE->getCastKind(),
6507 SubExpr,
6508 ICE->isLvalueCast());
6509 }
6510
6511 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006512 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00006513 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00006514 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6515 if (Method->isStatic()) {
6516 // Do nothing: static member functions aren't any different
6517 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00006518 } else {
John McCallf7a1a742009-11-24 19:00:30 +00006519 // Fix the sub expression, which really has to be an
6520 // UnresolvedLookupExpr holding an overloaded member function
6521 // or template.
John McCallba135432009-11-21 08:51:07 +00006522 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6523 if (SubExpr == UnOp->getSubExpr())
6524 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00006525
John McCallba135432009-11-21 08:51:07 +00006526 assert(isa<DeclRefExpr>(SubExpr)
6527 && "fixed to something other than a decl ref");
6528 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6529 && "fixed to a member ref with no nested name qualifier");
6530
6531 // We have taken the address of a pointer to member
6532 // function. Perform the computation here so that we get the
6533 // appropriate pointer to member type.
6534 QualType ClassType
6535 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6536 QualType MemPtrType
6537 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6538
6539 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6540 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00006541 }
6542 }
Douglas Gregor699ee522009-11-20 19:42:02 +00006543 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6544 if (SubExpr == UnOp->getSubExpr())
6545 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00006546
Douglas Gregor699ee522009-11-20 19:42:02 +00006547 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6548 Context.getPointerType(SubExpr->getType()),
6549 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00006550 }
John McCallba135432009-11-21 08:51:07 +00006551
6552 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00006553 // FIXME: avoid copy.
6554 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00006555 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00006556 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6557 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00006558 }
6559
John McCallba135432009-11-21 08:51:07 +00006560 return DeclRefExpr::Create(Context,
6561 ULE->getQualifier(),
6562 ULE->getQualifierRange(),
6563 Fn,
6564 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006565 Fn->getType(),
6566 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00006567 }
6568
John McCall129e2df2009-11-30 22:42:35 +00006569 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00006570 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00006571 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6572 if (MemExpr->hasExplicitTemplateArgs()) {
6573 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6574 TemplateArgs = &TemplateArgsBuffer;
6575 }
John McCalld5532b62009-11-23 01:53:49 +00006576
John McCallaa81e162009-12-01 22:10:20 +00006577 Expr *Base;
6578
6579 // If we're filling in
6580 if (MemExpr->isImplicitAccess()) {
6581 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6582 return DeclRefExpr::Create(Context,
6583 MemExpr->getQualifier(),
6584 MemExpr->getQualifierRange(),
6585 Fn,
6586 MemExpr->getMemberLoc(),
6587 Fn->getType(),
6588 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00006589 } else {
6590 SourceLocation Loc = MemExpr->getMemberLoc();
6591 if (MemExpr->getQualifier())
6592 Loc = MemExpr->getQualifierRange().getBegin();
6593 Base = new (Context) CXXThisExpr(Loc,
6594 MemExpr->getBaseType(),
6595 /*isImplicit=*/true);
6596 }
John McCallaa81e162009-12-01 22:10:20 +00006597 } else
6598 Base = MemExpr->getBase()->Retain();
6599
6600 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00006601 MemExpr->isArrow(),
6602 MemExpr->getQualifier(),
6603 MemExpr->getQualifierRange(),
6604 Fn,
John McCalld5532b62009-11-23 01:53:49 +00006605 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006606 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00006607 Fn->getType());
6608 }
6609
Douglas Gregor699ee522009-11-20 19:42:02 +00006610 assert(false && "Invalid reference to overloaded function");
6611 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00006612}
6613
Douglas Gregor20093b42009-12-09 23:02:17 +00006614Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6615 FunctionDecl *Fn) {
6616 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6617}
6618
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006619} // end namespace clang