blob: 86b1e37f10810483089b5f39bea01b0937d6d516 [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).
Sebastian Redl07779722008-10-31 14:43:28 +0000771 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000772 if (// We can promote any signed, promotable integer type to an int
773 (FromType->isSignedIntegerType() ||
774 // We can promote any unsigned integer type whose size is
775 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +0000776 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000777 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000778 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000779 }
780
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000781 return To->getKind() == BuiltinType::UInt;
782 }
783
784 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
785 // can be converted to an rvalue of the first of the following types
786 // that can represent all the values of its underlying type: int,
787 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +0000788
789 // We pre-calculate the promotion type for enum types.
790 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
791 if (ToType->isIntegerType())
792 return Context.hasSameUnqualifiedType(ToType,
793 FromEnumType->getDecl()->getPromotionType());
794
795 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000796 // Determine whether the type we're converting from is signed or
797 // unsigned.
798 bool FromIsSigned;
799 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +0000800
801 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
802 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000803
804 // The types we'll try to promote to, in the appropriate
805 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +0000806 QualType PromoteTypes[6] = {
807 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000808 Context.LongTy, Context.UnsignedLongTy ,
809 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000810 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000811 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000812 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
813 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000814 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000815 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
816 // We found the type that we can promote to. If this is the
817 // type we wanted, we have a promotion. Otherwise, no
818 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000819 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000820 }
821 }
822 }
823
824 // An rvalue for an integral bit-field (9.6) can be converted to an
825 // rvalue of type int if int can represent all the values of the
826 // bit-field; otherwise, it can be converted to unsigned int if
827 // unsigned int can represent all the values of the bit-field. If
828 // the bit-field is larger yet, no integral promotion applies to
829 // it. If the bit-field has an enumerated type, it is treated as any
830 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000831 // FIXME: We should delay checking of bit-fields until we actually perform the
832 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000833 using llvm::APSInt;
834 if (From)
835 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000836 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000837 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
838 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
839 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
840 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Douglas Gregor86f19402008-12-20 23:49:58 +0000842 // Are we promoting to an int from a bitfield that fits in an int?
843 if (BitWidth < ToSize ||
844 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
845 return To->getKind() == BuiltinType::Int;
846 }
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Douglas Gregor86f19402008-12-20 23:49:58 +0000848 // Are we promoting to an unsigned int from an unsigned bitfield
849 // that fits into an unsigned int?
850 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
851 return To->getKind() == BuiltinType::UInt;
852 }
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Douglas Gregor86f19402008-12-20 23:49:58 +0000854 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000855 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000856 }
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000858 // An rvalue of type bool can be converted to an rvalue of type int,
859 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000860 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000861 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000862 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000863
864 return false;
865}
866
867/// IsFloatingPointPromotion - Determines whether the conversion from
868/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
869/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000870bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000871 /// An rvalue of type float can be converted to an rvalue of type
872 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +0000873 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
874 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000875 if (FromBuiltin->getKind() == BuiltinType::Float &&
876 ToBuiltin->getKind() == BuiltinType::Double)
877 return true;
878
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000879 // C99 6.3.1.5p1:
880 // When a float is promoted to double or long double, or a
881 // double is promoted to long double [...].
882 if (!getLangOptions().CPlusPlus &&
883 (FromBuiltin->getKind() == BuiltinType::Float ||
884 FromBuiltin->getKind() == BuiltinType::Double) &&
885 (ToBuiltin->getKind() == BuiltinType::LongDouble))
886 return true;
887 }
888
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000889 return false;
890}
891
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000892/// \brief Determine if a conversion is a complex promotion.
893///
894/// A complex promotion is defined as a complex -> complex conversion
895/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000896/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000897bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000898 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000899 if (!FromComplex)
900 return false;
901
John McCall183700f2009-09-21 23:43:11 +0000902 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000903 if (!ToComplex)
904 return false;
905
906 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000907 ToComplex->getElementType()) ||
908 IsIntegralPromotion(0, FromComplex->getElementType(),
909 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000910}
911
Douglas Gregorcb7de522008-11-26 23:31:11 +0000912/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
913/// the pointer type FromPtr to a pointer to type ToPointee, with the
914/// same type qualifiers as FromPtr has on its pointee type. ToType,
915/// if non-empty, will be a pointer to ToType that may or may not have
916/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000917static QualType
918BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000919 QualType ToPointee, QualType ToType,
920 ASTContext &Context) {
921 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
922 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +0000923 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000924
925 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000926 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +0000927 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +0000928 if (!ToType.isNull())
Douglas Gregorcb7de522008-11-26 23:31:11 +0000929 return ToType;
930
931 // Build a pointer to ToPointee. It has the right qualifiers
932 // already.
933 return Context.getPointerType(ToPointee);
934 }
935
936 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +0000937 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +0000938 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
939 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +0000940}
941
Fariborz Jahanianadcfab12009-12-16 23:13:33 +0000942/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
943/// the FromType, which is an objective-c pointer, to ToType, which may or may
944/// not have the right set of qualifiers.
945static QualType
946BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
947 QualType ToType,
948 ASTContext &Context) {
949 QualType CanonFromType = Context.getCanonicalType(FromType);
950 QualType CanonToType = Context.getCanonicalType(ToType);
951 Qualifiers Quals = CanonFromType.getQualifiers();
952
953 // Exact qualifier match -> return the pointer type we're converting to.
954 if (CanonToType.getLocalQualifiers() == Quals)
955 return ToType;
956
957 // Just build a canonical type that has the right qualifiers.
958 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
959}
960
Mike Stump1eb44332009-09-09 15:08:12 +0000961static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000962 bool InOverloadResolution,
963 ASTContext &Context) {
964 // Handle value-dependent integral null pointer constants correctly.
965 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
966 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
967 Expr->getType()->isIntegralType())
968 return !InOverloadResolution;
969
Douglas Gregorce940492009-09-25 04:25:58 +0000970 return Expr->isNullPointerConstant(Context,
971 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
972 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000973}
Mike Stump1eb44332009-09-09 15:08:12 +0000974
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000975/// IsPointerConversion - Determines whether the conversion of the
976/// expression From, which has the (possibly adjusted) type FromType,
977/// can be converted to the type ToType via a pointer conversion (C++
978/// 4.10). If so, returns true and places the converted type (that
979/// might differ from ToType in its cv-qualifiers at some level) into
980/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000981///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000982/// This routine also supports conversions to and from block pointers
983/// and conversions with Objective-C's 'id', 'id<protocols...>', and
984/// pointers to interfaces. FIXME: Once we've determined the
985/// appropriate overloading rules for Objective-C, we may want to
986/// split the Objective-C checks into a different routine; however,
987/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000988/// conversions, so for now they live here. IncompatibleObjC will be
989/// set if the conversion is an allowed Objective-C conversion that
990/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000991bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000992 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +0000993 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +0000994 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +0000995 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000996 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
997 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000998
Mike Stump1eb44332009-09-09 15:08:12 +0000999 // Conversion from a null pointer constant to any Objective-C pointer type.
1000 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001001 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001002 ConvertedType = ToType;
1003 return true;
1004 }
1005
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001006 // Blocks: Block pointers can be converted to void*.
1007 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001008 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001009 ConvertedType = ToType;
1010 return true;
1011 }
1012 // Blocks: A null pointer constant can be converted to a block
1013 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001014 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001015 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001016 ConvertedType = ToType;
1017 return true;
1018 }
1019
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001020 // If the left-hand-side is nullptr_t, the right side can be a null
1021 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001022 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001023 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001024 ConvertedType = ToType;
1025 return true;
1026 }
1027
Ted Kremenek6217b802009-07-29 21:53:49 +00001028 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001029 if (!ToTypePtr)
1030 return false;
1031
1032 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001033 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001034 ConvertedType = ToType;
1035 return true;
1036 }
Sebastian Redl07779722008-10-31 14:43:28 +00001037
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001038 // Beyond this point, both types need to be pointers
1039 // , including objective-c pointers.
1040 QualType ToPointeeType = ToTypePtr->getPointeeType();
1041 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1042 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1043 ToType, Context);
1044 return true;
1045
1046 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001047 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001048 if (!FromTypePtr)
1049 return false;
1050
1051 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001052
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001053 // An rvalue of type "pointer to cv T," where T is an object type,
1054 // can be converted to an rvalue of type "pointer to cv void" (C++
1055 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +00001056 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001057 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001058 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001059 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001060 return true;
1061 }
1062
Douglas Gregorf9201e02009-02-11 23:02:49 +00001063 // When we're overloading in C, we allow a special kind of pointer
1064 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001065 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001066 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001067 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001068 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001069 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001070 return true;
1071 }
1072
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001073 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001074 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001075 // An rvalue of type "pointer to cv D," where D is a class type,
1076 // can be converted to an rvalue of type "pointer to cv B," where
1077 // B is a base class (clause 10) of D. If B is an inaccessible
1078 // (clause 11) or ambiguous (10.2) base class of D, a program that
1079 // necessitates this conversion is ill-formed. The result of the
1080 // conversion is a pointer to the base class sub-object of the
1081 // derived class object. The null pointer value is converted to
1082 // the null pointer value of the destination type.
1083 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001084 // Note that we do not check for ambiguity or inaccessibility
1085 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001086 if (getLangOptions().CPlusPlus &&
1087 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001088 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001089 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001090 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001091 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001092 ToType, Context);
1093 return true;
1094 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001095
Douglas Gregorc7887512008-12-19 19:13:09 +00001096 return false;
1097}
1098
1099/// isObjCPointerConversion - Determines whether this is an
1100/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1101/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001102bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001103 QualType& ConvertedType,
1104 bool &IncompatibleObjC) {
1105 if (!getLangOptions().ObjC1)
1106 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001107
Steve Naroff14108da2009-07-10 23:34:53 +00001108 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001109 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001110 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001111 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001112
Steve Naroff14108da2009-07-10 23:34:53 +00001113 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001114 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001115 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001116 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001117 ConvertedType = ToType;
1118 return true;
1119 }
1120 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001121 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001122 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001123 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001124 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001125 ConvertedType = ToType;
1126 return true;
1127 }
1128 // Objective C++: We're able to convert from a pointer to an
1129 // interface to a pointer to a different interface.
1130 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1131 ConvertedType = ToType;
1132 return true;
1133 }
1134
1135 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1136 // Okay: this is some kind of implicit downcast of Objective-C
1137 // interfaces, which is permitted. However, we're going to
1138 // complain about it.
1139 IncompatibleObjC = true;
1140 ConvertedType = FromType;
1141 return true;
1142 }
Mike Stump1eb44332009-09-09 15:08:12 +00001143 }
Steve Naroff14108da2009-07-10 23:34:53 +00001144 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001145 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001146 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001147 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001148 else if (const BlockPointerType *ToBlockPtr =
1149 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001150 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001151 // to a block pointer type.
1152 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1153 ConvertedType = ToType;
1154 return true;
1155 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001156 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001157 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001158 else if (FromType->getAs<BlockPointerType>() &&
1159 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1160 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001161 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001162 ConvertedType = ToType;
1163 return true;
1164 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001165 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001166 return false;
1167
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001168 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001169 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001170 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001171 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001172 FromPointeeType = FromBlockPtr->getPointeeType();
1173 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001174 return false;
1175
Douglas Gregorc7887512008-12-19 19:13:09 +00001176 // If we have pointers to pointers, recursively check whether this
1177 // is an Objective-C conversion.
1178 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1179 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1180 IncompatibleObjC)) {
1181 // We always complain about this conversion.
1182 IncompatibleObjC = true;
1183 ConvertedType = ToType;
1184 return true;
1185 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001186 // Allow conversion of pointee being objective-c pointer to another one;
1187 // as in I* to id.
1188 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1189 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1190 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1191 IncompatibleObjC)) {
1192 ConvertedType = ToType;
1193 return true;
1194 }
1195
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001196 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001197 // differences in the argument and result types are in Objective-C
1198 // pointer conversions. If so, we permit the conversion (but
1199 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001200 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001201 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001202 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001203 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001204 if (FromFunctionType && ToFunctionType) {
1205 // If the function types are exactly the same, this isn't an
1206 // Objective-C pointer conversion.
1207 if (Context.getCanonicalType(FromPointeeType)
1208 == Context.getCanonicalType(ToPointeeType))
1209 return false;
1210
1211 // Perform the quick checks that will tell us whether these
1212 // function types are obviously different.
1213 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1214 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1215 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1216 return false;
1217
1218 bool HasObjCConversion = false;
1219 if (Context.getCanonicalType(FromFunctionType->getResultType())
1220 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1221 // Okay, the types match exactly. Nothing to do.
1222 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1223 ToFunctionType->getResultType(),
1224 ConvertedType, IncompatibleObjC)) {
1225 // Okay, we have an Objective-C pointer conversion.
1226 HasObjCConversion = true;
1227 } else {
1228 // Function types are too different. Abort.
1229 return false;
1230 }
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Douglas Gregorc7887512008-12-19 19:13:09 +00001232 // Check argument types.
1233 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1234 ArgIdx != NumArgs; ++ArgIdx) {
1235 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1236 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1237 if (Context.getCanonicalType(FromArgType)
1238 == Context.getCanonicalType(ToArgType)) {
1239 // Okay, the types match exactly. Nothing to do.
1240 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1241 ConvertedType, IncompatibleObjC)) {
1242 // Okay, we have an Objective-C pointer conversion.
1243 HasObjCConversion = true;
1244 } else {
1245 // Argument types are too different. Abort.
1246 return false;
1247 }
1248 }
1249
1250 if (HasObjCConversion) {
1251 // We had an Objective-C conversion. Allow this pointer
1252 // conversion, but complain about it.
1253 ConvertedType = ToType;
1254 IncompatibleObjC = true;
1255 return true;
1256 }
1257 }
1258
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001259 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001260}
1261
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001262/// CheckPointerConversion - Check the pointer conversion from the
1263/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001264/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001265/// conversions for which IsPointerConversion has already returned
1266/// true. It returns true and produces a diagnostic if there was an
1267/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001268bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001269 CastExpr::CastKind &Kind,
1270 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001271 QualType FromType = From->getType();
1272
Ted Kremenek6217b802009-07-29 21:53:49 +00001273 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1274 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001275 QualType FromPointeeType = FromPtrType->getPointeeType(),
1276 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001277
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001278 if (FromPointeeType->isRecordType() &&
1279 ToPointeeType->isRecordType()) {
1280 // We must have a derived-to-base conversion. Check an
1281 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001282 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1283 From->getExprLoc(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001284 From->getSourceRange(),
1285 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001286 return true;
1287
1288 // The conversion was successful.
1289 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001290 }
1291 }
Mike Stump1eb44332009-09-09 15:08:12 +00001292 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001293 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001294 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001295 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001296 // Objective-C++ conversions are always okay.
1297 // FIXME: We should have a different class of conversions for the
1298 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001299 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001300 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001301
Steve Naroff14108da2009-07-10 23:34:53 +00001302 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001303 return false;
1304}
1305
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001306/// IsMemberPointerConversion - Determines whether the conversion of the
1307/// expression From, which has the (possibly adjusted) type FromType, can be
1308/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1309/// If so, returns true and places the converted type (that might differ from
1310/// ToType in its cv-qualifiers at some level) into ConvertedType.
1311bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001312 QualType ToType,
1313 bool InOverloadResolution,
1314 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001315 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001316 if (!ToTypePtr)
1317 return false;
1318
1319 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001320 if (From->isNullPointerConstant(Context,
1321 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1322 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001323 ConvertedType = ToType;
1324 return true;
1325 }
1326
1327 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001328 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001329 if (!FromTypePtr)
1330 return false;
1331
1332 // A pointer to member of B can be converted to a pointer to member of D,
1333 // where D is derived from B (C++ 4.11p2).
1334 QualType FromClass(FromTypePtr->getClass(), 0);
1335 QualType ToClass(ToTypePtr->getClass(), 0);
1336 // FIXME: What happens when these are dependent? Is this function even called?
1337
1338 if (IsDerivedFrom(ToClass, FromClass)) {
1339 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1340 ToClass.getTypePtr());
1341 return true;
1342 }
1343
1344 return false;
1345}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001346
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001347/// CheckMemberPointerConversion - Check the member pointer conversion from the
1348/// expression From to the type ToType. This routine checks for ambiguous or
1349/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1350/// for which IsMemberPointerConversion has already returned true. It returns
1351/// true and produces a diagnostic if there was an error, or returns false
1352/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001353bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001354 CastExpr::CastKind &Kind,
1355 bool IgnoreBaseAccess) {
1356 (void)IgnoreBaseAccess;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001357 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001358 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001359 if (!FromPtrType) {
1360 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001361 assert(From->isNullPointerConstant(Context,
1362 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001363 "Expr must be null pointer constant!");
1364 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001365 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001366 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001367
Ted Kremenek6217b802009-07-29 21:53:49 +00001368 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001369 assert(ToPtrType && "No member pointer cast has a target type "
1370 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001371
Sebastian Redl21593ac2009-01-28 18:33:18 +00001372 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1373 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001374
Sebastian Redl21593ac2009-01-28 18:33:18 +00001375 // FIXME: What about dependent types?
1376 assert(FromClass->isRecordType() && "Pointer into non-class.");
1377 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001378
Douglas Gregora8f32e02009-10-06 17:59:45 +00001379 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1380 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001381 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1382 assert(DerivationOkay &&
1383 "Should not have been called if derivation isn't OK.");
1384 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001385
Sebastian Redl21593ac2009-01-28 18:33:18 +00001386 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1387 getUnqualifiedType())) {
1388 // Derivation is ambiguous. Redo the check to find the exact paths.
1389 Paths.clear();
1390 Paths.setRecordingPaths(true);
1391 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1392 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1393 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001394
Sebastian Redl21593ac2009-01-28 18:33:18 +00001395 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1396 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1397 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1398 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001399 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001400
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001401 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001402 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1403 << FromClass << ToClass << QualType(VBase, 0)
1404 << From->getSourceRange();
1405 return true;
1406 }
1407
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001408 // Must be a base to derived member conversion.
1409 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001410 return false;
1411}
1412
Douglas Gregor98cd5992008-10-21 23:43:52 +00001413/// IsQualificationConversion - Determines whether the conversion from
1414/// an rvalue of type FromType to ToType is a qualification conversion
1415/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001416bool
1417Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001418 FromType = Context.getCanonicalType(FromType);
1419 ToType = Context.getCanonicalType(ToType);
1420
1421 // If FromType and ToType are the same type, this is not a
1422 // qualification conversion.
1423 if (FromType == ToType)
1424 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001425
Douglas Gregor98cd5992008-10-21 23:43:52 +00001426 // (C++ 4.4p4):
1427 // A conversion can add cv-qualifiers at levels other than the first
1428 // in multi-level pointers, subject to the following rules: [...]
1429 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001430 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001431 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001432 // Within each iteration of the loop, we check the qualifiers to
1433 // determine if this still looks like a qualification
1434 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001435 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001436 // until there are no more pointers or pointers-to-members left to
1437 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001438 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001439
1440 // -- for every j > 0, if const is in cv 1,j then const is in cv
1441 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001442 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001443 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Douglas Gregor98cd5992008-10-21 23:43:52 +00001445 // -- if the cv 1,j and cv 2,j are different, then const is in
1446 // every cv for 0 < k < j.
1447 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001448 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001449 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Douglas Gregor98cd5992008-10-21 23:43:52 +00001451 // Keep track of whether all prior cv-qualifiers in the "to" type
1452 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001453 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001454 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001455 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001456
1457 // We are left with FromType and ToType being the pointee types
1458 // after unwrapping the original FromType and ToType the same number
1459 // of types. If we unwrapped any pointers, and if FromType and
1460 // ToType have the same unqualified type (since we checked
1461 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001462 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001463}
1464
Douglas Gregor734d9862009-01-30 23:27:23 +00001465/// Determines whether there is a user-defined conversion sequence
1466/// (C++ [over.ics.user]) that converts expression From to the type
1467/// ToType. If such a conversion exists, User will contain the
1468/// user-defined conversion sequence that performs such a conversion
1469/// and this routine will return true. Otherwise, this routine returns
1470/// false and User is unspecified.
1471///
1472/// \param AllowConversionFunctions true if the conversion should
1473/// consider conversion functions at all. If false, only constructors
1474/// will be considered.
1475///
1476/// \param AllowExplicit true if the conversion should consider C++0x
1477/// "explicit" conversion functions as well as non-explicit conversion
1478/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001479///
1480/// \param ForceRValue true if the expression should be treated as an rvalue
1481/// for overload resolution.
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001482/// \param UserCast true if looking for user defined conversion for a static
1483/// cast.
Douglas Gregor20093b42009-12-09 23:02:17 +00001484OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1485 UserDefinedConversionSequence& User,
1486 OverloadCandidateSet& CandidateSet,
1487 bool AllowConversionFunctions,
1488 bool AllowExplicit,
1489 bool ForceRValue,
1490 bool UserCast) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001491 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001492 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1493 // We're not going to find any constructors.
1494 } else if (CXXRecordDecl *ToRecordDecl
1495 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001496 // C++ [over.match.ctor]p1:
1497 // When objects of class type are direct-initialized (8.5), or
1498 // copy-initialized from an expression of the same or a
1499 // derived class type (8.5), overload resolution selects the
1500 // constructor. [...] For copy-initialization, the candidate
1501 // functions are all the converting constructors (12.3.1) of
1502 // that class. The argument list is the expression-list within
1503 // the parentheses of the initializer.
Douglas Gregor79b680e2009-11-13 18:44:21 +00001504 bool SuppressUserConversions = !UserCast;
1505 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1506 IsDerivedFrom(From->getType(), ToType)) {
1507 SuppressUserConversions = false;
1508 AllowConversionFunctions = false;
1509 }
1510
Mike Stump1eb44332009-09-09 15:08:12 +00001511 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001512 = Context.DeclarationNames.getCXXConstructorName(
1513 Context.getCanonicalType(ToType).getUnqualifiedType());
1514 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001515 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001516 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001517 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00001518 // Find the constructor (which may be a template).
1519 CXXConstructorDecl *Constructor = 0;
1520 FunctionTemplateDecl *ConstructorTmpl
1521 = dyn_cast<FunctionTemplateDecl>(*Con);
1522 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001523 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001524 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1525 else
1526 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001527
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001528 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001529 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001530 if (ConstructorTmpl)
John McCall86820f52010-01-26 01:37:31 +00001531 AddTemplateOverloadCandidate(ConstructorTmpl,
1532 ConstructorTmpl->getAccess(),
1533 /*ExplicitArgs*/ 0,
John McCalld5532b62009-11-23 01:53:49 +00001534 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001535 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001536 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001537 // Allow one user-defined conversion when user specifies a
1538 // From->ToType conversion via an static cast (c-style, etc).
John McCall86820f52010-01-26 01:37:31 +00001539 AddOverloadCandidate(Constructor, Constructor->getAccess(),
1540 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001541 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001542 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001543 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001544 }
1545 }
1546
Douglas Gregor734d9862009-01-30 23:27:23 +00001547 if (!AllowConversionFunctions) {
1548 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001549 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1550 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001551 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001552 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001553 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001554 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001555 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001556 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1557 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00001558 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001559 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001560 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001561 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00001562 NamedDecl *D = *I;
1563 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1564 if (isa<UsingShadowDecl>(D))
1565 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1566
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001567 CXXConversionDecl *Conv;
1568 FunctionTemplateDecl *ConvTemplate;
John McCallba135432009-11-21 08:51:07 +00001569 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001570 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1571 else
John McCallba135432009-11-21 08:51:07 +00001572 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001573
1574 if (AllowExplicit || !Conv->isExplicit()) {
1575 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00001576 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
1577 ActingContext, From, ToType,
1578 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001579 else
John McCall86820f52010-01-26 01:37:31 +00001580 AddConversionCandidate(Conv, I.getAccess(), ActingContext,
1581 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001582 }
1583 }
1584 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001585 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001586
1587 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001588 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001589 case OR_Success:
1590 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001591 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001592 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1593 // C++ [over.ics.user]p1:
1594 // If the user-defined conversion is specified by a
1595 // constructor (12.3.1), the initial standard conversion
1596 // sequence converts the source type to the type required by
1597 // the argument of the constructor.
1598 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001599 QualType ThisType = Constructor->getThisType(Context);
John McCall1d318332010-01-12 00:44:57 +00001600 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001601 User.EllipsisConversion = true;
1602 else {
1603 User.Before = Best->Conversions[0].Standard;
1604 User.EllipsisConversion = false;
1605 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001606 User.ConversionFunction = Constructor;
1607 User.After.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00001608 User.After.setFromType(
1609 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregorad323a82010-01-27 03:51:04 +00001610 User.After.setAllToTypes(ToType);
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001611 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001612 } else if (CXXConversionDecl *Conversion
1613 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1614 // C++ [over.ics.user]p1:
1615 //
1616 // [...] If the user-defined conversion is specified by a
1617 // conversion function (12.3.2), the initial standard
1618 // conversion sequence converts the source type to the
1619 // implicit object parameter of the conversion function.
1620 User.Before = Best->Conversions[0].Standard;
1621 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001622 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001623
1624 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001625 // The second standard conversion sequence converts the
1626 // result of the user-defined conversion to the target type
1627 // for the sequence. Since an implicit conversion sequence
1628 // is an initialization, the special rules for
1629 // initialization by user-defined conversion apply when
1630 // selecting the best user-defined conversion for a
1631 // user-defined conversion sequence (see 13.3.3 and
1632 // 13.3.3.1).
1633 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001634 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001635 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001636 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001637 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001638 }
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Douglas Gregor60d62c22008-10-31 16:23:19 +00001640 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001641 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001642 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001643 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001644 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001645
1646 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001647 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001648 }
1649
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001650 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001651}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001652
1653bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001654Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001655 ImplicitConversionSequence ICS;
1656 OverloadCandidateSet CandidateSet;
1657 OverloadingResult OvResult =
1658 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1659 CandidateSet, true, false, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001660 if (OvResult == OR_Ambiguous)
1661 Diag(From->getSourceRange().getBegin(),
1662 diag::err_typecheck_ambiguous_condition)
1663 << From->getType() << ToType << From->getSourceRange();
1664 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1665 Diag(From->getSourceRange().getBegin(),
1666 diag::err_typecheck_nonviable_condition)
1667 << From->getType() << ToType << From->getSourceRange();
1668 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001669 return false;
John McCallcbce6062010-01-12 07:18:19 +00001670 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001671 return true;
1672}
Douglas Gregor60d62c22008-10-31 16:23:19 +00001673
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001674/// CompareImplicitConversionSequences - Compare two implicit
1675/// conversion sequences to determine whether one is better than the
1676/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001677ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001678Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1679 const ImplicitConversionSequence& ICS2)
1680{
1681 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1682 // conversion sequences (as defined in 13.3.3.1)
1683 // -- a standard conversion sequence (13.3.3.1.1) is a better
1684 // conversion sequence than a user-defined conversion sequence or
1685 // an ellipsis conversion sequence, and
1686 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1687 // conversion sequence than an ellipsis conversion sequence
1688 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001689 //
John McCall1d318332010-01-12 00:44:57 +00001690 // C++0x [over.best.ics]p10:
1691 // For the purpose of ranking implicit conversion sequences as
1692 // described in 13.3.3.2, the ambiguous conversion sequence is
1693 // treated as a user-defined sequence that is indistinguishable
1694 // from any other user-defined conversion sequence.
1695 if (ICS1.getKind() < ICS2.getKind()) {
1696 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1697 return ImplicitConversionSequence::Better;
1698 } else if (ICS2.getKind() < ICS1.getKind()) {
1699 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1700 return ImplicitConversionSequence::Worse;
1701 }
1702
1703 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1704 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001705
1706 // Two implicit conversion sequences of the same form are
1707 // indistinguishable conversion sequences unless one of the
1708 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00001709 if (ICS1.isStandard())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001710 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00001711 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001712 // User-defined conversion sequence U1 is a better conversion
1713 // sequence than another user-defined conversion sequence U2 if
1714 // they contain the same user-defined conversion function or
1715 // constructor and if the second standard conversion sequence of
1716 // U1 is better than the second standard conversion sequence of
1717 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001718 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001719 ICS2.UserDefined.ConversionFunction)
1720 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1721 ICS2.UserDefined.After);
1722 }
1723
1724 return ImplicitConversionSequence::Indistinguishable;
1725}
1726
Douglas Gregorad323a82010-01-27 03:51:04 +00001727// Per 13.3.3.2p3, compare the given standard conversion sequences to
1728// determine if one is a proper subset of the other.
1729static ImplicitConversionSequence::CompareKind
1730compareStandardConversionSubsets(ASTContext &Context,
1731 const StandardConversionSequence& SCS1,
1732 const StandardConversionSequence& SCS2) {
1733 ImplicitConversionSequence::CompareKind Result
1734 = ImplicitConversionSequence::Indistinguishable;
1735
1736 if (SCS1.Second != SCS2.Second) {
1737 if (SCS1.Second == ICK_Identity)
1738 Result = ImplicitConversionSequence::Better;
1739 else if (SCS2.Second == ICK_Identity)
1740 Result = ImplicitConversionSequence::Worse;
1741 else
1742 return ImplicitConversionSequence::Indistinguishable;
1743 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1744 return ImplicitConversionSequence::Indistinguishable;
1745
1746 if (SCS1.Third == SCS2.Third) {
1747 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1748 : ImplicitConversionSequence::Indistinguishable;
1749 }
1750
1751 if (SCS1.Third == ICK_Identity)
1752 return Result == ImplicitConversionSequence::Worse
1753 ? ImplicitConversionSequence::Indistinguishable
1754 : ImplicitConversionSequence::Better;
1755
1756 if (SCS2.Third == ICK_Identity)
1757 return Result == ImplicitConversionSequence::Better
1758 ? ImplicitConversionSequence::Indistinguishable
1759 : ImplicitConversionSequence::Worse;
1760
1761 return ImplicitConversionSequence::Indistinguishable;
1762}
1763
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001764/// CompareStandardConversionSequences - Compare two standard
1765/// conversion sequences to determine whether one is better than the
1766/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001767ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001768Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1769 const StandardConversionSequence& SCS2)
1770{
1771 // Standard conversion sequence S1 is a better conversion sequence
1772 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1773
1774 // -- S1 is a proper subsequence of S2 (comparing the conversion
1775 // sequences in the canonical form defined by 13.3.3.1.1,
1776 // excluding any Lvalue Transformation; the identity conversion
1777 // sequence is considered to be a subsequence of any
1778 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00001779 if (ImplicitConversionSequence::CompareKind CK
1780 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1781 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001782
1783 // -- the rank of S1 is better than the rank of S2 (by the rules
1784 // defined below), or, if not that,
1785 ImplicitConversionRank Rank1 = SCS1.getRank();
1786 ImplicitConversionRank Rank2 = SCS2.getRank();
1787 if (Rank1 < Rank2)
1788 return ImplicitConversionSequence::Better;
1789 else if (Rank2 < Rank1)
1790 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001791
Douglas Gregor57373262008-10-22 14:17:15 +00001792 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1793 // are indistinguishable unless one of the following rules
1794 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Douglas Gregor57373262008-10-22 14:17:15 +00001796 // A conversion that is not a conversion of a pointer, or
1797 // pointer to member, to bool is better than another conversion
1798 // that is such a conversion.
1799 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1800 return SCS2.isPointerConversionToBool()
1801 ? ImplicitConversionSequence::Better
1802 : ImplicitConversionSequence::Worse;
1803
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001804 // C++ [over.ics.rank]p4b2:
1805 //
1806 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001807 // conversion of B* to A* is better than conversion of B* to
1808 // void*, and conversion of A* to void* is better than conversion
1809 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001810 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001811 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001812 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001813 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001814 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1815 // Exactly one of the conversion sequences is a conversion to
1816 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001817 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1818 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001819 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1820 // Neither conversion sequence converts to a void pointer; compare
1821 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001822 if (ImplicitConversionSequence::CompareKind DerivedCK
1823 = CompareDerivedToBaseConversions(SCS1, SCS2))
1824 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001825 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1826 // Both conversion sequences are conversions to void
1827 // pointers. Compare the source types to determine if there's an
1828 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00001829 QualType FromType1 = SCS1.getFromType();
1830 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001831
1832 // Adjust the types we're converting from via the array-to-pointer
1833 // conversion, if we need to.
1834 if (SCS1.First == ICK_Array_To_Pointer)
1835 FromType1 = Context.getArrayDecayedType(FromType1);
1836 if (SCS2.First == ICK_Array_To_Pointer)
1837 FromType2 = Context.getArrayDecayedType(FromType2);
1838
Douglas Gregor01919692009-12-13 21:37:05 +00001839 QualType FromPointee1
1840 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1841 QualType FromPointee2
1842 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001843
Douglas Gregor01919692009-12-13 21:37:05 +00001844 if (IsDerivedFrom(FromPointee2, FromPointee1))
1845 return ImplicitConversionSequence::Better;
1846 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1847 return ImplicitConversionSequence::Worse;
1848
1849 // Objective-C++: If one interface is more specific than the
1850 // other, it is the better one.
1851 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1852 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1853 if (FromIface1 && FromIface1) {
1854 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1855 return ImplicitConversionSequence::Better;
1856 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1857 return ImplicitConversionSequence::Worse;
1858 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001859 }
Douglas Gregor57373262008-10-22 14:17:15 +00001860
1861 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1862 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001863 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001864 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001865 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001866
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001867 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001868 // C++0x [over.ics.rank]p3b4:
1869 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1870 // implicit object parameter of a non-static member function declared
1871 // without a ref-qualifier, and S1 binds an rvalue reference to an
1872 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001873 // FIXME: We don't know if we're dealing with the implicit object parameter,
1874 // or if the member function in this case has a ref qualifier.
1875 // (Of course, we don't have ref qualifiers yet.)
1876 if (SCS1.RRefBinding != SCS2.RRefBinding)
1877 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1878 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001879
1880 // C++ [over.ics.rank]p3b4:
1881 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1882 // which the references refer are the same type except for
1883 // top-level cv-qualifiers, and the type to which the reference
1884 // initialized by S2 refers is more cv-qualified than the type
1885 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00001886 QualType T1 = SCS1.getToType(2);
1887 QualType T2 = SCS2.getToType(2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001888 T1 = Context.getCanonicalType(T1);
1889 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001890 Qualifiers T1Quals, T2Quals;
1891 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1892 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1893 if (UnqualT1 == UnqualT2) {
1894 // If the type is an array type, promote the element qualifiers to the type
1895 // for comparison.
1896 if (isa<ArrayType>(T1) && T1Quals)
1897 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1898 if (isa<ArrayType>(T2) && T2Quals)
1899 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001900 if (T2.isMoreQualifiedThan(T1))
1901 return ImplicitConversionSequence::Better;
1902 else if (T1.isMoreQualifiedThan(T2))
1903 return ImplicitConversionSequence::Worse;
1904 }
1905 }
Douglas Gregor57373262008-10-22 14:17:15 +00001906
1907 return ImplicitConversionSequence::Indistinguishable;
1908}
1909
1910/// CompareQualificationConversions - Compares two standard conversion
1911/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001912/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1913ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001914Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001915 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001916 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001917 // -- S1 and S2 differ only in their qualification conversion and
1918 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1919 // cv-qualification signature of type T1 is a proper subset of
1920 // the cv-qualification signature of type T2, and S1 is not the
1921 // deprecated string literal array-to-pointer conversion (4.2).
1922 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1923 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1924 return ImplicitConversionSequence::Indistinguishable;
1925
1926 // FIXME: the example in the standard doesn't use a qualification
1927 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00001928 QualType T1 = SCS1.getToType(2);
1929 QualType T2 = SCS2.getToType(2);
Douglas Gregor57373262008-10-22 14:17:15 +00001930 T1 = Context.getCanonicalType(T1);
1931 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001932 Qualifiers T1Quals, T2Quals;
1933 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1934 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00001935
1936 // If the types are the same, we won't learn anything by unwrapped
1937 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00001938 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00001939 return ImplicitConversionSequence::Indistinguishable;
1940
Chandler Carruth28e318c2009-12-29 07:16:59 +00001941 // If the type is an array type, promote the element qualifiers to the type
1942 // for comparison.
1943 if (isa<ArrayType>(T1) && T1Quals)
1944 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1945 if (isa<ArrayType>(T2) && T2Quals)
1946 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1947
Mike Stump1eb44332009-09-09 15:08:12 +00001948 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001949 = ImplicitConversionSequence::Indistinguishable;
1950 while (UnwrapSimilarPointerTypes(T1, T2)) {
1951 // Within each iteration of the loop, we check the qualifiers to
1952 // determine if this still looks like a qualification
1953 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001954 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001955 // until there are no more pointers or pointers-to-members left
1956 // to unwrap. This essentially mimics what
1957 // IsQualificationConversion does, but here we're checking for a
1958 // strict subset of qualifiers.
1959 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1960 // The qualifiers are the same, so this doesn't tell us anything
1961 // about how the sequences rank.
1962 ;
1963 else if (T2.isMoreQualifiedThan(T1)) {
1964 // T1 has fewer qualifiers, so it could be the better sequence.
1965 if (Result == ImplicitConversionSequence::Worse)
1966 // Neither has qualifiers that are a subset of the other's
1967 // qualifiers.
1968 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Douglas Gregor57373262008-10-22 14:17:15 +00001970 Result = ImplicitConversionSequence::Better;
1971 } else if (T1.isMoreQualifiedThan(T2)) {
1972 // T2 has fewer qualifiers, so it could be the better sequence.
1973 if (Result == ImplicitConversionSequence::Better)
1974 // Neither has qualifiers that are a subset of the other's
1975 // qualifiers.
1976 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Douglas Gregor57373262008-10-22 14:17:15 +00001978 Result = ImplicitConversionSequence::Worse;
1979 } else {
1980 // Qualifiers are disjoint.
1981 return ImplicitConversionSequence::Indistinguishable;
1982 }
1983
1984 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001985 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00001986 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001987 }
1988
Douglas Gregor57373262008-10-22 14:17:15 +00001989 // Check that the winning standard conversion sequence isn't using
1990 // the deprecated string literal array to pointer conversion.
1991 switch (Result) {
1992 case ImplicitConversionSequence::Better:
1993 if (SCS1.Deprecated)
1994 Result = ImplicitConversionSequence::Indistinguishable;
1995 break;
1996
1997 case ImplicitConversionSequence::Indistinguishable:
1998 break;
1999
2000 case ImplicitConversionSequence::Worse:
2001 if (SCS2.Deprecated)
2002 Result = ImplicitConversionSequence::Indistinguishable;
2003 break;
2004 }
2005
2006 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002007}
2008
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002009/// CompareDerivedToBaseConversions - Compares two standard conversion
2010/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002011/// various kinds of derived-to-base conversions (C++
2012/// [over.ics.rank]p4b3). As part of these checks, we also look at
2013/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002014ImplicitConversionSequence::CompareKind
2015Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2016 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002017 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002018 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002019 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002020 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002021
2022 // Adjust the types we're converting from via the array-to-pointer
2023 // conversion, if we need to.
2024 if (SCS1.First == ICK_Array_To_Pointer)
2025 FromType1 = Context.getArrayDecayedType(FromType1);
2026 if (SCS2.First == ICK_Array_To_Pointer)
2027 FromType2 = Context.getArrayDecayedType(FromType2);
2028
2029 // Canonicalize all of the types.
2030 FromType1 = Context.getCanonicalType(FromType1);
2031 ToType1 = Context.getCanonicalType(ToType1);
2032 FromType2 = Context.getCanonicalType(FromType2);
2033 ToType2 = Context.getCanonicalType(ToType2);
2034
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002035 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002036 //
2037 // If class B is derived directly or indirectly from class A and
2038 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002039 //
2040 // For Objective-C, we let A, B, and C also be Objective-C
2041 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002042
2043 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002044 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002045 SCS2.Second == ICK_Pointer_Conversion &&
2046 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2047 FromType1->isPointerType() && FromType2->isPointerType() &&
2048 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002049 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002050 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002051 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002052 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002053 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002054 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002055 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002056 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002057
John McCall183700f2009-09-21 23:43:11 +00002058 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2059 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2060 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2061 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002062
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002063 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002064 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2065 if (IsDerivedFrom(ToPointee1, ToPointee2))
2066 return ImplicitConversionSequence::Better;
2067 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2068 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002069
2070 if (ToIface1 && ToIface2) {
2071 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2072 return ImplicitConversionSequence::Better;
2073 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2074 return ImplicitConversionSequence::Worse;
2075 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002076 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002077
2078 // -- conversion of B* to A* is better than conversion of C* to A*,
2079 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2080 if (IsDerivedFrom(FromPointee2, FromPointee1))
2081 return ImplicitConversionSequence::Better;
2082 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2083 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Douglas Gregorcb7de522008-11-26 23:31:11 +00002085 if (FromIface1 && FromIface2) {
2086 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2087 return ImplicitConversionSequence::Better;
2088 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2089 return ImplicitConversionSequence::Worse;
2090 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002091 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002092 }
2093
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002094 // Compare based on reference bindings.
2095 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
2096 SCS1.Second == ICK_Derived_To_Base) {
2097 // -- binding of an expression of type C to a reference of type
2098 // B& is better than binding an expression of type C to a
2099 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002100 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2101 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002102 if (IsDerivedFrom(ToType1, ToType2))
2103 return ImplicitConversionSequence::Better;
2104 else if (IsDerivedFrom(ToType2, ToType1))
2105 return ImplicitConversionSequence::Worse;
2106 }
2107
Douglas Gregor225c41e2008-11-03 19:09:14 +00002108 // -- binding of an expression of type B to a reference of type
2109 // A& is better than binding an expression of type C to a
2110 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002111 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2112 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002113 if (IsDerivedFrom(FromType2, FromType1))
2114 return ImplicitConversionSequence::Better;
2115 else if (IsDerivedFrom(FromType1, FromType2))
2116 return ImplicitConversionSequence::Worse;
2117 }
2118 }
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002119
2120 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002121 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2122 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2123 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2124 const MemberPointerType * FromMemPointer1 =
2125 FromType1->getAs<MemberPointerType>();
2126 const MemberPointerType * ToMemPointer1 =
2127 ToType1->getAs<MemberPointerType>();
2128 const MemberPointerType * FromMemPointer2 =
2129 FromType2->getAs<MemberPointerType>();
2130 const MemberPointerType * ToMemPointer2 =
2131 ToType2->getAs<MemberPointerType>();
2132 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2133 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2134 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2135 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2136 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2137 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2138 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2139 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002140 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002141 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2142 if (IsDerivedFrom(ToPointee1, ToPointee2))
2143 return ImplicitConversionSequence::Worse;
2144 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2145 return ImplicitConversionSequence::Better;
2146 }
2147 // conversion of B::* to C::* is better than conversion of A::* to C::*
2148 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2149 if (IsDerivedFrom(FromPointee1, FromPointee2))
2150 return ImplicitConversionSequence::Better;
2151 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2152 return ImplicitConversionSequence::Worse;
2153 }
2154 }
2155
Douglas Gregor225c41e2008-11-03 19:09:14 +00002156 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2157 SCS1.Second == ICK_Derived_To_Base) {
2158 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002159 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2160 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002161 if (IsDerivedFrom(ToType1, ToType2))
2162 return ImplicitConversionSequence::Better;
2163 else if (IsDerivedFrom(ToType2, ToType1))
2164 return ImplicitConversionSequence::Worse;
2165 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002166
Douglas Gregor225c41e2008-11-03 19:09:14 +00002167 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002168 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2169 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002170 if (IsDerivedFrom(FromType2, FromType1))
2171 return ImplicitConversionSequence::Better;
2172 else if (IsDerivedFrom(FromType1, FromType2))
2173 return ImplicitConversionSequence::Worse;
2174 }
2175 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002176
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002177 return ImplicitConversionSequence::Indistinguishable;
2178}
2179
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002180/// TryCopyInitialization - Try to copy-initialize a value of type
2181/// ToType from the expression From. Return the implicit conversion
2182/// sequence required to pass this argument, which may be a bad
2183/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002184/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00002185/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2186/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00002187ImplicitConversionSequence
2188Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002189 bool SuppressUserConversions, bool ForceRValue,
2190 bool InOverloadResolution) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00002191 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002192 ImplicitConversionSequence ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002193 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00002194 CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002195 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002196 SuppressUserConversions,
2197 /*AllowExplicit=*/false,
2198 ForceRValue,
2199 &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002200 return ICS;
2201 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002202 return TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002203 SuppressUserConversions,
2204 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002205 ForceRValue,
2206 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002207 }
2208}
2209
Sebastian Redle2b68332009-04-12 17:16:29 +00002210/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2211/// the expression @p From. Returns true (and emits a diagnostic) if there was
2212/// an error, returns false if the initialization succeeded. Elidable should
2213/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2214/// differently in C++0x for this case.
Mike Stump1eb44332009-09-09 15:08:12 +00002215bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00002216 AssignmentAction Action, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002217 if (!getLangOptions().CPlusPlus) {
2218 // In C, argument passing is the same as performing an assignment.
2219 QualType FromType = From->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002221 AssignConvertType ConvTy =
2222 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00002223 if (ConvTy != Compatible &&
2224 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2225 ConvTy = Compatible;
Mike Stump1eb44332009-09-09 15:08:12 +00002226
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002227 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00002228 FromType, From, Action);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002229 }
Sebastian Redle2b68332009-04-12 17:16:29 +00002230
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002231 if (ToType->isReferenceType())
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002232 return CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002233 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002234 /*SuppressUserConversions=*/false,
2235 /*AllowExplicit=*/false,
2236 /*ForceRValue=*/false);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002237
Douglas Gregor68647482009-12-16 03:45:30 +00002238 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redle2b68332009-04-12 17:16:29 +00002239 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002240 return false;
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002241 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002242 return Diag(From->getSourceRange().getBegin(),
2243 diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00002244 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002245 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002246}
2247
Douglas Gregor96176b32008-11-18 23:14:02 +00002248/// TryObjectArgumentInitialization - Try to initialize the object
2249/// parameter of the given member function (@c Method) from the
2250/// expression @p From.
2251ImplicitConversionSequence
John McCall651f3ee2010-01-14 03:28:57 +00002252Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall701c89e2009-12-03 04:06:58 +00002253 CXXMethodDecl *Method,
2254 CXXRecordDecl *ActingContext) {
2255 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002256 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2257 // const volatile object.
2258 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2259 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2260 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002261
2262 // Set up the conversion sequence as a "bad" conversion, to allow us
2263 // to exit early.
2264 ImplicitConversionSequence ICS;
2265 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00002266 ICS.setBad();
Douglas Gregor96176b32008-11-18 23:14:02 +00002267
2268 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00002269 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002270 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002271 FromType = PT->getPointeeType();
2272
2273 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002274
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002275 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002276 // where X is the class of which the function is a member
2277 // (C++ [over.match.funcs]p4). However, when finding an implicit
2278 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002279 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002280 // (C++ [over.match.funcs]p5). We perform a simplified version of
2281 // reference binding here, that allows class rvalues to bind to
2282 // non-constant references.
2283
2284 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2285 // with the implicit object parameter (C++ [over.match.funcs]p5).
2286 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002287 if (ImplicitParamType.getCVRQualifiers()
2288 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00002289 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall651f3ee2010-01-14 03:28:57 +00002290 ICS.Bad.init(BadConversionSequence::bad_qualifiers,
2291 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002292 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002293 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002294
2295 // Check that we have either the same type or a derived type. It
2296 // affects the conversion rank.
2297 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002298 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor96176b32008-11-18 23:14:02 +00002299 ICS.Standard.Second = ICK_Identity;
2300 else if (IsDerivedFrom(FromType, ClassType))
2301 ICS.Standard.Second = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00002302 else {
2303 ICS.Bad.init(BadConversionSequence::unrelated_class, FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002304 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002305 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002306
2307 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00002308 ICS.setStandard();
2309 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00002310 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002311 ICS.Standard.ReferenceBinding = true;
2312 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002313 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002314 return ICS;
2315}
2316
2317/// PerformObjectArgumentInitialization - Perform initialization of
2318/// the implicit object parameter for the given Method with the given
2319/// expression.
2320bool
2321Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002322 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002323 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002324 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002325
Ted Kremenek6217b802009-07-29 21:53:49 +00002326 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002327 FromRecordType = PT->getPointeeType();
2328 DestType = Method->getThisType(Context);
2329 } else {
2330 FromRecordType = From->getType();
2331 DestType = ImplicitParamRecordType;
2332 }
2333
John McCall701c89e2009-12-03 04:06:58 +00002334 // Note that we always use the true parent context when performing
2335 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002336 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00002337 = TryObjectArgumentInitialization(From->getType(), Method,
2338 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00002339 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00002340 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002341 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002342 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002343
Douglas Gregor96176b32008-11-18 23:14:02 +00002344 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssona552f7c2009-05-01 18:34:30 +00002345 CheckDerivedToBaseConversion(FromRecordType,
2346 ImplicitParamRecordType,
Douglas Gregor96176b32008-11-18 23:14:02 +00002347 From->getSourceRange().getBegin(),
2348 From->getSourceRange()))
2349 return true;
2350
Mike Stump1eb44332009-09-09 15:08:12 +00002351 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson116b7d92009-08-07 18:45:49 +00002352 /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002353 return false;
2354}
2355
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002356/// TryContextuallyConvertToBool - Attempt to contextually convert the
2357/// expression From to bool (C++0x [conv]p3).
2358ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002359 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002360 // FIXME: Are these flags correct?
2361 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002362 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002363 /*ForceRValue=*/false,
2364 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002365}
2366
2367/// PerformContextuallyConvertToBool - Perform a contextual conversion
2368/// of the expression From to bool (C++0x [conv]p3).
2369bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2370 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall1d318332010-01-12 00:44:57 +00002371 if (!ICS.isBad())
2372 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002373
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002374 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002375 return Diag(From->getSourceRange().getBegin(),
2376 diag::err_typecheck_bool_condition)
2377 << From->getType() << From->getSourceRange();
2378 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002379}
2380
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002381/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002382/// candidate functions, using the given function call arguments. If
2383/// @p SuppressUserConversions, then don't allow user-defined
2384/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002385/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2386/// hacky way to implement the overloading rules for elidable copy
2387/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002388///
2389/// \para PartialOverloading true if we are performing "partial" overloading
2390/// based on an incomplete set of function arguments. This feature is used by
2391/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00002392void
2393Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall86820f52010-01-26 01:37:31 +00002394 AccessSpecifier Access,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002395 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002396 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002397 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002398 bool ForceRValue,
2399 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00002400 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002401 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002402 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002403 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002404 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002405
Douglas Gregor88a35142008-12-22 05:46:06 +00002406 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002407 if (!isa<CXXConstructorDecl>(Method)) {
2408 // If we get here, it's because we're calling a member function
2409 // that is named without a member access expression (e.g.,
2410 // "this->f") that was either written explicitly or created
2411 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00002412 // function, e.g., X::f(). We use an empty type for the implied
2413 // object argument (C++ [over.call.func]p3), and the acting context
2414 // is irrelevant.
John McCall86820f52010-01-26 01:37:31 +00002415 AddMethodCandidate(Method, Access, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00002416 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002417 SuppressUserConversions, ForceRValue);
2418 return;
2419 }
2420 // We treat a constructor like a non-member function, since its object
2421 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002422 }
2423
Douglas Gregorfd476482009-11-13 23:59:09 +00002424 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00002425 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00002426
Douglas Gregor7edfb692009-11-23 12:27:39 +00002427 // Overload resolution is always an unevaluated context.
2428 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2429
Douglas Gregor66724ea2009-11-14 01:20:54 +00002430 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2431 // C++ [class.copy]p3:
2432 // A member function template is never instantiated to perform the copy
2433 // of a class object to an object of its class type.
2434 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2435 if (NumArgs == 1 &&
2436 Constructor->isCopyConstructorLikeSpecialization() &&
2437 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2438 return;
2439 }
2440
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002441 // Add this candidate
2442 CandidateSet.push_back(OverloadCandidate());
2443 OverloadCandidate& Candidate = CandidateSet.back();
2444 Candidate.Function = Function;
John McCall86820f52010-01-26 01:37:31 +00002445 Candidate.Access = Access;
Douglas Gregor88a35142008-12-22 05:46:06 +00002446 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002447 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002448 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002449
2450 unsigned NumArgsInProto = Proto->getNumArgs();
2451
2452 // (C++ 13.3.2p2): A candidate function having fewer than m
2453 // parameters is viable only if it has an ellipsis in its parameter
2454 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00002455 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2456 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002457 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002458 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002459 return;
2460 }
2461
2462 // (C++ 13.3.2p2): A candidate function having more than m parameters
2463 // is viable only if the (m+1)st parameter has a default argument
2464 // (8.3.6). For the purposes of overload resolution, the
2465 // parameter list is truncated on the right, so that there are
2466 // exactly m parameters.
2467 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002468 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002469 // Not enough arguments.
2470 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002471 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002472 return;
2473 }
2474
2475 // Determine the implicit conversion sequences for each of the
2476 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002477 Candidate.Conversions.resize(NumArgs);
2478 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2479 if (ArgIdx < NumArgsInProto) {
2480 // (C++ 13.3.2p3): for F to be a viable function, there shall
2481 // exist for each argument an implicit conversion sequence
2482 // (13.3.3.1) that converts that argument to the corresponding
2483 // parameter of F.
2484 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002485 Candidate.Conversions[ArgIdx]
2486 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002487 SuppressUserConversions, ForceRValue,
2488 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00002489 if (Candidate.Conversions[ArgIdx].isBad()) {
2490 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002491 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00002492 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00002493 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002494 } else {
2495 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2496 // argument for which there is no corresponding parameter is
2497 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002498 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002499 }
2500 }
2501}
2502
Douglas Gregor063daf62009-03-13 18:40:31 +00002503/// \brief Add all of the function declarations in the given function set to
2504/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00002505void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00002506 Expr **Args, unsigned NumArgs,
2507 OverloadCandidateSet& CandidateSet,
2508 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00002509 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall701c89e2009-12-03 04:06:58 +00002510 // FIXME: using declarations
Douglas Gregor3f396022009-09-28 04:47:19 +00002511 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2512 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall6e266892010-01-26 03:27:55 +00002513 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getAccess(),
John McCall701c89e2009-12-03 04:06:58 +00002514 cast<CXXMethodDecl>(FD)->getParent(),
2515 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002516 CandidateSet, SuppressUserConversions);
2517 else
John McCall86820f52010-01-26 01:37:31 +00002518 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00002519 SuppressUserConversions);
2520 } else {
2521 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2522 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2523 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall6e266892010-01-26 03:27:55 +00002524 AddMethodTemplateCandidate(FunTmpl, F.getAccess(),
John McCall701c89e2009-12-03 04:06:58 +00002525 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00002526 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00002527 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002528 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002529 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00002530 else
John McCall86820f52010-01-26 01:37:31 +00002531 AddTemplateOverloadCandidate(FunTmpl, AS_none,
John McCalld5532b62009-11-23 01:53:49 +00002532 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00002533 Args, NumArgs, CandidateSet,
2534 SuppressUserConversions);
2535 }
Douglas Gregor364e0212009-06-27 21:05:07 +00002536 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002537}
2538
John McCall314be4e2009-11-17 07:50:12 +00002539/// AddMethodCandidate - Adds a named decl (which is some kind of
2540/// method) as a method candidate to the given overload set.
John McCall701c89e2009-12-03 04:06:58 +00002541void Sema::AddMethodCandidate(NamedDecl *Decl,
John McCall86820f52010-01-26 01:37:31 +00002542 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002543 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00002544 Expr **Args, unsigned NumArgs,
2545 OverloadCandidateSet& CandidateSet,
2546 bool SuppressUserConversions, bool ForceRValue) {
John McCall701c89e2009-12-03 04:06:58 +00002547 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00002548
2549 if (isa<UsingShadowDecl>(Decl))
2550 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2551
2552 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2553 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2554 "Expected a member function template");
John McCall86820f52010-01-26 01:37:31 +00002555 AddMethodTemplateCandidate(TD, Access, ActingContext, /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00002556 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002557 CandidateSet,
2558 SuppressUserConversions,
2559 ForceRValue);
2560 } else {
John McCall86820f52010-01-26 01:37:31 +00002561 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Access, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00002562 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002563 CandidateSet, SuppressUserConversions, ForceRValue);
2564 }
2565}
2566
Douglas Gregor96176b32008-11-18 23:14:02 +00002567/// AddMethodCandidate - Adds the given C++ member function to the set
2568/// of candidate functions, using the given function call arguments
2569/// and the object argument (@c Object). For example, in a call
2570/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2571/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2572/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002573/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2574/// a slightly hacky way to implement the overloading rules for elidable copy
2575/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002576void
John McCall86820f52010-01-26 01:37:31 +00002577Sema::AddMethodCandidate(CXXMethodDecl *Method, AccessSpecifier Access,
2578 CXXRecordDecl *ActingContext, QualType ObjectType,
2579 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00002580 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002581 bool SuppressUserConversions, bool ForceRValue) {
2582 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002583 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002584 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002585 assert(!isa<CXXConstructorDecl>(Method) &&
2586 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002587
Douglas Gregor3f396022009-09-28 04:47:19 +00002588 if (!CandidateSet.isNewCandidate(Method))
2589 return;
2590
Douglas Gregor7edfb692009-11-23 12:27:39 +00002591 // Overload resolution is always an unevaluated context.
2592 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2593
Douglas Gregor96176b32008-11-18 23:14:02 +00002594 // Add this candidate
2595 CandidateSet.push_back(OverloadCandidate());
2596 OverloadCandidate& Candidate = CandidateSet.back();
2597 Candidate.Function = Method;
John McCall86820f52010-01-26 01:37:31 +00002598 Candidate.Access = Access;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002599 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002600 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002601
2602 unsigned NumArgsInProto = Proto->getNumArgs();
2603
2604 // (C++ 13.3.2p2): A candidate function having fewer than m
2605 // parameters is viable only if it has an ellipsis in its parameter
2606 // list (8.3.5).
2607 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2608 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002609 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00002610 return;
2611 }
2612
2613 // (C++ 13.3.2p2): A candidate function having more than m parameters
2614 // is viable only if the (m+1)st parameter has a default argument
2615 // (8.3.6). For the purposes of overload resolution, the
2616 // parameter list is truncated on the right, so that there are
2617 // exactly m parameters.
2618 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2619 if (NumArgs < MinRequiredArgs) {
2620 // Not enough arguments.
2621 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002622 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00002623 return;
2624 }
2625
2626 Candidate.Viable = true;
2627 Candidate.Conversions.resize(NumArgs + 1);
2628
John McCall701c89e2009-12-03 04:06:58 +00002629 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00002630 // The implicit object argument is ignored.
2631 Candidate.IgnoreObjectArgument = true;
2632 else {
2633 // Determine the implicit conversion sequence for the object
2634 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00002635 Candidate.Conversions[0]
2636 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00002637 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002638 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002639 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00002640 return;
2641 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002642 }
2643
2644 // Determine the implicit conversion sequences for each of the
2645 // arguments.
2646 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2647 if (ArgIdx < NumArgsInProto) {
2648 // (C++ 13.3.2p3): for F to be a viable function, there shall
2649 // exist for each argument an implicit conversion sequence
2650 // (13.3.3.1) that converts that argument to the corresponding
2651 // parameter of F.
2652 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002653 Candidate.Conversions[ArgIdx + 1]
2654 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002655 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002656 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00002657 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002658 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002659 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00002660 break;
2661 }
2662 } else {
2663 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2664 // argument for which there is no corresponding parameter is
2665 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002666 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00002667 }
2668 }
2669}
2670
Douglas Gregor6b906862009-08-21 00:16:32 +00002671/// \brief Add a C++ member function template as a candidate to the candidate
2672/// set, using template argument deduction to produce an appropriate member
2673/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002674void
Douglas Gregor6b906862009-08-21 00:16:32 +00002675Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall86820f52010-01-26 01:37:31 +00002676 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002677 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00002678 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00002679 QualType ObjectType,
2680 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002681 OverloadCandidateSet& CandidateSet,
2682 bool SuppressUserConversions,
2683 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002684 if (!CandidateSet.isNewCandidate(MethodTmpl))
2685 return;
2686
Douglas Gregor6b906862009-08-21 00:16:32 +00002687 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002688 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002689 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002690 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002691 // candidate functions in the usual way.113) A given name can refer to one
2692 // or more function templates and also to a set of overloaded non-template
2693 // functions. In such a case, the candidate functions generated from each
2694 // function template are combined with the set of non-template candidate
2695 // functions.
2696 TemplateDeductionInfo Info(Context);
2697 FunctionDecl *Specialization = 0;
2698 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002699 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002700 Args, NumArgs, Specialization, Info)) {
2701 // FIXME: Record what happened with template argument deduction, so
2702 // that we can give the user a beautiful diagnostic.
2703 (void)Result;
2704 return;
2705 }
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Douglas Gregor6b906862009-08-21 00:16:32 +00002707 // Add the function template specialization produced by template argument
2708 // deduction as a candidate.
2709 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002710 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002711 "Specialization is not a member function?");
John McCall86820f52010-01-26 01:37:31 +00002712 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Access,
2713 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002714 CandidateSet, SuppressUserConversions, ForceRValue);
2715}
2716
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002717/// \brief Add a C++ function template specialization as a candidate
2718/// in the candidate set, using template argument deduction to produce
2719/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002720void
Douglas Gregore53060f2009-06-25 22:08:12 +00002721Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall86820f52010-01-26 01:37:31 +00002722 AccessSpecifier Access,
John McCalld5532b62009-11-23 01:53:49 +00002723 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002724 Expr **Args, unsigned NumArgs,
2725 OverloadCandidateSet& CandidateSet,
2726 bool SuppressUserConversions,
2727 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002728 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2729 return;
2730
Douglas Gregore53060f2009-06-25 22:08:12 +00002731 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002732 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00002733 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002734 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00002735 // candidate functions in the usual way.113) A given name can refer to one
2736 // or more function templates and also to a set of overloaded non-template
2737 // functions. In such a case, the candidate functions generated from each
2738 // function template are combined with the set of non-template candidate
2739 // functions.
2740 TemplateDeductionInfo Info(Context);
2741 FunctionDecl *Specialization = 0;
2742 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002743 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002744 Args, NumArgs, Specialization, Info)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002745 // FIXME: Record what happened with template argument deduction, so
2746 // that we can give the user a beautiful diagnostic.
John McCall578b69b2009-12-16 08:11:27 +00002747 (void) Result;
2748
2749 CandidateSet.push_back(OverloadCandidate());
2750 OverloadCandidate &Candidate = CandidateSet.back();
2751 Candidate.Function = FunctionTemplate->getTemplatedDecl();
John McCall86820f52010-01-26 01:37:31 +00002752 Candidate.Access = Access;
John McCall578b69b2009-12-16 08:11:27 +00002753 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002754 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00002755 Candidate.IsSurrogate = false;
2756 Candidate.IgnoreObjectArgument = false;
Douglas Gregore53060f2009-06-25 22:08:12 +00002757 return;
2758 }
Mike Stump1eb44332009-09-09 15:08:12 +00002759
Douglas Gregore53060f2009-06-25 22:08:12 +00002760 // Add the function template specialization produced by template argument
2761 // deduction as a candidate.
2762 assert(Specialization && "Missing function template specialization?");
John McCall86820f52010-01-26 01:37:31 +00002763 AddOverloadCandidate(Specialization, Access, Args, NumArgs, CandidateSet,
Douglas Gregore53060f2009-06-25 22:08:12 +00002764 SuppressUserConversions, ForceRValue);
2765}
Mike Stump1eb44332009-09-09 15:08:12 +00002766
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002767/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002768/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002769/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002770/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002771/// (which may or may not be the same type as the type that the
2772/// conversion function produces).
2773void
2774Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall86820f52010-01-26 01:37:31 +00002775 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002776 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002777 Expr *From, QualType ToType,
2778 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002779 assert(!Conversion->getDescribedFunctionTemplate() &&
2780 "Conversion function templates use AddTemplateConversionCandidate");
2781
Douglas Gregor3f396022009-09-28 04:47:19 +00002782 if (!CandidateSet.isNewCandidate(Conversion))
2783 return;
2784
Douglas Gregor7edfb692009-11-23 12:27:39 +00002785 // Overload resolution is always an unevaluated context.
2786 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2787
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002788 // Add this candidate
2789 CandidateSet.push_back(OverloadCandidate());
2790 OverloadCandidate& Candidate = CandidateSet.back();
2791 Candidate.Function = Conversion;
John McCall86820f52010-01-26 01:37:31 +00002792 Candidate.Access = Access;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002793 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002794 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002795 Candidate.FinalConversion.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00002796 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
Douglas Gregorad323a82010-01-27 03:51:04 +00002797 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002798
Douglas Gregor96176b32008-11-18 23:14:02 +00002799 // Determine the implicit conversion sequence for the implicit
2800 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002801 Candidate.Viable = true;
2802 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00002803 Candidate.Conversions[0]
2804 = TryObjectArgumentInitialization(From->getType(), Conversion,
2805 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002806 // Conversion functions to a different type in the base class is visible in
2807 // the derived class. So, a derived to base conversion should not participate
2808 // in overload resolution.
2809 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2810 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall1d318332010-01-12 00:44:57 +00002811 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002812 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002813 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002814 return;
2815 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002816
2817 // We won't go through a user-define type conversion function to convert a
2818 // derived to base as such conversions are given Conversion Rank. They only
2819 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2820 QualType FromCanon
2821 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2822 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2823 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2824 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00002825 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002826 return;
2827 }
2828
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002829
2830 // To determine what the conversion from the result of calling the
2831 // conversion function to the type we're eventually trying to
2832 // convert to (ToType), we need to synthesize a call to the
2833 // conversion function and attempt copy initialization from it. This
2834 // makes sure that we get the right semantics with respect to
2835 // lvalues/rvalues and the type. Fortunately, we can allocate this
2836 // call on the stack and we don't need its arguments to be
2837 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002838 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002839 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002840 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00002841 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002842 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002843
2844 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002845 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2846 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002847 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002848 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002849 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00002850 ImplicitConversionSequence ICS =
2851 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002852 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002853 /*ForceRValue=*/false,
2854 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002855
John McCall1d318332010-01-12 00:44:57 +00002856 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002857 case ImplicitConversionSequence::StandardConversion:
2858 Candidate.FinalConversion = ICS.Standard;
2859 break;
2860
2861 case ImplicitConversionSequence::BadConversion:
2862 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00002863 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002864 break;
2865
2866 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002867 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002868 "Can only end up with a standard conversion sequence or failure");
2869 }
2870}
2871
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002872/// \brief Adds a conversion function template specialization
2873/// candidate to the overload set, using template argument deduction
2874/// to deduce the template arguments of the conversion function
2875/// template from the type that we are converting to (C++
2876/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002877void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002878Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall86820f52010-01-26 01:37:31 +00002879 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002880 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002881 Expr *From, QualType ToType,
2882 OverloadCandidateSet &CandidateSet) {
2883 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2884 "Only conversion function templates permitted here");
2885
Douglas Gregor3f396022009-09-28 04:47:19 +00002886 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2887 return;
2888
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002889 TemplateDeductionInfo Info(Context);
2890 CXXConversionDecl *Specialization = 0;
2891 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002892 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002893 Specialization, Info)) {
2894 // FIXME: Record what happened with template argument deduction, so
2895 // that we can give the user a beautiful diagnostic.
2896 (void)Result;
2897 return;
2898 }
Mike Stump1eb44332009-09-09 15:08:12 +00002899
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002900 // Add the conversion function template specialization produced by
2901 // template argument deduction as a candidate.
2902 assert(Specialization && "Missing function template specialization?");
John McCall86820f52010-01-26 01:37:31 +00002903 AddConversionCandidate(Specialization, Access, ActingDC, From, ToType,
2904 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002905}
2906
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002907/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2908/// converts the given @c Object to a function pointer via the
2909/// conversion function @c Conversion, and then attempts to call it
2910/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2911/// the type of function that we'll eventually be calling.
2912void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall86820f52010-01-26 01:37:31 +00002913 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002914 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00002915 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00002916 QualType ObjectType,
2917 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002918 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002919 if (!CandidateSet.isNewCandidate(Conversion))
2920 return;
2921
Douglas Gregor7edfb692009-11-23 12:27:39 +00002922 // Overload resolution is always an unevaluated context.
2923 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2924
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002925 CandidateSet.push_back(OverloadCandidate());
2926 OverloadCandidate& Candidate = CandidateSet.back();
2927 Candidate.Function = 0;
John McCall86820f52010-01-26 01:37:31 +00002928 Candidate.Access = Access;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002929 Candidate.Surrogate = Conversion;
2930 Candidate.Viable = true;
2931 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002932 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002933 Candidate.Conversions.resize(NumArgs + 1);
2934
2935 // Determine the implicit conversion sequence for the implicit
2936 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002937 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00002938 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00002939 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002940 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002941 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00002942 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002943 return;
2944 }
2945
2946 // The first conversion is actually a user-defined conversion whose
2947 // first conversion is ObjectInit's standard conversion (which is
2948 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00002949 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002950 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002951 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002952 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002953 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002954 = Candidate.Conversions[0].UserDefined.Before;
2955 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2956
Mike Stump1eb44332009-09-09 15:08:12 +00002957 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002958 unsigned NumArgsInProto = Proto->getNumArgs();
2959
2960 // (C++ 13.3.2p2): A candidate function having fewer than m
2961 // parameters is viable only if it has an ellipsis in its parameter
2962 // list (8.3.5).
2963 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2964 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002965 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002966 return;
2967 }
2968
2969 // Function types don't have any default arguments, so just check if
2970 // we have enough arguments.
2971 if (NumArgs < NumArgsInProto) {
2972 // Not enough arguments.
2973 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002974 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002975 return;
2976 }
2977
2978 // Determine the implicit conversion sequences for each of the
2979 // arguments.
2980 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2981 if (ArgIdx < NumArgsInProto) {
2982 // (C++ 13.3.2p3): for F to be a viable function, there shall
2983 // exist for each argument an implicit conversion sequence
2984 // (13.3.3.1) that converts that argument to the corresponding
2985 // parameter of F.
2986 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002987 Candidate.Conversions[ArgIdx + 1]
2988 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002989 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002990 /*ForceRValue=*/false,
2991 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00002992 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002993 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002994 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002995 break;
2996 }
2997 } else {
2998 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2999 // argument for which there is no corresponding parameter is
3000 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003001 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003002 }
3003 }
3004}
3005
Mike Stump390b4cc2009-05-16 07:39:55 +00003006// FIXME: This will eventually be removed, once we've migrated all of the
3007// operator overloading logic over to the scheme used by binary operators, which
3008// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00003009void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00003010 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00003011 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00003012 OverloadCandidateSet& CandidateSet,
3013 SourceRange OpRange) {
John McCall6e266892010-01-26 03:27:55 +00003014 UnresolvedSet<16> Fns;
Douglas Gregor063daf62009-03-13 18:40:31 +00003015
3016 QualType T1 = Args[0]->getType();
3017 QualType T2;
3018 if (NumArgs > 1)
3019 T2 = Args[1]->getType();
3020
3021 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003022 if (S)
John McCall6e266892010-01-26 03:27:55 +00003023 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3024 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3025 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3026 CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00003027 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregor573d9c32009-10-21 23:19:44 +00003028 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00003029}
3030
3031/// \brief Add overload candidates for overloaded operators that are
3032/// member functions.
3033///
3034/// Add the overloaded operator candidates that are member functions
3035/// for the operator Op that was used in an operator expression such
3036/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3037/// CandidateSet will store the added overload candidates. (C++
3038/// [over.match.oper]).
3039void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3040 SourceLocation OpLoc,
3041 Expr **Args, unsigned NumArgs,
3042 OverloadCandidateSet& CandidateSet,
3043 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003044 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3045
3046 // C++ [over.match.oper]p3:
3047 // For a unary operator @ with an operand of a type whose
3048 // cv-unqualified version is T1, and for a binary operator @ with
3049 // a left operand of a type whose cv-unqualified version is T1 and
3050 // a right operand of a type whose cv-unqualified version is T2,
3051 // three sets of candidate functions, designated member
3052 // candidates, non-member candidates and built-in candidates, are
3053 // constructed as follows:
3054 QualType T1 = Args[0]->getType();
3055 QualType T2;
3056 if (NumArgs > 1)
3057 T2 = Args[1]->getType();
3058
3059 // -- If T1 is a class type, the set of member candidates is the
3060 // result of the qualified lookup of T1::operator@
3061 // (13.3.1.1.1); otherwise, the set of member candidates is
3062 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00003063 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003064 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003065 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003066 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003067
John McCalla24dc2e2009-11-17 02:14:36 +00003068 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3069 LookupQualifiedName(Operators, T1Rec->getDecl());
3070 Operators.suppressDiagnostics();
3071
Mike Stump1eb44332009-09-09 15:08:12 +00003072 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003073 OperEnd = Operators.end();
3074 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00003075 ++Oper)
John McCall86820f52010-01-26 01:37:31 +00003076 AddMethodCandidate(*Oper, Oper.getAccess(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00003077 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00003078 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00003079 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003080}
3081
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003082/// AddBuiltinCandidate - Add a candidate for a built-in
3083/// operator. ResultTy and ParamTys are the result and parameter types
3084/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003085/// arguments being passed to the candidate. IsAssignmentOperator
3086/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003087/// operator. NumContextualBoolArguments is the number of arguments
3088/// (at the beginning of the argument list) that will be contextually
3089/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00003090void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003091 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003092 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003093 bool IsAssignmentOperator,
3094 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00003095 // Overload resolution is always an unevaluated context.
3096 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3097
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003098 // Add this candidate
3099 CandidateSet.push_back(OverloadCandidate());
3100 OverloadCandidate& Candidate = CandidateSet.back();
3101 Candidate.Function = 0;
John McCall86820f52010-01-26 01:37:31 +00003102 Candidate.Access = AS_none;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003103 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003104 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003105 Candidate.BuiltinTypes.ResultTy = ResultTy;
3106 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3107 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3108
3109 // Determine the implicit conversion sequences for each of the
3110 // arguments.
3111 Candidate.Viable = true;
3112 Candidate.Conversions.resize(NumArgs);
3113 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003114 // C++ [over.match.oper]p4:
3115 // For the built-in assignment operators, conversions of the
3116 // left operand are restricted as follows:
3117 // -- no temporaries are introduced to hold the left operand, and
3118 // -- no user-defined conversions are applied to the left
3119 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00003120 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003121 //
3122 // We block these conversions by turning off user-defined
3123 // conversions, since that is the only way that initialization of
3124 // a reference to a non-class type can occur from something that
3125 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003126 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00003127 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003128 "Contextual conversion to bool requires bool type");
3129 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3130 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003131 Candidate.Conversions[ArgIdx]
3132 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00003133 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003134 /*ForceRValue=*/false,
3135 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003136 }
John McCall1d318332010-01-12 00:44:57 +00003137 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003138 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003139 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003140 break;
3141 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003142 }
3143}
3144
3145/// BuiltinCandidateTypeSet - A set of types that will be used for the
3146/// candidate operator functions for built-in operators (C++
3147/// [over.built]). The types are separated into pointer types and
3148/// enumeration types.
3149class BuiltinCandidateTypeSet {
3150 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003151 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003152
3153 /// PointerTypes - The set of pointer types that will be used in the
3154 /// built-in candidates.
3155 TypeSet PointerTypes;
3156
Sebastian Redl78eb8742009-04-19 21:53:20 +00003157 /// MemberPointerTypes - The set of member pointer types that will be
3158 /// used in the built-in candidates.
3159 TypeSet MemberPointerTypes;
3160
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003161 /// EnumerationTypes - The set of enumeration types that will be
3162 /// used in the built-in candidates.
3163 TypeSet EnumerationTypes;
3164
Douglas Gregor5842ba92009-08-24 15:23:48 +00003165 /// Sema - The semantic analysis instance where we are building the
3166 /// candidate type set.
3167 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003168
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003169 /// Context - The AST context in which we will build the type sets.
3170 ASTContext &Context;
3171
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003172 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3173 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003174 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003175
3176public:
3177 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003178 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003179
Mike Stump1eb44332009-09-09 15:08:12 +00003180 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003181 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003182
Douglas Gregor573d9c32009-10-21 23:19:44 +00003183 void AddTypesConvertedFrom(QualType Ty,
3184 SourceLocation Loc,
3185 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003186 bool AllowExplicitConversions,
3187 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003188
3189 /// pointer_begin - First pointer type found;
3190 iterator pointer_begin() { return PointerTypes.begin(); }
3191
Sebastian Redl78eb8742009-04-19 21:53:20 +00003192 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003193 iterator pointer_end() { return PointerTypes.end(); }
3194
Sebastian Redl78eb8742009-04-19 21:53:20 +00003195 /// member_pointer_begin - First member pointer type found;
3196 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3197
3198 /// member_pointer_end - Past the last member pointer type found;
3199 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3200
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003201 /// enumeration_begin - First enumeration type found;
3202 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3203
Sebastian Redl78eb8742009-04-19 21:53:20 +00003204 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003205 iterator enumeration_end() { return EnumerationTypes.end(); }
3206};
3207
Sebastian Redl78eb8742009-04-19 21:53:20 +00003208/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003209/// the set of pointer types along with any more-qualified variants of
3210/// that type. For example, if @p Ty is "int const *", this routine
3211/// will add "int const *", "int const volatile *", "int const
3212/// restrict *", and "int const volatile restrict *" to the set of
3213/// pointer types. Returns true if the add of @p Ty itself succeeded,
3214/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003215///
3216/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003217bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003218BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3219 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003220
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003221 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003222 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003223 return false;
3224
John McCall0953e762009-09-24 19:53:00 +00003225 const PointerType *PointerTy = Ty->getAs<PointerType>();
3226 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003227
John McCall0953e762009-09-24 19:53:00 +00003228 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003229 // Don't add qualified variants of arrays. For one, they're not allowed
3230 // (the qualifier would sink to the element type), and for another, the
3231 // only overload situation where it matters is subscript or pointer +- int,
3232 // and those shouldn't have qualifier variants anyway.
3233 if (PointeeTy->isArrayType())
3234 return true;
John McCall0953e762009-09-24 19:53:00 +00003235 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003236 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003237 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003238 bool hasVolatile = VisibleQuals.hasVolatile();
3239 bool hasRestrict = VisibleQuals.hasRestrict();
3240
John McCall0953e762009-09-24 19:53:00 +00003241 // Iterate through all strict supersets of BaseCVR.
3242 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3243 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003244 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3245 // in the types.
3246 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3247 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003248 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3249 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003250 }
3251
3252 return true;
3253}
3254
Sebastian Redl78eb8742009-04-19 21:53:20 +00003255/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3256/// to the set of pointer types along with any more-qualified variants of
3257/// that type. For example, if @p Ty is "int const *", this routine
3258/// will add "int const *", "int const volatile *", "int const
3259/// restrict *", and "int const volatile restrict *" to the set of
3260/// pointer types. Returns true if the add of @p Ty itself succeeded,
3261/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003262///
3263/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003264bool
3265BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3266 QualType Ty) {
3267 // Insert this type.
3268 if (!MemberPointerTypes.insert(Ty))
3269 return false;
3270
John McCall0953e762009-09-24 19:53:00 +00003271 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3272 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003273
John McCall0953e762009-09-24 19:53:00 +00003274 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003275 // Don't add qualified variants of arrays. For one, they're not allowed
3276 // (the qualifier would sink to the element type), and for another, the
3277 // only overload situation where it matters is subscript or pointer +- int,
3278 // and those shouldn't have qualifier variants anyway.
3279 if (PointeeTy->isArrayType())
3280 return true;
John McCall0953e762009-09-24 19:53:00 +00003281 const Type *ClassTy = PointerTy->getClass();
3282
3283 // Iterate through all strict supersets of the pointee type's CVR
3284 // qualifiers.
3285 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3286 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3287 if ((CVR | BaseCVR) != CVR) continue;
3288
3289 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3290 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003291 }
3292
3293 return true;
3294}
3295
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003296/// AddTypesConvertedFrom - Add each of the types to which the type @p
3297/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003298/// primarily interested in pointer types and enumeration types. We also
3299/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003300/// AllowUserConversions is true if we should look at the conversion
3301/// functions of a class type, and AllowExplicitConversions if we
3302/// should also include the explicit conversion functions of a class
3303/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003304void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003305BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003306 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003307 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003308 bool AllowExplicitConversions,
3309 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003310 // Only deal with canonical types.
3311 Ty = Context.getCanonicalType(Ty);
3312
3313 // Look through reference types; they aren't part of the type of an
3314 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003315 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003316 Ty = RefTy->getPointeeType();
3317
3318 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003319 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003320
Sebastian Redla65b5512009-11-05 16:36:20 +00003321 // If we're dealing with an array type, decay to the pointer.
3322 if (Ty->isArrayType())
3323 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3324
Ted Kremenek6217b802009-07-29 21:53:49 +00003325 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003326 QualType PointeeTy = PointerTy->getPointeeType();
3327
3328 // Insert our type, and its more-qualified variants, into the set
3329 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003330 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003331 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003332 } else if (Ty->isMemberPointerType()) {
3333 // Member pointers are far easier, since the pointee can't be converted.
3334 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3335 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003336 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003337 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003338 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003339 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003340 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003341 // No conversion functions in incomplete types.
3342 return;
3343 }
Mike Stump1eb44332009-09-09 15:08:12 +00003344
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003345 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00003346 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003347 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003348 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003349 E = Conversions->end(); I != E; ++I) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003350
Mike Stump1eb44332009-09-09 15:08:12 +00003351 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003352 // about which builtin types we can convert to.
John McCallba135432009-11-21 08:51:07 +00003353 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003354 continue;
3355
John McCallba135432009-11-21 08:51:07 +00003356 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003357 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003358 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003359 VisibleQuals);
3360 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003361 }
3362 }
3363 }
3364}
3365
Douglas Gregor19b7b152009-08-24 13:43:27 +00003366/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3367/// the volatile- and non-volatile-qualified assignment operators for the
3368/// given type to the candidate set.
3369static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3370 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003371 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003372 unsigned NumArgs,
3373 OverloadCandidateSet &CandidateSet) {
3374 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003375
Douglas Gregor19b7b152009-08-24 13:43:27 +00003376 // T& operator=(T&, T)
3377 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3378 ParamTypes[1] = T;
3379 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3380 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003381
Douglas Gregor19b7b152009-08-24 13:43:27 +00003382 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3383 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003384 ParamTypes[0]
3385 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003386 ParamTypes[1] = T;
3387 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003388 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003389 }
3390}
Mike Stump1eb44332009-09-09 15:08:12 +00003391
Sebastian Redl9994a342009-10-25 17:03:50 +00003392/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3393/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003394static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3395 Qualifiers VRQuals;
3396 const RecordType *TyRec;
3397 if (const MemberPointerType *RHSMPType =
3398 ArgExpr->getType()->getAs<MemberPointerType>())
3399 TyRec = cast<RecordType>(RHSMPType->getClass());
3400 else
3401 TyRec = ArgExpr->getType()->getAs<RecordType>();
3402 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003403 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003404 VRQuals.addVolatile();
3405 VRQuals.addRestrict();
3406 return VRQuals;
3407 }
3408
3409 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00003410 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00003411 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003412
John McCalleec51cf2010-01-20 00:46:10 +00003413 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003414 E = Conversions->end(); I != E; ++I) {
3415 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003416 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3417 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3418 CanTy = ResTypeRef->getPointeeType();
3419 // Need to go down the pointer/mempointer chain and add qualifiers
3420 // as see them.
3421 bool done = false;
3422 while (!done) {
3423 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3424 CanTy = ResTypePtr->getPointeeType();
3425 else if (const MemberPointerType *ResTypeMPtr =
3426 CanTy->getAs<MemberPointerType>())
3427 CanTy = ResTypeMPtr->getPointeeType();
3428 else
3429 done = true;
3430 if (CanTy.isVolatileQualified())
3431 VRQuals.addVolatile();
3432 if (CanTy.isRestrictQualified())
3433 VRQuals.addRestrict();
3434 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3435 return VRQuals;
3436 }
3437 }
3438 }
3439 return VRQuals;
3440}
3441
Douglas Gregor74253732008-11-19 15:42:04 +00003442/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3443/// operator overloads to the candidate set (C++ [over.built]), based
3444/// on the operator @p Op and the arguments given. For example, if the
3445/// operator is a binary '+', this routine might add "int
3446/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003447void
Mike Stump1eb44332009-09-09 15:08:12 +00003448Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003449 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00003450 Expr **Args, unsigned NumArgs,
3451 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003452 // The set of "promoted arithmetic types", which are the arithmetic
3453 // types are that preserved by promotion (C++ [over.built]p2). Note
3454 // that the first few of these types are the promoted integral
3455 // types; these types need to be first.
3456 // FIXME: What about complex?
3457 const unsigned FirstIntegralType = 0;
3458 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00003459 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003460 LastPromotedIntegralType = 13;
3461 const unsigned FirstPromotedArithmeticType = 7,
3462 LastPromotedArithmeticType = 16;
3463 const unsigned NumArithmeticTypes = 16;
3464 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003465 Context.BoolTy, Context.CharTy, Context.WCharTy,
3466// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003467 Context.SignedCharTy, Context.ShortTy,
3468 Context.UnsignedCharTy, Context.UnsignedShortTy,
3469 Context.IntTy, Context.LongTy, Context.LongLongTy,
3470 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3471 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3472 };
Douglas Gregor652371a2009-10-21 22:01:30 +00003473 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3474 "Invalid first promoted integral type");
3475 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3476 == Context.UnsignedLongLongTy &&
3477 "Invalid last promoted integral type");
3478 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3479 "Invalid first promoted arithmetic type");
3480 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3481 == Context.LongDoubleTy &&
3482 "Invalid last promoted arithmetic type");
3483
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003484 // Find all of the types that the arguments can convert to, but only
3485 // if the operator we're looking at has built-in operator candidates
3486 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003487 Qualifiers VisibleTypeConversionsQuals;
3488 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003489 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3490 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3491
Douglas Gregor5842ba92009-08-24 15:23:48 +00003492 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003493 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3494 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003495 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003496 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003497 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003498 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003499 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003500 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregor573d9c32009-10-21 23:19:44 +00003501 OpLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003502 true,
3503 (Op == OO_Exclaim ||
3504 Op == OO_AmpAmp ||
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003505 Op == OO_PipePipe),
3506 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003507 }
3508
3509 bool isComparison = false;
3510 switch (Op) {
3511 case OO_None:
3512 case NUM_OVERLOADED_OPERATORS:
3513 assert(false && "Expected an overloaded operator");
3514 break;
3515
Douglas Gregor74253732008-11-19 15:42:04 +00003516 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003517 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003518 goto UnaryStar;
3519 else
3520 goto BinaryStar;
3521 break;
3522
3523 case OO_Plus: // '+' is either unary or binary
3524 if (NumArgs == 1)
3525 goto UnaryPlus;
3526 else
3527 goto BinaryPlus;
3528 break;
3529
3530 case OO_Minus: // '-' is either unary or binary
3531 if (NumArgs == 1)
3532 goto UnaryMinus;
3533 else
3534 goto BinaryMinus;
3535 break;
3536
3537 case OO_Amp: // '&' is either unary or binary
3538 if (NumArgs == 1)
3539 goto UnaryAmp;
3540 else
3541 goto BinaryAmp;
3542
3543 case OO_PlusPlus:
3544 case OO_MinusMinus:
3545 // C++ [over.built]p3:
3546 //
3547 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3548 // is either volatile or empty, there exist candidate operator
3549 // functions of the form
3550 //
3551 // VQ T& operator++(VQ T&);
3552 // T operator++(VQ T&, int);
3553 //
3554 // C++ [over.built]p4:
3555 //
3556 // For every pair (T, VQ), where T is an arithmetic type other
3557 // than bool, and VQ is either volatile or empty, there exist
3558 // candidate operator functions of the form
3559 //
3560 // VQ T& operator--(VQ T&);
3561 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003562 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003563 Arith < NumArithmeticTypes; ++Arith) {
3564 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003565 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003566 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003567
3568 // Non-volatile version.
3569 if (NumArgs == 1)
3570 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3571 else
3572 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003573 // heuristic to reduce number of builtin candidates in the set.
3574 // Add volatile version only if there are conversions to a volatile type.
3575 if (VisibleTypeConversionsQuals.hasVolatile()) {
3576 // Volatile version
3577 ParamTypes[0]
3578 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3579 if (NumArgs == 1)
3580 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3581 else
3582 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3583 }
Douglas Gregor74253732008-11-19 15:42:04 +00003584 }
3585
3586 // C++ [over.built]p5:
3587 //
3588 // For every pair (T, VQ), where T is a cv-qualified or
3589 // cv-unqualified object type, and VQ is either volatile or
3590 // empty, there exist candidate operator functions of the form
3591 //
3592 // T*VQ& operator++(T*VQ&);
3593 // T*VQ& operator--(T*VQ&);
3594 // T* operator++(T*VQ&, int);
3595 // T* operator--(T*VQ&, int);
3596 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3597 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3598 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003599 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003600 continue;
3601
Mike Stump1eb44332009-09-09 15:08:12 +00003602 QualType ParamTypes[2] = {
3603 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003604 };
Mike Stump1eb44332009-09-09 15:08:12 +00003605
Douglas Gregor74253732008-11-19 15:42:04 +00003606 // Without volatile
3607 if (NumArgs == 1)
3608 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3609 else
3610 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3611
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003612 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3613 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003614 // With volatile
John McCall0953e762009-09-24 19:53:00 +00003615 ParamTypes[0]
3616 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00003617 if (NumArgs == 1)
3618 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3619 else
3620 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3621 }
3622 }
3623 break;
3624
3625 UnaryStar:
3626 // C++ [over.built]p6:
3627 // For every cv-qualified or cv-unqualified object type T, there
3628 // exist candidate operator functions of the form
3629 //
3630 // T& operator*(T*);
3631 //
3632 // C++ [over.built]p7:
3633 // For every function type T, there exist candidate operator
3634 // functions of the form
3635 // T& operator*(T*);
3636 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3637 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3638 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003639 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003640 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003641 &ParamTy, Args, 1, CandidateSet);
3642 }
3643 break;
3644
3645 UnaryPlus:
3646 // C++ [over.built]p8:
3647 // For every type T, there exist candidate operator functions of
3648 // the form
3649 //
3650 // T* operator+(T*);
3651 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3652 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3653 QualType ParamTy = *Ptr;
3654 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3655 }
Mike Stump1eb44332009-09-09 15:08:12 +00003656
Douglas Gregor74253732008-11-19 15:42:04 +00003657 // Fall through
3658
3659 UnaryMinus:
3660 // C++ [over.built]p9:
3661 // For every promoted arithmetic type T, there exist candidate
3662 // operator functions of the form
3663 //
3664 // T operator+(T);
3665 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003666 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003667 Arith < LastPromotedArithmeticType; ++Arith) {
3668 QualType ArithTy = ArithmeticTypes[Arith];
3669 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3670 }
3671 break;
3672
3673 case OO_Tilde:
3674 // C++ [over.built]p10:
3675 // For every promoted integral type T, there exist candidate
3676 // operator functions of the form
3677 //
3678 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003679 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003680 Int < LastPromotedIntegralType; ++Int) {
3681 QualType IntTy = ArithmeticTypes[Int];
3682 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3683 }
3684 break;
3685
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003686 case OO_New:
3687 case OO_Delete:
3688 case OO_Array_New:
3689 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003690 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003691 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003692 break;
3693
3694 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003695 UnaryAmp:
3696 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003697 // C++ [over.match.oper]p3:
3698 // -- For the operator ',', the unary operator '&', or the
3699 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003700 break;
3701
Douglas Gregor19b7b152009-08-24 13:43:27 +00003702 case OO_EqualEqual:
3703 case OO_ExclaimEqual:
3704 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003705 // For every pointer to member type T, there exist candidate operator
3706 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003707 //
3708 // bool operator==(T,T);
3709 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003710 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003711 MemPtr = CandidateTypes.member_pointer_begin(),
3712 MemPtrEnd = CandidateTypes.member_pointer_end();
3713 MemPtr != MemPtrEnd;
3714 ++MemPtr) {
3715 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3716 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3717 }
Mike Stump1eb44332009-09-09 15:08:12 +00003718
Douglas Gregor19b7b152009-08-24 13:43:27 +00003719 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003720
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003721 case OO_Less:
3722 case OO_Greater:
3723 case OO_LessEqual:
3724 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003725 // C++ [over.built]p15:
3726 //
3727 // For every pointer or enumeration type T, there exist
3728 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003729 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003730 // bool operator<(T, T);
3731 // 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 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3737 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3738 QualType ParamTypes[2] = { *Ptr, *Ptr };
3739 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3740 }
Mike Stump1eb44332009-09-09 15:08:12 +00003741 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003742 = CandidateTypes.enumeration_begin();
3743 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3744 QualType ParamTypes[2] = { *Enum, *Enum };
3745 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3746 }
3747
3748 // Fall through.
3749 isComparison = true;
3750
Douglas Gregor74253732008-11-19 15:42:04 +00003751 BinaryPlus:
3752 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003753 if (!isComparison) {
3754 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3755
3756 // C++ [over.built]p13:
3757 //
3758 // For every cv-qualified or cv-unqualified object type T
3759 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003760 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003761 // T* operator+(T*, ptrdiff_t);
3762 // T& operator[](T*, ptrdiff_t); [BELOW]
3763 // T* operator-(T*, ptrdiff_t);
3764 // T* operator+(ptrdiff_t, T*);
3765 // T& operator[](ptrdiff_t, T*); [BELOW]
3766 //
3767 // C++ [over.built]p14:
3768 //
3769 // For every T, where T is a pointer to object type, there
3770 // exist candidate operator functions of the form
3771 //
3772 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003773 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003774 = CandidateTypes.pointer_begin();
3775 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3776 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3777
3778 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3779 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3780
3781 if (Op == OO_Plus) {
3782 // T* operator+(ptrdiff_t, T*);
3783 ParamTypes[0] = ParamTypes[1];
3784 ParamTypes[1] = *Ptr;
3785 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3786 } else {
3787 // ptrdiff_t operator-(T, T);
3788 ParamTypes[1] = *Ptr;
3789 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3790 Args, 2, CandidateSet);
3791 }
3792 }
3793 }
3794 // Fall through
3795
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003796 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003797 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003798 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003799 // C++ [over.built]p12:
3800 //
3801 // For every pair of promoted arithmetic types L and R, there
3802 // exist candidate operator functions of the form
3803 //
3804 // LR operator*(L, R);
3805 // LR operator/(L, R);
3806 // LR operator+(L, R);
3807 // LR operator-(L, R);
3808 // bool 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 //
3815 // where LR is the result of the usual arithmetic conversions
3816 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003817 //
3818 // C++ [over.built]p24:
3819 //
3820 // For every pair of promoted arithmetic types L and R, there exist
3821 // candidate operator functions of the form
3822 //
3823 // LR operator?(bool, L, R);
3824 //
3825 // where LR is the result of the usual arithmetic conversions
3826 // between types L and R.
3827 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003828 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003829 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003830 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003831 Right < LastPromotedArithmeticType; ++Right) {
3832 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003833 QualType Result
3834 = isComparison
3835 ? Context.BoolTy
3836 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003837 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3838 }
3839 }
3840 break;
3841
3842 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003843 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003844 case OO_Caret:
3845 case OO_Pipe:
3846 case OO_LessLess:
3847 case OO_GreaterGreater:
3848 // C++ [over.built]p17:
3849 //
3850 // For every pair of promoted integral types L and R, there
3851 // exist candidate operator functions of the form
3852 //
3853 // LR operator%(L, R);
3854 // LR operator&(L, R);
3855 // LR operator^(L, R);
3856 // LR operator|(L, R);
3857 // L operator<<(L, R);
3858 // L operator>>(L, R);
3859 //
3860 // where LR is the result of the usual arithmetic conversions
3861 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003862 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003863 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003864 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003865 Right < LastPromotedIntegralType; ++Right) {
3866 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3867 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3868 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003869 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003870 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3871 }
3872 }
3873 break;
3874
3875 case OO_Equal:
3876 // C++ [over.built]p20:
3877 //
3878 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003879 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003880 // empty, there exist candidate operator functions of the form
3881 //
3882 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003883 for (BuiltinCandidateTypeSet::iterator
3884 Enum = CandidateTypes.enumeration_begin(),
3885 EnumEnd = CandidateTypes.enumeration_end();
3886 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003887 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003888 CandidateSet);
3889 for (BuiltinCandidateTypeSet::iterator
3890 MemPtr = CandidateTypes.member_pointer_begin(),
3891 MemPtrEnd = CandidateTypes.member_pointer_end();
3892 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003893 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003894 CandidateSet);
3895 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003896
3897 case OO_PlusEqual:
3898 case OO_MinusEqual:
3899 // C++ [over.built]p19:
3900 //
3901 // For every pair (T, VQ), where T is any type and VQ is either
3902 // volatile or empty, there exist candidate operator functions
3903 // of the form
3904 //
3905 // T*VQ& operator=(T*VQ&, T*);
3906 //
3907 // C++ [over.built]p21:
3908 //
3909 // For every pair (T, VQ), where T is a cv-qualified or
3910 // cv-unqualified object type and VQ is either volatile or
3911 // empty, there exist candidate operator functions of the form
3912 //
3913 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3914 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3915 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3916 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3917 QualType ParamTypes[2];
3918 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3919
3920 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003921 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003922 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3923 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003924
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003925 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3926 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003927 // volatile version
John McCall0953e762009-09-24 19:53:00 +00003928 ParamTypes[0]
3929 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003930 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3931 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003932 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003933 }
3934 // Fall through.
3935
3936 case OO_StarEqual:
3937 case OO_SlashEqual:
3938 // C++ [over.built]p18:
3939 //
3940 // For every triple (L, VQ, R), where L is an arithmetic type,
3941 // VQ is either volatile or empty, and R is a promoted
3942 // arithmetic type, there exist candidate operator functions of
3943 // the form
3944 //
3945 // VQ L& operator=(VQ L&, R);
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 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003951 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003952 Right < LastPromotedArithmeticType; ++Right) {
3953 QualType ParamTypes[2];
3954 ParamTypes[1] = ArithmeticTypes[Right];
3955
3956 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003957 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003958 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3959 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003960
3961 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003962 if (VisibleTypeConversionsQuals.hasVolatile()) {
3963 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3964 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3965 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3966 /*IsAssigmentOperator=*/Op == OO_Equal);
3967 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003968 }
3969 }
3970 break;
3971
3972 case OO_PercentEqual:
3973 case OO_LessLessEqual:
3974 case OO_GreaterGreaterEqual:
3975 case OO_AmpEqual:
3976 case OO_CaretEqual:
3977 case OO_PipeEqual:
3978 // C++ [over.built]p22:
3979 //
3980 // For every triple (L, VQ, R), where L is an integral type, VQ
3981 // is either volatile or empty, and R is a promoted integral
3982 // type, there exist candidate operator functions of the form
3983 //
3984 // VQ L& operator%=(VQ L&, R);
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 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003991 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003992 Right < LastPromotedIntegralType; ++Right) {
3993 QualType ParamTypes[2];
3994 ParamTypes[1] = ArithmeticTypes[Right];
3995
3996 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003997 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003998 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00003999 if (VisibleTypeConversionsQuals.hasVolatile()) {
4000 // Add this built-in operator as a candidate (VQ is 'volatile').
4001 ParamTypes[0] = ArithmeticTypes[Left];
4002 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4003 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4004 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4005 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004006 }
4007 }
4008 break;
4009
Douglas Gregor74253732008-11-19 15:42:04 +00004010 case OO_Exclaim: {
4011 // C++ [over.operator]p23:
4012 //
4013 // There also exist candidate operator functions of the form
4014 //
Mike Stump1eb44332009-09-09 15:08:12 +00004015 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00004016 // bool operator&&(bool, bool); [BELOW]
4017 // bool operator||(bool, bool); [BELOW]
4018 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004019 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4020 /*IsAssignmentOperator=*/false,
4021 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00004022 break;
4023 }
4024
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004025 case OO_AmpAmp:
4026 case OO_PipePipe: {
4027 // C++ [over.operator]p23:
4028 //
4029 // There also exist candidate operator functions of the form
4030 //
Douglas Gregor74253732008-11-19 15:42:04 +00004031 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004032 // bool operator&&(bool, bool);
4033 // bool operator||(bool, bool);
4034 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004035 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4036 /*IsAssignmentOperator=*/false,
4037 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004038 break;
4039 }
4040
4041 case OO_Subscript:
4042 // C++ [over.built]p13:
4043 //
4044 // For every cv-qualified or cv-unqualified object type T there
4045 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004046 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004047 // T* operator+(T*, ptrdiff_t); [ABOVE]
4048 // T& operator[](T*, ptrdiff_t);
4049 // T* operator-(T*, ptrdiff_t); [ABOVE]
4050 // T* operator+(ptrdiff_t, T*); [ABOVE]
4051 // T& operator[](ptrdiff_t, T*);
4052 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4053 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4054 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00004055 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004056 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004057
4058 // T& operator[](T*, ptrdiff_t)
4059 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4060
4061 // T& operator[](ptrdiff_t, T*);
4062 ParamTypes[0] = ParamTypes[1];
4063 ParamTypes[1] = *Ptr;
4064 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4065 }
4066 break;
4067
4068 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004069 // C++ [over.built]p11:
4070 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4071 // C1 is the same type as C2 or is a derived class of C2, T is an object
4072 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4073 // there exist candidate operator functions of the form
4074 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4075 // where CV12 is the union of CV1 and CV2.
4076 {
4077 for (BuiltinCandidateTypeSet::iterator Ptr =
4078 CandidateTypes.pointer_begin();
4079 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4080 QualType C1Ty = (*Ptr);
4081 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004082 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004083 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004084 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004085 if (!isa<RecordType>(C1))
4086 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004087 // heuristic to reduce number of builtin candidates in the set.
4088 // Add volatile/restrict version only if there are conversions to a
4089 // volatile/restrict type.
4090 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4091 continue;
4092 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4093 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004094 }
4095 for (BuiltinCandidateTypeSet::iterator
4096 MemPtr = CandidateTypes.member_pointer_begin(),
4097 MemPtrEnd = CandidateTypes.member_pointer_end();
4098 MemPtr != MemPtrEnd; ++MemPtr) {
4099 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4100 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00004101 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004102 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4103 break;
4104 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4105 // build CV12 T&
4106 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004107 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4108 T.isVolatileQualified())
4109 continue;
4110 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4111 T.isRestrictQualified())
4112 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004113 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004114 QualType ResultTy = Context.getLValueReferenceType(T);
4115 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4116 }
4117 }
4118 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004119 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004120
4121 case OO_Conditional:
4122 // Note that we don't consider the first argument, since it has been
4123 // contextually converted to bool long ago. The candidates below are
4124 // therefore added as binary.
4125 //
4126 // C++ [over.built]p24:
4127 // For every type T, where T is a pointer or pointer-to-member type,
4128 // there exist candidate operator functions of the form
4129 //
4130 // T operator?(bool, T, T);
4131 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004132 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4133 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4134 QualType ParamTypes[2] = { *Ptr, *Ptr };
4135 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4136 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00004137 for (BuiltinCandidateTypeSet::iterator Ptr =
4138 CandidateTypes.member_pointer_begin(),
4139 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4140 QualType ParamTypes[2] = { *Ptr, *Ptr };
4141 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4142 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004143 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004144 }
4145}
4146
Douglas Gregorfa047642009-02-04 00:32:51 +00004147/// \brief Add function candidates found via argument-dependent lookup
4148/// to the set of overloading candidates.
4149///
4150/// This routine performs argument-dependent name lookup based on the
4151/// given function name (which may also be an operator name) and adds
4152/// all of the overload candidates found by ADL to the overload
4153/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004154void
Douglas Gregorfa047642009-02-04 00:32:51 +00004155Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00004156 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00004157 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004158 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004159 OverloadCandidateSet& CandidateSet,
4160 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00004161 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00004162
John McCalla113e722010-01-26 06:04:06 +00004163 // FIXME: This approach for uniquing ADL results (and removing
4164 // redundant candidates from the set) relies on pointer-equality,
4165 // which means we need to key off the canonical decl. However,
4166 // always going back to the canonical decl might not get us the
4167 // right set of default arguments. What default arguments are
4168 // we supposed to consider on ADL candidates, anyway?
4169
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004170 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00004171 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00004172
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004173 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004174 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4175 CandEnd = CandidateSet.end();
4176 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004177 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00004178 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004179 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00004180 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00004181 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004182
4183 // For each of the ADL candidates we found, add it to the overload
4184 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00004185 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00004186 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00004187 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004188 continue;
4189
John McCall86820f52010-01-26 01:37:31 +00004190 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004191 false, false, PartialOverloading);
4192 } else
John McCall6e266892010-01-26 03:27:55 +00004193 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall86820f52010-01-26 01:37:31 +00004194 AS_none, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004195 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004196 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004197}
4198
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004199/// isBetterOverloadCandidate - Determines whether the first overload
4200/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004201bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004202Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump1eb44332009-09-09 15:08:12 +00004203 const OverloadCandidate& Cand2) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004204 // Define viable functions to be better candidates than non-viable
4205 // functions.
4206 if (!Cand2.Viable)
4207 return Cand1.Viable;
4208 else if (!Cand1.Viable)
4209 return false;
4210
Douglas Gregor88a35142008-12-22 05:46:06 +00004211 // C++ [over.match.best]p1:
4212 //
4213 // -- if F is a static member function, ICS1(F) is defined such
4214 // that ICS1(F) is neither better nor worse than ICS1(G) for
4215 // any function G, and, symmetrically, ICS1(G) is neither
4216 // better nor worse than ICS1(F).
4217 unsigned StartArg = 0;
4218 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4219 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004220
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004221 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004222 // A viable function F1 is defined to be a better function than another
4223 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004224 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004225 unsigned NumArgs = Cand1.Conversions.size();
4226 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4227 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004228 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004229 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4230 Cand2.Conversions[ArgIdx])) {
4231 case ImplicitConversionSequence::Better:
4232 // Cand1 has a better conversion sequence.
4233 HasBetterConversion = true;
4234 break;
4235
4236 case ImplicitConversionSequence::Worse:
4237 // Cand1 can't be better than Cand2.
4238 return false;
4239
4240 case ImplicitConversionSequence::Indistinguishable:
4241 // Do nothing.
4242 break;
4243 }
4244 }
4245
Mike Stump1eb44332009-09-09 15:08:12 +00004246 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004247 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004248 if (HasBetterConversion)
4249 return true;
4250
Mike Stump1eb44332009-09-09 15:08:12 +00004251 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004252 // specialization, or, if not that,
4253 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4254 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4255 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004256
4257 // -- F1 and F2 are function template specializations, and the function
4258 // template for F1 is more specialized than the template for F2
4259 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004260 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004261 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4262 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004263 if (FunctionTemplateDecl *BetterTemplate
4264 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4265 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004266 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4267 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004268 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004269
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004270 // -- the context is an initialization by user-defined conversion
4271 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4272 // from the return type of F1 to the destination type (i.e.,
4273 // the type of the entity being initialized) is a better
4274 // conversion sequence than the standard conversion sequence
4275 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004276 if (Cand1.Function && Cand2.Function &&
4277 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004278 isa<CXXConversionDecl>(Cand2.Function)) {
4279 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4280 Cand2.FinalConversion)) {
4281 case ImplicitConversionSequence::Better:
4282 // Cand1 has a better conversion sequence.
4283 return true;
4284
4285 case ImplicitConversionSequence::Worse:
4286 // Cand1 can't be better than Cand2.
4287 return false;
4288
4289 case ImplicitConversionSequence::Indistinguishable:
4290 // Do nothing
4291 break;
4292 }
4293 }
4294
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004295 return false;
4296}
4297
Mike Stump1eb44332009-09-09 15:08:12 +00004298/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004299/// within an overload candidate set.
4300///
4301/// \param CandidateSet the set of candidate functions.
4302///
4303/// \param Loc the location of the function name (or operator symbol) for
4304/// which overload resolution occurs.
4305///
Mike Stump1eb44332009-09-09 15:08:12 +00004306/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004307/// function, Best points to the candidate function found.
4308///
4309/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00004310OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4311 SourceLocation Loc,
4312 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004313 // Find the best viable function.
4314 Best = CandidateSet.end();
4315 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4316 Cand != CandidateSet.end(); ++Cand) {
4317 if (Cand->Viable) {
4318 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4319 Best = Cand;
4320 }
4321 }
4322
4323 // If we didn't find any viable functions, abort.
4324 if (Best == CandidateSet.end())
4325 return OR_No_Viable_Function;
4326
4327 // Make sure that this function is better than every other viable
4328 // function. If not, we have an ambiguity.
4329 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4330 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00004331 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004332 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004333 !isBetterOverloadCandidate(*Best, *Cand)) {
4334 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004335 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004336 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004337 }
Mike Stump1eb44332009-09-09 15:08:12 +00004338
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004339 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004340 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00004341 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004342 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004343 return OR_Deleted;
4344
Douglas Gregore0762c92009-06-19 23:52:42 +00004345 // C++ [basic.def.odr]p2:
4346 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00004347 // when referred to from a potentially-evaluated expression. [Note: this
4348 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00004349 // (clause 13), user-defined conversions (12.3.2), allocation function for
4350 // placement new (5.3.4), as well as non-default initialization (8.5).
4351 if (Best->Function)
4352 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004353 return OR_Success;
4354}
4355
John McCall3c80f572010-01-12 02:15:36 +00004356namespace {
4357
4358enum OverloadCandidateKind {
4359 oc_function,
4360 oc_method,
4361 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004362 oc_function_template,
4363 oc_method_template,
4364 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00004365 oc_implicit_default_constructor,
4366 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004367 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00004368};
4369
John McCall220ccbf2010-01-13 00:25:19 +00004370OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4371 FunctionDecl *Fn,
4372 std::string &Description) {
4373 bool isTemplate = false;
4374
4375 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4376 isTemplate = true;
4377 Description = S.getTemplateArgumentBindingsText(
4378 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4379 }
John McCallb1622a12010-01-06 09:43:14 +00004380
4381 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00004382 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004383 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004384
John McCall3c80f572010-01-12 02:15:36 +00004385 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4386 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004387 }
4388
4389 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4390 // This actually gets spelled 'candidate function' for now, but
4391 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00004392 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004393 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00004394
4395 assert(Meth->isCopyAssignment()
4396 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00004397 return oc_implicit_copy_assignment;
4398 }
4399
John McCall220ccbf2010-01-13 00:25:19 +00004400 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00004401}
4402
4403} // end anonymous namespace
4404
4405// Notes the location of an overload candidate.
4406void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00004407 std::string FnDesc;
4408 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4409 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4410 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00004411}
4412
John McCall1d318332010-01-12 00:44:57 +00004413/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4414/// "lead" diagnostic; it will be given two arguments, the source and
4415/// target types of the conversion.
4416void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4417 SourceLocation CaretLoc,
4418 const PartialDiagnostic &PDiag) {
4419 Diag(CaretLoc, PDiag)
4420 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4421 for (AmbiguousConversionSequence::const_iterator
4422 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4423 NoteOverloadCandidate(*I);
4424 }
John McCall81201622010-01-08 04:41:39 +00004425}
4426
John McCall1d318332010-01-12 00:44:57 +00004427namespace {
4428
John McCalladbb8f82010-01-13 09:16:55 +00004429void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4430 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4431 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00004432 assert(Cand->Function && "for now, candidate must be a function");
4433 FunctionDecl *Fn = Cand->Function;
4434
4435 // There's a conversion slot for the object argument if this is a
4436 // non-constructor method. Note that 'I' corresponds the
4437 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00004438 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00004439 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00004440 if (I == 0)
4441 isObjectArgument = true;
4442 else
4443 I--;
John McCall220ccbf2010-01-13 00:25:19 +00004444 }
4445
John McCall220ccbf2010-01-13 00:25:19 +00004446 std::string FnDesc;
4447 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4448
John McCalladbb8f82010-01-13 09:16:55 +00004449 Expr *FromExpr = Conv.Bad.FromExpr;
4450 QualType FromTy = Conv.Bad.getFromType();
4451 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00004452
John McCall258b2032010-01-23 08:10:49 +00004453 // Do some hand-waving analysis to see if the non-viability is due
4454 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00004455 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4456 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4457 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4458 CToTy = RT->getPointeeType();
4459 else {
4460 // TODO: detect and diagnose the full richness of const mismatches.
4461 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4462 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4463 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4464 }
4465
4466 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4467 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4468 // It is dumb that we have to do this here.
4469 while (isa<ArrayType>(CFromTy))
4470 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4471 while (isa<ArrayType>(CToTy))
4472 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4473
4474 Qualifiers FromQs = CFromTy.getQualifiers();
4475 Qualifiers ToQs = CToTy.getQualifiers();
4476
4477 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4478 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4479 << (unsigned) FnKind << FnDesc
4480 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4481 << FromTy
4482 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4483 << (unsigned) isObjectArgument << I+1;
4484 return;
4485 }
4486
4487 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4488 assert(CVR && "unexpected qualifiers mismatch");
4489
4490 if (isObjectArgument) {
4491 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4492 << (unsigned) FnKind << FnDesc
4493 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4494 << FromTy << (CVR - 1);
4495 } else {
4496 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4497 << (unsigned) FnKind << FnDesc
4498 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4499 << FromTy << (CVR - 1) << I+1;
4500 }
4501 return;
4502 }
4503
John McCall258b2032010-01-23 08:10:49 +00004504 // Diagnose references or pointers to incomplete types differently,
4505 // since it's far from impossible that the incompleteness triggered
4506 // the failure.
4507 QualType TempFromTy = FromTy.getNonReferenceType();
4508 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4509 TempFromTy = PTy->getPointeeType();
4510 if (TempFromTy->isIncompleteType()) {
4511 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4512 << (unsigned) FnKind << FnDesc
4513 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4514 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4515 return;
4516 }
4517
John McCall651f3ee2010-01-14 03:28:57 +00004518 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00004519 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4520 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00004521 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00004522 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00004523}
4524
4525void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4526 unsigned NumFormalArgs) {
4527 // TODO: treat calls to a missing default constructor as a special case
4528
4529 FunctionDecl *Fn = Cand->Function;
4530 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4531
4532 unsigned MinParams = Fn->getMinRequiredArguments();
4533
4534 // at least / at most / exactly
4535 unsigned mode, modeCount;
4536 if (NumFormalArgs < MinParams) {
4537 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4538 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4539 mode = 0; // "at least"
4540 else
4541 mode = 2; // "exactly"
4542 modeCount = MinParams;
4543 } else {
4544 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4545 if (MinParams != FnTy->getNumArgs())
4546 mode = 1; // "at most"
4547 else
4548 mode = 2; // "exactly"
4549 modeCount = FnTy->getNumArgs();
4550 }
4551
4552 std::string Description;
4553 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4554
4555 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4556 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00004557}
4558
4559void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4560 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00004561 FunctionDecl *Fn = Cand->Function;
4562
John McCall81201622010-01-08 04:41:39 +00004563 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00004564 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00004565 std::string FnDesc;
4566 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00004567
4568 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00004569 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00004570 return;
John McCall81201622010-01-08 04:41:39 +00004571 }
4572
John McCall220ccbf2010-01-13 00:25:19 +00004573 // We don't really have anything else to say about viable candidates.
4574 if (Cand->Viable) {
4575 S.NoteOverloadCandidate(Fn);
4576 return;
4577 }
John McCall1d318332010-01-12 00:44:57 +00004578
John McCalladbb8f82010-01-13 09:16:55 +00004579 switch (Cand->FailureKind) {
4580 case ovl_fail_too_many_arguments:
4581 case ovl_fail_too_few_arguments:
4582 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00004583
John McCalladbb8f82010-01-13 09:16:55 +00004584 case ovl_fail_bad_deduction:
John McCall717e8912010-01-23 05:17:32 +00004585 case ovl_fail_trivial_conversion:
4586 case ovl_fail_bad_final_conversion:
John McCalladbb8f82010-01-13 09:16:55 +00004587 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00004588
John McCalladbb8f82010-01-13 09:16:55 +00004589 case ovl_fail_bad_conversion:
4590 for (unsigned I = 0, N = Cand->Conversions.size(); I != N; ++I)
4591 if (Cand->Conversions[I].isBad())
4592 return DiagnoseBadConversion(S, Cand, I);
4593
4594 // FIXME: this currently happens when we're called from SemaInit
4595 // when user-conversion overload fails. Figure out how to handle
4596 // those conditions and diagnose them well.
4597 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00004598 }
John McCalla1d7d622010-01-08 00:58:21 +00004599}
4600
4601void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4602 // Desugar the type of the surrogate down to a function type,
4603 // retaining as many typedefs as possible while still showing
4604 // the function type (and, therefore, its parameter types).
4605 QualType FnType = Cand->Surrogate->getConversionType();
4606 bool isLValueReference = false;
4607 bool isRValueReference = false;
4608 bool isPointer = false;
4609 if (const LValueReferenceType *FnTypeRef =
4610 FnType->getAs<LValueReferenceType>()) {
4611 FnType = FnTypeRef->getPointeeType();
4612 isLValueReference = true;
4613 } else if (const RValueReferenceType *FnTypeRef =
4614 FnType->getAs<RValueReferenceType>()) {
4615 FnType = FnTypeRef->getPointeeType();
4616 isRValueReference = true;
4617 }
4618 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4619 FnType = FnTypePtr->getPointeeType();
4620 isPointer = true;
4621 }
4622 // Desugar down to a function type.
4623 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4624 // Reconstruct the pointer/reference as appropriate.
4625 if (isPointer) FnType = S.Context.getPointerType(FnType);
4626 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4627 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4628
4629 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4630 << FnType;
4631}
4632
4633void NoteBuiltinOperatorCandidate(Sema &S,
4634 const char *Opc,
4635 SourceLocation OpLoc,
4636 OverloadCandidate *Cand) {
4637 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4638 std::string TypeStr("operator");
4639 TypeStr += Opc;
4640 TypeStr += "(";
4641 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4642 if (Cand->Conversions.size() == 1) {
4643 TypeStr += ")";
4644 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4645 } else {
4646 TypeStr += ", ";
4647 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4648 TypeStr += ")";
4649 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4650 }
4651}
4652
4653void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4654 OverloadCandidate *Cand) {
4655 unsigned NoOperands = Cand->Conversions.size();
4656 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4657 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00004658 if (ICS.isBad()) break; // all meaningless after first invalid
4659 if (!ICS.isAmbiguous()) continue;
4660
4661 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4662 PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00004663 }
4664}
4665
John McCall1b77e732010-01-15 23:32:50 +00004666SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4667 if (Cand->Function)
4668 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00004669 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00004670 return Cand->Surrogate->getLocation();
4671 return SourceLocation();
4672}
4673
John McCallbf65c0b2010-01-12 00:48:53 +00004674struct CompareOverloadCandidatesForDisplay {
4675 Sema &S;
4676 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00004677
4678 bool operator()(const OverloadCandidate *L,
4679 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00004680 // Fast-path this check.
4681 if (L == R) return false;
4682
John McCall81201622010-01-08 04:41:39 +00004683 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00004684 if (L->Viable) {
4685 if (!R->Viable) return true;
4686
4687 // TODO: introduce a tri-valued comparison for overload
4688 // candidates. Would be more worthwhile if we had a sort
4689 // that could exploit it.
4690 if (S.isBetterOverloadCandidate(*L, *R)) return true;
4691 if (S.isBetterOverloadCandidate(*R, *L)) return false;
4692 } else if (R->Viable)
4693 return false;
John McCall81201622010-01-08 04:41:39 +00004694
John McCall1b77e732010-01-15 23:32:50 +00004695 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00004696
John McCall1b77e732010-01-15 23:32:50 +00004697 // Criteria by which we can sort non-viable candidates:
4698 if (!L->Viable) {
4699 // 1. Arity mismatches come after other candidates.
4700 if (L->FailureKind == ovl_fail_too_many_arguments ||
4701 L->FailureKind == ovl_fail_too_few_arguments)
4702 return false;
4703 if (R->FailureKind == ovl_fail_too_many_arguments ||
4704 R->FailureKind == ovl_fail_too_few_arguments)
4705 return true;
John McCall81201622010-01-08 04:41:39 +00004706
John McCall717e8912010-01-23 05:17:32 +00004707 // 2. Bad conversions come first and are ordered by the number
4708 // of bad conversions and quality of good conversions.
4709 if (L->FailureKind == ovl_fail_bad_conversion) {
4710 if (R->FailureKind != ovl_fail_bad_conversion)
4711 return true;
4712
4713 // If there's any ordering between the defined conversions...
4714 // FIXME: this might not be transitive.
4715 assert(L->Conversions.size() == R->Conversions.size());
4716
4717 int leftBetter = 0;
4718 for (unsigned I = 0, E = L->Conversions.size(); I != E; ++I) {
4719 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
4720 R->Conversions[I])) {
4721 case ImplicitConversionSequence::Better:
4722 leftBetter++;
4723 break;
4724
4725 case ImplicitConversionSequence::Worse:
4726 leftBetter--;
4727 break;
4728
4729 case ImplicitConversionSequence::Indistinguishable:
4730 break;
4731 }
4732 }
4733 if (leftBetter > 0) return true;
4734 if (leftBetter < 0) return false;
4735
4736 } else if (R->FailureKind == ovl_fail_bad_conversion)
4737 return false;
4738
John McCall1b77e732010-01-15 23:32:50 +00004739 // TODO: others?
4740 }
4741
4742 // Sort everything else by location.
4743 SourceLocation LLoc = GetLocationForCandidate(L);
4744 SourceLocation RLoc = GetLocationForCandidate(R);
4745
4746 // Put candidates without locations (e.g. builtins) at the end.
4747 if (LLoc.isInvalid()) return false;
4748 if (RLoc.isInvalid()) return true;
4749
4750 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00004751 }
4752};
4753
John McCall717e8912010-01-23 05:17:32 +00004754/// CompleteNonViableCandidate - Normally, overload resolution only
4755/// computes up to the first
4756void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
4757 Expr **Args, unsigned NumArgs) {
4758 assert(!Cand->Viable);
4759
4760 // Don't do anything on failures other than bad conversion.
4761 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
4762
4763 // Skip forward to the first bad conversion.
4764 unsigned ConvIdx = 0;
4765 unsigned ConvCount = Cand->Conversions.size();
4766 while (true) {
4767 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
4768 ConvIdx++;
4769 if (Cand->Conversions[ConvIdx - 1].isBad())
4770 break;
4771 }
4772
4773 if (ConvIdx == ConvCount)
4774 return;
4775
4776 // FIXME: these should probably be preserved from the overload
4777 // operation somehow.
4778 bool SuppressUserConversions = false;
4779 bool ForceRValue = false;
4780
4781 const FunctionProtoType* Proto;
4782 unsigned ArgIdx = ConvIdx;
4783
4784 if (Cand->IsSurrogate) {
4785 QualType ConvType
4786 = Cand->Surrogate->getConversionType().getNonReferenceType();
4787 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4788 ConvType = ConvPtrType->getPointeeType();
4789 Proto = ConvType->getAs<FunctionProtoType>();
4790 ArgIdx--;
4791 } else if (Cand->Function) {
4792 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
4793 if (isa<CXXMethodDecl>(Cand->Function) &&
4794 !isa<CXXConstructorDecl>(Cand->Function))
4795 ArgIdx--;
4796 } else {
4797 // Builtin binary operator with a bad first conversion.
4798 assert(ConvCount <= 3);
4799 for (; ConvIdx != ConvCount; ++ConvIdx)
4800 Cand->Conversions[ConvIdx]
4801 = S.TryCopyInitialization(Args[ConvIdx],
4802 Cand->BuiltinTypes.ParamTypes[ConvIdx],
4803 SuppressUserConversions, ForceRValue,
4804 /*InOverloadResolution*/ true);
4805 return;
4806 }
4807
4808 // Fill in the rest of the conversions.
4809 unsigned NumArgsInProto = Proto->getNumArgs();
4810 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
4811 if (ArgIdx < NumArgsInProto)
4812 Cand->Conversions[ConvIdx]
4813 = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx),
4814 SuppressUserConversions, ForceRValue,
4815 /*InOverloadResolution=*/true);
4816 else
4817 Cand->Conversions[ConvIdx].setEllipsis();
4818 }
4819}
4820
John McCalla1d7d622010-01-08 00:58:21 +00004821} // end anonymous namespace
4822
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004823/// PrintOverloadCandidates - When overload resolution fails, prints
4824/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00004825/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00004826void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004827Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00004828 OverloadCandidateDisplayKind OCD,
John McCallcbce6062010-01-12 07:18:19 +00004829 Expr **Args, unsigned NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004830 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004831 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00004832 // Sort the candidates by viability and position. Sorting directly would
4833 // be prohibitive, so we make a set of pointers and sort those.
4834 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4835 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4836 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4837 LastCand = CandidateSet.end();
John McCall717e8912010-01-23 05:17:32 +00004838 Cand != LastCand; ++Cand) {
4839 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00004840 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00004841 else if (OCD == OCD_AllCandidates) {
4842 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
4843 Cands.push_back(Cand);
4844 }
4845 }
4846
John McCallbf65c0b2010-01-12 00:48:53 +00004847 std::sort(Cands.begin(), Cands.end(),
4848 CompareOverloadCandidatesForDisplay(*this));
John McCall81201622010-01-08 04:41:39 +00004849
John McCall1d318332010-01-12 00:44:57 +00004850 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00004851
John McCall81201622010-01-08 04:41:39 +00004852 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4853 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4854 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00004855
John McCalla1d7d622010-01-08 00:58:21 +00004856 if (Cand->Function)
John McCall220ccbf2010-01-13 00:25:19 +00004857 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00004858 else if (Cand->IsSurrogate)
4859 NoteSurrogateCandidate(*this, Cand);
4860
4861 // This a builtin candidate. We do not, in general, want to list
4862 // every possible builtin candidate.
John McCall1d318332010-01-12 00:44:57 +00004863 else if (Cand->Viable) {
4864 // Generally we only see ambiguities including viable builtin
4865 // operators if overload resolution got screwed up by an
4866 // ambiguous user-defined conversion.
4867 //
4868 // FIXME: It's quite possible for different conversions to see
4869 // different ambiguities, though.
4870 if (!ReportedAmbiguousConversions) {
4871 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4872 ReportedAmbiguousConversions = true;
4873 }
John McCalla1d7d622010-01-08 00:58:21 +00004874
John McCall1d318332010-01-12 00:44:57 +00004875 // If this is a viable builtin, print it.
John McCalla1d7d622010-01-08 00:58:21 +00004876 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004877 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004878 }
4879}
4880
John McCallc373d482010-01-27 01:50:18 +00004881static bool CheckUnresolvedAccess(Sema &S, Expr *E, NamedDecl *D,
4882 AccessSpecifier AS) {
4883 if (isa<UnresolvedLookupExpr>(E))
4884 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D, AS);
4885
4886 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D, AS);
4887}
4888
Douglas Gregor904eed32008-11-10 20:40:00 +00004889/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4890/// an overloaded function (C++ [over.over]), where @p From is an
4891/// expression with overloaded function type and @p ToType is the type
4892/// we're trying to resolve to. For example:
4893///
4894/// @code
4895/// int f(double);
4896/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00004897///
Douglas Gregor904eed32008-11-10 20:40:00 +00004898/// int (*pfd)(double) = f; // selects f(double)
4899/// @endcode
4900///
4901/// This routine returns the resulting FunctionDecl if it could be
4902/// resolved, and NULL otherwise. When @p Complain is true, this
4903/// routine will emit diagnostics if there is an error.
4904FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00004905Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004906 bool Complain) {
4907 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00004908 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00004909 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00004910 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004911 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00004912 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00004913 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00004914 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004915 FunctionType = MemTypePtr->getPointeeType();
4916 IsMember = true;
4917 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004918
4919 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00004920 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00004921 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00004922 return 0;
4923
4924 // Find the actual overloaded function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004925
Douglas Gregor904eed32008-11-10 20:40:00 +00004926 // C++ [over.over]p1:
4927 // [...] [Note: any redundant set of parentheses surrounding the
4928 // overloaded function name is ignored (5.1). ]
4929 Expr *OvlExpr = From->IgnoreParens();
4930
4931 // C++ [over.over]p1:
4932 // [...] The overloaded function name can be preceded by the &
4933 // operator.
4934 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4935 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4936 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4937 }
4938
Anders Carlsson70534852009-10-20 22:53:47 +00004939 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004940 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall75345162010-01-26 07:37:41 +00004941 const UnresolvedSetImpl *Fns;
Anders Carlsson70534852009-10-20 22:53:47 +00004942
John McCall129e2df2009-11-30 22:42:35 +00004943 // Look into the overloaded expression.
John McCallf7a1a742009-11-24 19:00:30 +00004944 if (UnresolvedLookupExpr *UL
John McCallba135432009-11-21 08:51:07 +00004945 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
John McCall75345162010-01-26 07:37:41 +00004946 Fns = &UL->getDecls();
John McCallf7a1a742009-11-24 19:00:30 +00004947 if (UL->hasExplicitTemplateArgs()) {
4948 HasExplicitTemplateArgs = true;
4949 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4950 }
John McCall129e2df2009-11-30 22:42:35 +00004951 } else if (UnresolvedMemberExpr *ME
4952 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
John McCall75345162010-01-26 07:37:41 +00004953 Fns = &ME->getDecls();
John McCall129e2df2009-11-30 22:42:35 +00004954 if (ME->hasExplicitTemplateArgs()) {
4955 HasExplicitTemplateArgs = true;
John McCalld5532b62009-11-23 01:53:49 +00004956 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004957 }
John McCall75345162010-01-26 07:37:41 +00004958 } else return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004959
John McCallba135432009-11-21 08:51:07 +00004960 // If we didn't actually find anything, we're done.
John McCall75345162010-01-26 07:37:41 +00004961 if (Fns->empty())
John McCallba135432009-11-21 08:51:07 +00004962 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004963
Douglas Gregor904eed32008-11-10 20:40:00 +00004964 // Look through all of the overloaded functions, searching for one
4965 // whose type matches exactly.
John McCallc373d482010-01-27 01:50:18 +00004966 UnresolvedSet<4> Matches; // contains only FunctionDecls
Douglas Gregor00aeb522009-07-08 23:33:52 +00004967 bool FoundNonTemplateFunction = false;
John McCall75345162010-01-26 07:37:41 +00004968 for (UnresolvedSetIterator I = Fns->begin(), E = Fns->end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00004969 // Look through any using declarations to find the underlying function.
4970 NamedDecl *Fn = (*I)->getUnderlyingDecl();
4971
Douglas Gregor904eed32008-11-10 20:40:00 +00004972 // C++ [over.over]p3:
4973 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00004974 // targets of type "pointer-to-function" or "reference-to-function."
4975 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00004976 // type "pointer-to-member-function."
4977 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00004978
Mike Stump1eb44332009-09-09 15:08:12 +00004979 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00004980 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004981 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00004982 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004983 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00004984 // static when converting to member pointer.
4985 if (Method->isStatic() == IsMember)
4986 continue;
4987 } else if (IsMember)
4988 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00004989
Douglas Gregor00aeb522009-07-08 23:33:52 +00004990 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004991 // If the name is a function template, template argument deduction is
4992 // done (14.8.2.2), and if the argument deduction succeeds, the
4993 // resulting template argument list is used to generate a single
4994 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00004995 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004996 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00004997 FunctionDecl *Specialization = 0;
4998 TemplateDeductionInfo Info(Context);
4999 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00005000 = DeduceTemplateArguments(FunctionTemplate,
5001 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor83314aa2009-07-08 20:55:45 +00005002 FunctionType, Specialization, Info)) {
5003 // FIXME: make a note of the failed deduction for diagnostics.
5004 (void)Result;
5005 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005006 // FIXME: If the match isn't exact, shouldn't we just drop this as
5007 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00005008 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00005009 == Context.getCanonicalType(Specialization->getType()));
John McCallc373d482010-01-27 01:50:18 +00005010 Matches.addDecl(cast<FunctionDecl>(Specialization->getCanonicalDecl()),
5011 I.getAccess());
Douglas Gregor83314aa2009-07-08 20:55:45 +00005012 }
John McCallba135432009-11-21 08:51:07 +00005013
5014 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00005015 }
Mike Stump1eb44332009-09-09 15:08:12 +00005016
Chandler Carruthbd647292009-12-29 06:17:27 +00005017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00005018 // Skip non-static functions when converting to pointer, and static
5019 // when converting to member pointer.
5020 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00005021 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005022
5023 // If we have explicit template arguments, skip non-templates.
5024 if (HasExplicitTemplateArgs)
5025 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00005026 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00005027 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00005028
Chandler Carruthbd647292009-12-29 06:17:27 +00005029 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00005030 QualType ResultTy;
5031 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5032 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5033 ResultTy)) {
John McCallc373d482010-01-27 01:50:18 +00005034 Matches.addDecl(cast<FunctionDecl>(FunDecl->getCanonicalDecl()),
5035 I.getAccess());
Douglas Gregor00aeb522009-07-08 23:33:52 +00005036 FoundNonTemplateFunction = true;
5037 }
Mike Stump1eb44332009-09-09 15:08:12 +00005038 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005039 }
5040
Douglas Gregor00aeb522009-07-08 23:33:52 +00005041 // If there were 0 or 1 matches, we're done.
5042 if (Matches.empty())
5043 return 0;
Sebastian Redl07ab2022009-10-17 21:12:09 +00005044 else if (Matches.size() == 1) {
John McCallc373d482010-01-27 01:50:18 +00005045 FunctionDecl *Result = cast<FunctionDecl>(*Matches.begin());
Sebastian Redl07ab2022009-10-17 21:12:09 +00005046 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00005047 if (Complain)
5048 CheckUnresolvedAccess(*this, OvlExpr, Result, Matches.begin().getAccess());
Sebastian Redl07ab2022009-10-17 21:12:09 +00005049 return Result;
5050 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00005051
5052 // C++ [over.over]p4:
5053 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00005054 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005055 // [...] and any given function template specialization F1 is
5056 // eliminated if the set contains a second function template
5057 // specialization whose function template is more specialized
5058 // than the function template of F1 according to the partial
5059 // ordering rules of 14.5.5.2.
5060
5061 // The algorithm specified above is quadratic. We instead use a
5062 // two-pass algorithm (similar to the one used to identify the
5063 // best viable function in an overload set) that identifies the
5064 // best function template (if it exists).
John McCallc373d482010-01-27 01:50:18 +00005065
5066 UnresolvedSetIterator Result =
5067 getMostSpecialized(Matches.begin(), Matches.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00005068 TPOC_Other, From->getLocStart(),
5069 PDiag(),
5070 PDiag(diag::err_addr_ovl_ambiguous)
John McCallc373d482010-01-27 01:50:18 +00005071 << Matches[0]->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00005072 PDiag(diag::note_ovl_candidate)
5073 << (unsigned) oc_function_template);
John McCallc373d482010-01-27 01:50:18 +00005074 assert(Result != Matches.end() && "no most-specialized template");
5075 MarkDeclarationReferenced(From->getLocStart(), *Result);
5076 if (Complain)
5077 CheckUnresolvedAccess(*this, OvlExpr, *Result, Result.getAccess());
5078 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00005079 }
Mike Stump1eb44332009-09-09 15:08:12 +00005080
Douglas Gregor312a2022009-09-26 03:56:17 +00005081 // [...] any function template specializations in the set are
5082 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00005083 for (unsigned I = 0, N = Matches.size(); I != N; ) {
5084 if (cast<FunctionDecl>(Matches[I].getDecl())->getPrimaryTemplate() == 0)
5085 ++I;
5086 else {
5087 Matches.erase(I);
5088 --N;
5089 }
5090 }
Douglas Gregor312a2022009-09-26 03:56:17 +00005091
Mike Stump1eb44332009-09-09 15:08:12 +00005092 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00005093 // selected function.
John McCallc373d482010-01-27 01:50:18 +00005094 if (Matches.size() == 1) {
5095 UnresolvedSetIterator Match = Matches.begin();
5096 MarkDeclarationReferenced(From->getLocStart(), *Match);
5097 if (Complain)
5098 CheckUnresolvedAccess(*this, OvlExpr, *Match, Match.getAccess());
5099 return cast<FunctionDecl>(*Match);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005100 }
Mike Stump1eb44332009-09-09 15:08:12 +00005101
Douglas Gregor00aeb522009-07-08 23:33:52 +00005102 // FIXME: We should probably return the same thing that BestViableFunction
5103 // returns (even if we issue the diagnostics here).
5104 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCallc373d482010-01-27 01:50:18 +00005105 << Matches[0]->getDeclName();
5106 for (UnresolvedSetIterator I = Matches.begin(),
5107 E = Matches.end(); I != E; ++I)
5108 NoteOverloadCandidate(cast<FunctionDecl>(*I));
Douglas Gregor904eed32008-11-10 20:40:00 +00005109 return 0;
5110}
5111
Douglas Gregor4b52e252009-12-21 23:17:24 +00005112/// \brief Given an expression that refers to an overloaded function, try to
5113/// resolve that overloaded function expression down to a single function.
5114///
5115/// This routine can only resolve template-ids that refer to a single function
5116/// template, where that template-id refers to a single template whose template
5117/// arguments are either provided by the template-id or have defaults,
5118/// as described in C++0x [temp.arg.explicit]p3.
5119FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5120 // C++ [over.over]p1:
5121 // [...] [Note: any redundant set of parentheses surrounding the
5122 // overloaded function name is ignored (5.1). ]
5123 Expr *OvlExpr = From->IgnoreParens();
5124
5125 // C++ [over.over]p1:
5126 // [...] The overloaded function name can be preceded by the &
5127 // operator.
5128 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
5129 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
5130 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
5131 }
5132
5133 bool HasExplicitTemplateArgs = false;
5134 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall75345162010-01-26 07:37:41 +00005135 const UnresolvedSetImpl *Fns;
Douglas Gregor4b52e252009-12-21 23:17:24 +00005136
5137 // Look into the overloaded expression.
5138 if (UnresolvedLookupExpr *UL
5139 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
John McCall75345162010-01-26 07:37:41 +00005140 Fns = &UL->getDecls();
Douglas Gregor4b52e252009-12-21 23:17:24 +00005141 if (UL->hasExplicitTemplateArgs()) {
5142 HasExplicitTemplateArgs = true;
5143 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
5144 }
5145 } else if (UnresolvedMemberExpr *ME
5146 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
John McCall75345162010-01-26 07:37:41 +00005147 Fns = &ME->getDecls();
Douglas Gregor4b52e252009-12-21 23:17:24 +00005148 if (ME->hasExplicitTemplateArgs()) {
5149 HasExplicitTemplateArgs = true;
5150 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
5151 }
John McCall75345162010-01-26 07:37:41 +00005152 } else return 0;
Douglas Gregor4b52e252009-12-21 23:17:24 +00005153
5154 // If we didn't actually find any template-ids, we're done.
John McCall75345162010-01-26 07:37:41 +00005155 if (Fns->empty() || !HasExplicitTemplateArgs)
Douglas Gregor4b52e252009-12-21 23:17:24 +00005156 return 0;
5157
5158 // Look through all of the overloaded functions, searching for one
5159 // whose type matches exactly.
5160 FunctionDecl *Matched = 0;
John McCall75345162010-01-26 07:37:41 +00005161 for (UnresolvedSetIterator I = Fns->begin(), E = Fns->end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00005162 // C++0x [temp.arg.explicit]p3:
5163 // [...] In contexts where deduction is done and fails, or in contexts
5164 // where deduction is not done, if a template argument list is
5165 // specified and it, along with any default template arguments,
5166 // identifies a single function template specialization, then the
5167 // template-id is an lvalue for the function template specialization.
5168 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5169
5170 // C++ [over.over]p2:
5171 // If the name is a function template, template argument deduction is
5172 // done (14.8.2.2), and if the argument deduction succeeds, the
5173 // resulting template argument list is used to generate a single
5174 // function template specialization, which is added to the set of
5175 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00005176 FunctionDecl *Specialization = 0;
5177 TemplateDeductionInfo Info(Context);
5178 if (TemplateDeductionResult Result
5179 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5180 Specialization, Info)) {
5181 // FIXME: make a note of the failed deduction for diagnostics.
5182 (void)Result;
5183 continue;
5184 }
5185
5186 // Multiple matches; we can't resolve to a single declaration.
5187 if (Matched)
5188 return 0;
5189
5190 Matched = Specialization;
5191 }
5192
5193 return Matched;
5194}
5195
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005196/// \brief Add a single candidate to the overload set.
5197static void AddOverloadedCallCandidate(Sema &S,
John McCallba135432009-11-21 08:51:07 +00005198 NamedDecl *Callee,
John McCall86820f52010-01-26 01:37:31 +00005199 AccessSpecifier Access,
John McCalld5532b62009-11-23 01:53:49 +00005200 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005201 Expr **Args, unsigned NumArgs,
5202 OverloadCandidateSet &CandidateSet,
5203 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00005204 if (isa<UsingShadowDecl>(Callee))
5205 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5206
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005207 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00005208 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall86820f52010-01-26 01:37:31 +00005209 S.AddOverloadCandidate(Func, Access, Args, NumArgs, CandidateSet,
5210 false, false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005211 return;
John McCallba135432009-11-21 08:51:07 +00005212 }
5213
5214 if (FunctionTemplateDecl *FuncTemplate
5215 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall86820f52010-01-26 01:37:31 +00005216 S.AddTemplateOverloadCandidate(FuncTemplate, Access, ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005217 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00005218 return;
5219 }
5220
5221 assert(false && "unhandled case in overloaded call candidate");
5222
5223 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005224}
5225
5226/// \brief Add the overload candidates named by callee and/or found by argument
5227/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00005228void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
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
5233#ifndef NDEBUG
5234 // Verify that ArgumentDependentLookup is consistent with the rules
5235 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005236 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005237 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5238 // and let Y be the lookup set produced by argument dependent
5239 // lookup (defined as follows). If X contains
5240 //
5241 // -- a declaration of a class member, or
5242 //
5243 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00005244 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005245 //
5246 // -- a declaration that is neither a function or a function
5247 // template
5248 //
5249 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00005250
John McCall3b4294e2009-12-16 12:17:52 +00005251 if (ULE->requiresADL()) {
5252 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5253 E = ULE->decls_end(); I != E; ++I) {
5254 assert(!(*I)->getDeclContext()->isRecord());
5255 assert(isa<UsingShadowDecl>(*I) ||
5256 !(*I)->getDeclContext()->isFunctionOrMethod());
5257 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00005258 }
5259 }
5260#endif
5261
John McCall3b4294e2009-12-16 12:17:52 +00005262 // It would be nice to avoid this copy.
5263 TemplateArgumentListInfo TABuffer;
5264 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5265 if (ULE->hasExplicitTemplateArgs()) {
5266 ULE->copyTemplateArgumentsInto(TABuffer);
5267 ExplicitTemplateArgs = &TABuffer;
5268 }
5269
5270 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5271 E = ULE->decls_end(); I != E; ++I)
John McCall86820f52010-01-26 01:37:31 +00005272 AddOverloadedCallCandidate(*this, *I, I.getAccess(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005273 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005274 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00005275
John McCall3b4294e2009-12-16 12:17:52 +00005276 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00005277 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5278 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005279 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005280 CandidateSet,
5281 PartialOverloading);
5282}
John McCall578b69b2009-12-16 08:11:27 +00005283
John McCall3b4294e2009-12-16 12:17:52 +00005284static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5285 Expr **Args, unsigned NumArgs) {
5286 Fn->Destroy(SemaRef.Context);
5287 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5288 Args[Arg]->Destroy(SemaRef.Context);
5289 return SemaRef.ExprError();
5290}
5291
John McCall578b69b2009-12-16 08:11:27 +00005292/// Attempts to recover from a call where no functions were found.
5293///
5294/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00005295static Sema::OwningExprResult
5296BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5297 UnresolvedLookupExpr *ULE,
5298 SourceLocation LParenLoc,
5299 Expr **Args, unsigned NumArgs,
5300 SourceLocation *CommaLocs,
5301 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00005302
5303 CXXScopeSpec SS;
5304 if (ULE->getQualifier()) {
5305 SS.setScopeRep(ULE->getQualifier());
5306 SS.setRange(ULE->getQualifierRange());
5307 }
5308
John McCall3b4294e2009-12-16 12:17:52 +00005309 TemplateArgumentListInfo TABuffer;
5310 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5311 if (ULE->hasExplicitTemplateArgs()) {
5312 ULE->copyTemplateArgumentsInto(TABuffer);
5313 ExplicitTemplateArgs = &TABuffer;
5314 }
5315
John McCall578b69b2009-12-16 08:11:27 +00005316 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5317 Sema::LookupOrdinaryName);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00005318 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall3b4294e2009-12-16 12:17:52 +00005319 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCall578b69b2009-12-16 08:11:27 +00005320
John McCall3b4294e2009-12-16 12:17:52 +00005321 assert(!R.empty() && "lookup results empty despite recovery");
5322
5323 // Build an implicit member call if appropriate. Just drop the
5324 // casts and such from the call, we don't really care.
5325 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5326 if ((*R.begin())->isCXXClassMember())
5327 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5328 else if (ExplicitTemplateArgs)
5329 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5330 else
5331 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5332
5333 if (NewFn.isInvalid())
5334 return Destroy(SemaRef, Fn, Args, NumArgs);
5335
5336 Fn->Destroy(SemaRef.Context);
5337
5338 // This shouldn't cause an infinite loop because we're giving it
5339 // an expression with non-empty lookup results, which should never
5340 // end up here.
5341 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5342 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5343 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00005344}
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005345
Douglas Gregorf6b89692008-11-26 05:54:23 +00005346/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00005347/// (which eventually refers to the declaration Func) and the call
5348/// arguments Args/NumArgs, attempt to resolve the function call down
5349/// to a specific function. If overload resolution succeeds, returns
5350/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00005351/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00005352/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00005353Sema::OwningExprResult
5354Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5355 SourceLocation LParenLoc,
5356 Expr **Args, unsigned NumArgs,
5357 SourceLocation *CommaLocs,
5358 SourceLocation RParenLoc) {
5359#ifndef NDEBUG
5360 if (ULE->requiresADL()) {
5361 // To do ADL, we must have found an unqualified name.
5362 assert(!ULE->getQualifier() && "qualified name with ADL");
5363
5364 // We don't perform ADL for implicit declarations of builtins.
5365 // Verify that this was correctly set up.
5366 FunctionDecl *F;
5367 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5368 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5369 F->getBuiltinID() && F->isImplicit())
5370 assert(0 && "performing ADL for builtin");
5371
5372 // We don't perform ADL in C.
5373 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5374 }
5375#endif
5376
Douglas Gregorf6b89692008-11-26 05:54:23 +00005377 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00005378
John McCall3b4294e2009-12-16 12:17:52 +00005379 // Add the functions denoted by the callee to the set of candidate
5380 // functions, including those from argument-dependent lookup.
5381 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00005382
5383 // If we found nothing, try to recover.
5384 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5385 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00005386 if (CandidateSet.empty())
5387 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5388 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00005389
Douglas Gregorf6b89692008-11-26 05:54:23 +00005390 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005391 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00005392 case OR_Success: {
5393 FunctionDecl *FDecl = Best->Function;
John McCallc373d482010-01-27 01:50:18 +00005394 CheckUnresolvedLookupAccess(ULE, FDecl, Best->getAccess());
John McCall3b4294e2009-12-16 12:17:52 +00005395 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5396 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5397 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00005398
5399 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00005400 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00005401 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00005402 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005403 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005404 break;
5405
5406 case OR_Ambiguous:
5407 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00005408 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005409 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005410 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005411
5412 case OR_Deleted:
5413 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5414 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00005415 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005416 << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005417 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005418 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00005419 }
5420
5421 // Overload resolution failed. Destroy all of the subexpressions and
5422 // return NULL.
5423 Fn->Destroy(Context);
5424 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5425 Args[Arg]->Destroy(Context);
John McCall3b4294e2009-12-16 12:17:52 +00005426 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00005427}
5428
John McCall6e266892010-01-26 03:27:55 +00005429static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00005430 return Functions.size() > 1 ||
5431 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5432}
5433
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005434/// \brief Create a unary operation that may resolve to an overloaded
5435/// operator.
5436///
5437/// \param OpLoc The location of the operator itself (e.g., '*').
5438///
5439/// \param OpcIn The UnaryOperator::Opcode that describes this
5440/// operator.
5441///
5442/// \param Functions The set of non-member functions that will be
5443/// considered by overload resolution. The caller needs to build this
5444/// set based on the context using, e.g.,
5445/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5446/// set should not contain any member functions; those will be added
5447/// by CreateOverloadedUnaryOp().
5448///
5449/// \param input The input argument.
John McCall6e266892010-01-26 03:27:55 +00005450Sema::OwningExprResult
5451Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5452 const UnresolvedSetImpl &Fns,
5453 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005454 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5455 Expr *Input = (Expr *)input.get();
5456
5457 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5458 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5459 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5460
5461 Expr *Args[2] = { Input, 0 };
5462 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00005463
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005464 // For post-increment and post-decrement, add the implicit '0' as
5465 // the second argument, so that we know this is a post-increment or
5466 // post-decrement.
5467 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5468 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00005469 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005470 SourceLocation());
5471 NumArgs = 2;
5472 }
5473
5474 if (Input->isTypeDependent()) {
John McCallc373d482010-01-27 01:50:18 +00005475 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005476 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005477 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005478 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00005479 /*ADL*/ true, IsOverloaded(Fns));
5480 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump1eb44332009-09-09 15:08:12 +00005481
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005482 input.release();
5483 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5484 &Args[0], NumArgs,
5485 Context.DependentTy,
5486 OpLoc));
5487 }
5488
5489 // Build an empty overload set.
5490 OverloadCandidateSet CandidateSet;
5491
5492 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00005493 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005494
5495 // Add operator candidates that are member functions.
5496 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5497
John McCall6e266892010-01-26 03:27:55 +00005498 // Add candidates from ADL.
5499 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5500 Args, 1,
5501 /*ExplicitTemplateArgs*/ 0,
5502 CandidateSet);
5503
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005504 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005505 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005506
5507 // Perform overload resolution.
5508 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005509 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005510 case OR_Success: {
5511 // We found a built-in operator or an overloaded operator.
5512 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00005513
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005514 if (FnDecl) {
5515 // We matched an overloaded operator. Build a call to that
5516 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00005517
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005518 // Convert the arguments.
5519 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00005520 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5521
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005522 if (PerformObjectArgumentInitialization(Input, Method))
5523 return ExprError();
5524 } else {
5525 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00005526 OwningExprResult InputInit
5527 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005528 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00005529 SourceLocation(),
5530 move(input));
5531 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005532 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005533
Douglas Gregore1a5c172009-12-23 17:40:29 +00005534 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005535 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005536 }
5537
5538 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00005539 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005540
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005541 // Build the actual expression node.
5542 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5543 SourceLocation());
5544 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00005545
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005546 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00005547 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00005548 ExprOwningPtr<CallExpr> TheCall(this,
5549 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00005550 Args, NumArgs, ResultTy, OpLoc));
Anders Carlsson26a2a072009-10-13 21:19:37 +00005551
5552 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5553 FnDecl))
5554 return ExprError();
5555
5556 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005557 } else {
5558 // We matched a built-in operator. Convert the arguments, then
5559 // break out so that we will build the appropriate built-in
5560 // operator node.
5561 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005562 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005563 return ExprError();
5564
5565 break;
5566 }
5567 }
5568
5569 case OR_No_Viable_Function:
5570 // No viable function; fall through to handling this as a
5571 // built-in operator, which will produce an error message for us.
5572 break;
5573
5574 case OR_Ambiguous:
5575 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5576 << UnaryOperator::getOpcodeStr(Opc)
5577 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005578 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005579 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005580 return ExprError();
5581
5582 case OR_Deleted:
5583 Diag(OpLoc, diag::err_ovl_deleted_oper)
5584 << Best->Function->isDeleted()
5585 << UnaryOperator::getOpcodeStr(Opc)
5586 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005587 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005588 return ExprError();
5589 }
5590
5591 // Either we found no viable overloaded operator or we matched a
5592 // built-in operator. In either case, fall through to trying to
5593 // build a built-in operation.
5594 input.release();
5595 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5596}
5597
Douglas Gregor063daf62009-03-13 18:40:31 +00005598/// \brief Create a binary operation that may resolve to an overloaded
5599/// operator.
5600///
5601/// \param OpLoc The location of the operator itself (e.g., '+').
5602///
5603/// \param OpcIn The BinaryOperator::Opcode that describes this
5604/// operator.
5605///
5606/// \param Functions The set of non-member functions that will be
5607/// considered by overload resolution. The caller needs to build this
5608/// set based on the context using, e.g.,
5609/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5610/// set should not contain any member functions; those will be added
5611/// by CreateOverloadedBinOp().
5612///
5613/// \param LHS Left-hand argument.
5614/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005615Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00005616Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005617 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00005618 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00005619 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00005620 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005621 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00005622
5623 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5624 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5625 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5626
5627 // If either side is type-dependent, create an appropriate dependent
5628 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005629 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00005630 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005631 // If there are no functions to store, just build a dependent
5632 // BinaryOperator or CompoundAssignment.
5633 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5634 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5635 Context.DependentTy, OpLoc));
5636
5637 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5638 Context.DependentTy,
5639 Context.DependentTy,
5640 Context.DependentTy,
5641 OpLoc));
5642 }
John McCall6e266892010-01-26 03:27:55 +00005643
5644 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00005645 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005646 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005647 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005648 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00005649 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump1eb44332009-09-09 15:08:12 +00005650
John McCall6e266892010-01-26 03:27:55 +00005651 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00005652 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00005653 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00005654 Context.DependentTy,
5655 OpLoc));
5656 }
5657
5658 // If this is the .* operator, which is not overloadable, just
5659 // create a built-in binary operator.
5660 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005661 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005662
Sebastian Redl275c2b42009-11-18 23:10:33 +00005663 // If this is the assignment operator, we only perform overload resolution
5664 // if the left-hand side is a class or enumeration type. This is actually
5665 // a hack. The standard requires that we do overload resolution between the
5666 // various built-in candidates, but as DR507 points out, this can lead to
5667 // problems. So we do it this way, which pretty much follows what GCC does.
5668 // Note that we go the traditional code path for compound assignment forms.
5669 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005670 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005671
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005672 // Build an empty overload set.
5673 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00005674
5675 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00005676 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00005677
5678 // Add operator candidates that are member functions.
5679 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5680
John McCall6e266892010-01-26 03:27:55 +00005681 // Add candidates from ADL.
5682 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5683 Args, 2,
5684 /*ExplicitTemplateArgs*/ 0,
5685 CandidateSet);
5686
Douglas Gregor063daf62009-03-13 18:40:31 +00005687 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005688 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00005689
5690 // Perform overload resolution.
5691 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005692 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005693 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00005694 // We found a built-in operator or an overloaded operator.
5695 FunctionDecl *FnDecl = Best->Function;
5696
5697 if (FnDecl) {
5698 // We matched an overloaded operator. Build a call to that
5699 // operator.
5700
5701 // Convert the arguments.
5702 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00005703 // Best->Access is only meaningful for class members.
5704 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5705
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005706 OwningExprResult Arg1
5707 = PerformCopyInitialization(
5708 InitializedEntity::InitializeParameter(
5709 FnDecl->getParamDecl(0)),
5710 SourceLocation(),
5711 Owned(Args[1]));
5712 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00005713 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005714
5715 if (PerformObjectArgumentInitialization(Args[0], Method))
5716 return ExprError();
5717
5718 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00005719 } else {
5720 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005721 OwningExprResult Arg0
5722 = PerformCopyInitialization(
5723 InitializedEntity::InitializeParameter(
5724 FnDecl->getParamDecl(0)),
5725 SourceLocation(),
5726 Owned(Args[0]));
5727 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00005728 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005729
5730 OwningExprResult Arg1
5731 = PerformCopyInitialization(
5732 InitializedEntity::InitializeParameter(
5733 FnDecl->getParamDecl(1)),
5734 SourceLocation(),
5735 Owned(Args[1]));
5736 if (Arg1.isInvalid())
5737 return ExprError();
5738 Args[0] = LHS = Arg0.takeAs<Expr>();
5739 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00005740 }
5741
5742 // Determine the result type
5743 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00005744 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00005745 ResultTy = ResultTy.getNonReferenceType();
5746
5747 // Build the actual expression node.
5748 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00005749 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005750 UsualUnaryConversions(FnExpr);
5751
Anders Carlsson15ea3782009-10-13 22:43:21 +00005752 ExprOwningPtr<CXXOperatorCallExpr>
5753 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5754 Args, 2, ResultTy,
5755 OpLoc));
5756
5757 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5758 FnDecl))
5759 return ExprError();
5760
5761 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00005762 } else {
5763 // We matched a built-in operator. Convert the arguments, then
5764 // break out so that we will build the appropriate built-in
5765 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005766 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005767 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005768 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005769 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00005770 return ExprError();
5771
5772 break;
5773 }
5774 }
5775
Douglas Gregor33074752009-09-30 21:46:01 +00005776 case OR_No_Viable_Function: {
5777 // C++ [over.match.oper]p9:
5778 // If the operator is the operator , [...] and there are no
5779 // viable functions, then the operator is assumed to be the
5780 // built-in operator and interpreted according to clause 5.
5781 if (Opc == BinaryOperator::Comma)
5782 break;
5783
Sebastian Redl8593c782009-05-21 11:50:50 +00005784 // For class as left operand for assignment or compound assigment operator
5785 // do not fall through to handling in built-in, but report that no overloaded
5786 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00005787 OwningExprResult Result = ExprError();
5788 if (Args[0]->getType()->isRecordType() &&
5789 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00005790 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5791 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005792 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00005793 } else {
5794 // No viable function; try to create a built-in operation, which will
5795 // produce an error. Then, show the non-viable candidates.
5796 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00005797 }
Douglas Gregor33074752009-09-30 21:46:01 +00005798 assert(Result.isInvalid() &&
5799 "C++ binary operator overloading is missing candidates!");
5800 if (Result.isInvalid())
John McCallcbce6062010-01-12 07:18:19 +00005801 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005802 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00005803 return move(Result);
5804 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005805
5806 case OR_Ambiguous:
5807 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5808 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005809 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005810 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005811 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005812 return ExprError();
5813
5814 case OR_Deleted:
5815 Diag(OpLoc, diag::err_ovl_deleted_oper)
5816 << Best->Function->isDeleted()
5817 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005818 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005819 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00005820 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00005821 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005822
Douglas Gregor33074752009-09-30 21:46:01 +00005823 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005824 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005825}
5826
Sebastian Redlf322ed62009-10-29 20:17:01 +00005827Action::OwningExprResult
5828Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5829 SourceLocation RLoc,
5830 ExprArg Base, ExprArg Idx) {
5831 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5832 static_cast<Expr*>(Idx.get()) };
5833 DeclarationName OpName =
5834 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5835
5836 // If either side is type-dependent, create an appropriate dependent
5837 // expression.
5838 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5839
John McCallc373d482010-01-27 01:50:18 +00005840 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005841 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005842 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005843 0, SourceRange(), OpName, LLoc,
John McCall7453ed42009-11-22 00:44:51 +00005844 /*ADL*/ true, /*Overloaded*/ false);
John McCallf7a1a742009-11-24 19:00:30 +00005845 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00005846
5847 Base.release();
5848 Idx.release();
5849 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5850 Args, 2,
5851 Context.DependentTy,
5852 RLoc));
5853 }
5854
5855 // Build an empty overload set.
5856 OverloadCandidateSet CandidateSet;
5857
5858 // Subscript can only be overloaded as a member function.
5859
5860 // Add operator candidates that are member functions.
5861 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5862
5863 // Add builtin operator candidates.
5864 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5865
5866 // Perform overload resolution.
5867 OverloadCandidateSet::iterator Best;
5868 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5869 case OR_Success: {
5870 // We found a built-in operator or an overloaded operator.
5871 FunctionDecl *FnDecl = Best->Function;
5872
5873 if (FnDecl) {
5874 // We matched an overloaded operator. Build a call to that
5875 // operator.
5876
John McCall5357b612010-01-28 01:42:12 +00005877 CheckMemberOperatorAccess(LLoc, Args[0], FnDecl, Best->getAccess());
John McCallc373d482010-01-27 01:50:18 +00005878
Sebastian Redlf322ed62009-10-29 20:17:01 +00005879 // Convert the arguments.
5880 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5881 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5882 PerformCopyInitialization(Args[1],
5883 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +00005884 AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005885 return ExprError();
5886
5887 // Determine the result type
5888 QualType ResultTy
5889 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5890 ResultTy = ResultTy.getNonReferenceType();
5891
5892 // Build the actual expression node.
5893 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5894 LLoc);
5895 UsualUnaryConversions(FnExpr);
5896
5897 Base.release();
5898 Idx.release();
5899 ExprOwningPtr<CXXOperatorCallExpr>
5900 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5901 FnExpr, Args, 2,
5902 ResultTy, RLoc));
5903
5904 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5905 FnDecl))
5906 return ExprError();
5907
5908 return MaybeBindToTemporary(TheCall.release());
5909 } else {
5910 // We matched a built-in operator. Convert the arguments, then
5911 // break out so that we will build the appropriate built-in
5912 // operator node.
5913 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005914 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00005915 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005916 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005917 return ExprError();
5918
5919 break;
5920 }
5921 }
5922
5923 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00005924 if (CandidateSet.empty())
5925 Diag(LLoc, diag::err_ovl_no_oper)
5926 << Args[0]->getType() << /*subscript*/ 0
5927 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5928 else
5929 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5930 << Args[0]->getType()
5931 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005932 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall1eb3e102010-01-07 02:04:15 +00005933 "[]", LLoc);
5934 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00005935 }
5936
5937 case OR_Ambiguous:
5938 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5939 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005940 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redlf322ed62009-10-29 20:17:01 +00005941 "[]", LLoc);
5942 return ExprError();
5943
5944 case OR_Deleted:
5945 Diag(LLoc, diag::err_ovl_deleted_oper)
5946 << Best->Function->isDeleted() << "[]"
5947 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005948 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall81201622010-01-08 04:41:39 +00005949 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00005950 return ExprError();
5951 }
5952
5953 // We matched a built-in operator; build it.
5954 Base.release();
5955 Idx.release();
5956 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5957 Owned(Args[1]), RLoc);
5958}
5959
Douglas Gregor88a35142008-12-22 05:46:06 +00005960/// BuildCallToMemberFunction - Build a call to a member
5961/// function. MemExpr is the expression that refers to the member
5962/// function (and includes the object parameter), Args/NumArgs are the
5963/// arguments to the function call (not including the object
5964/// parameter). The caller needs to validate that the member
5965/// expression refers to a member function or an overloaded member
5966/// function.
John McCallaa81e162009-12-01 22:10:20 +00005967Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00005968Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5969 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00005970 unsigned NumArgs, SourceLocation *CommaLocs,
5971 SourceLocation RParenLoc) {
5972 // Dig out the member expression. This holds both the object
5973 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00005974 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5975
John McCall129e2df2009-11-30 22:42:35 +00005976 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00005977 CXXMethodDecl *Method = 0;
John McCall129e2df2009-11-30 22:42:35 +00005978 if (isa<MemberExpr>(NakedMemExpr)) {
5979 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00005980 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5981 } else {
5982 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCallaa81e162009-12-01 22:10:20 +00005983
John McCall701c89e2009-12-03 04:06:58 +00005984 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00005985
Douglas Gregor88a35142008-12-22 05:46:06 +00005986 // Add overload candidates
5987 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00005988
John McCallaa81e162009-12-01 22:10:20 +00005989 // FIXME: avoid copy.
5990 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5991 if (UnresExpr->hasExplicitTemplateArgs()) {
5992 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5993 TemplateArgs = &TemplateArgsBuffer;
5994 }
5995
John McCall129e2df2009-11-30 22:42:35 +00005996 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5997 E = UnresExpr->decls_end(); I != E; ++I) {
5998
John McCall701c89e2009-12-03 04:06:58 +00005999 NamedDecl *Func = *I;
6000 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6001 if (isa<UsingShadowDecl>(Func))
6002 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6003
John McCall129e2df2009-11-30 22:42:35 +00006004 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006005 // If explicit template arguments were provided, we can't call a
6006 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00006007 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006008 continue;
6009
John McCall86820f52010-01-26 01:37:31 +00006010 AddMethodCandidate(Method, I.getAccess(), ActingDC, ObjectType,
6011 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00006012 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006013 } else {
John McCall129e2df2009-11-30 22:42:35 +00006014 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall86820f52010-01-26 01:37:31 +00006015 I.getAccess(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00006016 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00006017 CandidateSet,
6018 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006019 }
Douglas Gregordec06662009-08-21 18:42:58 +00006020 }
Mike Stump1eb44332009-09-09 15:08:12 +00006021
John McCall129e2df2009-11-30 22:42:35 +00006022 DeclarationName DeclName = UnresExpr->getMemberName();
6023
Douglas Gregor88a35142008-12-22 05:46:06 +00006024 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00006025 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00006026 case OR_Success:
6027 Method = cast<CXXMethodDecl>(Best->Function);
John McCallc373d482010-01-27 01:50:18 +00006028 CheckUnresolvedMemberAccess(UnresExpr, Method, Best->getAccess());
Douglas Gregor88a35142008-12-22 05:46:06 +00006029 break;
6030
6031 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00006032 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00006033 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006034 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006035 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006036 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006037 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006038
6039 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00006040 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006041 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006042 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006043 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006044 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006045
6046 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00006047 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006048 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00006049 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006050 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006051 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006052 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006053 }
6054
Douglas Gregor699ee522009-11-20 19:42:02 +00006055 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCallaa81e162009-12-01 22:10:20 +00006056
John McCallaa81e162009-12-01 22:10:20 +00006057 // If overload resolution picked a static member, build a
6058 // non-member call based on that function.
6059 if (Method->isStatic()) {
6060 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6061 Args, NumArgs, RParenLoc);
6062 }
6063
John McCall129e2df2009-11-30 22:42:35 +00006064 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00006065 }
6066
6067 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00006068 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00006069 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00006070 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006071 Method->getResultType().getNonReferenceType(),
6072 RParenLoc));
6073
Anders Carlssoneed3e692009-10-10 00:06:20 +00006074 // Check for a valid return type.
6075 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6076 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00006077 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00006078
Douglas Gregor88a35142008-12-22 05:46:06 +00006079 // Convert the object argument (for a non-static member function call).
John McCallaa81e162009-12-01 22:10:20 +00006080 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00006081 if (!Method->isStatic() &&
Douglas Gregor88a35142008-12-22 05:46:06 +00006082 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCallaa81e162009-12-01 22:10:20 +00006083 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006084 MemExpr->setBase(ObjectArg);
6085
6086 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00006087 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00006088 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006089 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00006090 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006091
Anders Carlssond406bf02009-08-16 01:56:34 +00006092 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00006093 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00006094
John McCallaa81e162009-12-01 22:10:20 +00006095 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00006096}
6097
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006098/// BuildCallToObjectOfClassType - Build a call to an object of class
6099/// type (C++ [over.call.object]), which can end up invoking an
6100/// overloaded function call operator (@c operator()) or performing a
6101/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006102Sema::ExprResult
6103Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00006104 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006105 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00006106 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006107 SourceLocation RParenLoc) {
6108 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00006109 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006110
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006111 // C++ [over.call.object]p1:
6112 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00006113 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006114 // candidate functions includes at least the function call
6115 // operators of T. The function call operators of T are obtained by
6116 // ordinary lookup of the name operator() in the context of
6117 // (E).operator().
6118 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00006119 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00006120
6121 if (RequireCompleteType(LParenLoc, Object->getType(),
6122 PartialDiagnostic(diag::err_incomplete_object_call)
6123 << Object->getSourceRange()))
6124 return true;
6125
John McCalla24dc2e2009-11-17 02:14:36 +00006126 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6127 LookupQualifiedName(R, Record->getDecl());
6128 R.suppressDiagnostics();
6129
Douglas Gregor593564b2009-11-15 07:48:03 +00006130 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00006131 Oper != OperEnd; ++Oper) {
John McCall86820f52010-01-26 01:37:31 +00006132 AddMethodCandidate(*Oper, Oper.getAccess(), Object->getType(),
6133 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006134 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00006135 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00006136
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006137 // C++ [over.call.object]p2:
6138 // In addition, for each conversion function declared in T of the
6139 // form
6140 //
6141 // operator conversion-type-id () cv-qualifier;
6142 //
6143 // where cv-qualifier is the same cv-qualification as, or a
6144 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00006145 // denotes the type "pointer to function of (P1,...,Pn) returning
6146 // R", or the type "reference to pointer to function of
6147 // (P1,...,Pn) returning R", or the type "reference to function
6148 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006149 // is also considered as a candidate function. Similarly,
6150 // surrogate call functions are added to the set of candidate
6151 // functions for each conversion function declared in an
6152 // accessible base class provided the function is not hidden
6153 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00006154 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00006155 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00006156 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006157 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00006158 NamedDecl *D = *I;
6159 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6160 if (isa<UsingShadowDecl>(D))
6161 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6162
Douglas Gregor4a27d702009-10-21 06:18:39 +00006163 // Skip over templated conversion functions; they aren't
6164 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00006165 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00006166 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006167
John McCall701c89e2009-12-03 04:06:58 +00006168 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00006169
Douglas Gregor4a27d702009-10-21 06:18:39 +00006170 // Strip the reference type (if any) and then the pointer type (if
6171 // any) to get down to what might be a function type.
6172 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6173 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6174 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006175
Douglas Gregor4a27d702009-10-21 06:18:39 +00006176 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall86820f52010-01-26 01:37:31 +00006177 AddSurrogateCandidate(Conv, I.getAccess(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00006178 Object->getType(), Args, NumArgs,
6179 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006180 }
Mike Stump1eb44332009-09-09 15:08:12 +00006181
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006182 // Perform overload resolution.
6183 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006184 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006185 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006186 // Overload resolution succeeded; we'll build the appropriate call
6187 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006188 break;
6189
6190 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00006191 if (CandidateSet.empty())
6192 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6193 << Object->getType() << /*call*/ 1
6194 << Object->getSourceRange();
6195 else
6196 Diag(Object->getSourceRange().getBegin(),
6197 diag::err_ovl_no_viable_object_call)
6198 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006199 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006200 break;
6201
6202 case OR_Ambiguous:
6203 Diag(Object->getSourceRange().getBegin(),
6204 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00006205 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006206 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006207 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006208
6209 case OR_Deleted:
6210 Diag(Object->getSourceRange().getBegin(),
6211 diag::err_ovl_deleted_object_call)
6212 << Best->Function->isDeleted()
6213 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006214 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006215 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006216 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006217
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006218 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006219 // We had an error; delete all of the subexpressions and return
6220 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006221 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006222 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00006223 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006224 return true;
6225 }
6226
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006227 if (Best->Function == 0) {
6228 // Since there is no function declaration, this is one of the
6229 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00006230 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006231 = cast<CXXConversionDecl>(
6232 Best->Conversions[0].UserDefined.ConversionFunction);
6233
John McCall233a6412010-01-28 07:38:46 +00006234 CheckMemberOperatorAccess(LParenLoc, Object, Conv, Best->getAccess());
John McCall41d89032010-01-28 01:54:34 +00006235
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006236 // We selected one of the surrogate functions that converts the
6237 // object parameter to a function pointer. Perform the conversion
6238 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006239
6240 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006241 // and then call it.
Eli Friedmanc8c771e2009-12-09 04:52:43 +00006242 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006243
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006244 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00006245 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6246 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006247 }
6248
John McCall233a6412010-01-28 07:38:46 +00006249 CheckMemberOperatorAccess(LParenLoc, Object,
6250 Best->Function, Best->getAccess());
John McCall41d89032010-01-28 01:54:34 +00006251
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006252 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6253 // that calls this method, using Object for the implicit object
6254 // parameter and passing along the remaining arguments.
6255 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00006256 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006257
6258 unsigned NumArgsInProto = Proto->getNumArgs();
6259 unsigned NumArgsToCheck = NumArgs;
6260
6261 // Build the full argument list for the method call (the
6262 // implicit object parameter is placed at the beginning of the
6263 // list).
6264 Expr **MethodArgs;
6265 if (NumArgs < NumArgsInProto) {
6266 NumArgsToCheck = NumArgsInProto;
6267 MethodArgs = new Expr*[NumArgsInProto + 1];
6268 } else {
6269 MethodArgs = new Expr*[NumArgs + 1];
6270 }
6271 MethodArgs[0] = Object;
6272 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6273 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00006274
6275 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00006276 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006277 UsualUnaryConversions(NewFn);
6278
6279 // Once we've built TheCall, all of the expressions are properly
6280 // owned.
6281 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00006282 ExprOwningPtr<CXXOperatorCallExpr>
6283 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00006284 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00006285 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006286 delete [] MethodArgs;
6287
Anders Carlsson07d68f12009-10-13 21:49:31 +00006288 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6289 Method))
6290 return true;
6291
Douglas Gregor518fda12009-01-13 05:10:00 +00006292 // We may have default arguments. If so, we need to allocate more
6293 // slots in the call for them.
6294 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00006295 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00006296 else if (NumArgs > NumArgsInProto)
6297 NumArgsToCheck = NumArgsInProto;
6298
Chris Lattner312531a2009-04-12 08:11:20 +00006299 bool IsError = false;
6300
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006301 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00006302 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006303 TheCall->setArg(0, Object);
6304
Chris Lattner312531a2009-04-12 08:11:20 +00006305
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006306 // Check the argument types.
6307 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006308 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00006309 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006310 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00006311
Douglas Gregor518fda12009-01-13 05:10:00 +00006312 // Pass the argument.
6313 QualType ProtoArgType = Proto->getArgType(i);
Douglas Gregor68647482009-12-16 03:45:30 +00006314 IsError |= PerformCopyInitialization(Arg, ProtoArgType, AA_Passing);
Douglas Gregor518fda12009-01-13 05:10:00 +00006315 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00006316 OwningExprResult DefArg
6317 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6318 if (DefArg.isInvalid()) {
6319 IsError = true;
6320 break;
6321 }
6322
6323 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00006324 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006325
6326 TheCall->setArg(i + 1, Arg);
6327 }
6328
6329 // If this is a variadic call, handle args passed through "...".
6330 if (Proto->isVariadic()) {
6331 // Promote the arguments (C99 6.5.2.2p7).
6332 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6333 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00006334 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006335 TheCall->setArg(i + 1, Arg);
6336 }
6337 }
6338
Chris Lattner312531a2009-04-12 08:11:20 +00006339 if (IsError) return true;
6340
Anders Carlssond406bf02009-08-16 01:56:34 +00006341 if (CheckFunctionCall(Method, TheCall.get()))
6342 return true;
6343
Anders Carlssona303f9e2009-08-16 03:53:54 +00006344 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006345}
6346
Douglas Gregor8ba10742008-11-20 16:27:02 +00006347/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00006348/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00006349/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006350Sema::OwningExprResult
6351Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6352 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00006353 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00006354
Douglas Gregor8ba10742008-11-20 16:27:02 +00006355 // C++ [over.ref]p1:
6356 //
6357 // [...] An expression x->m is interpreted as (x.operator->())->m
6358 // for a class object x of type T if T::operator->() exists and if
6359 // the operator is selected as the best match function by the
6360 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00006361 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
6362 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00006363 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006364
Eli Friedmanf43fb722009-11-18 01:28:03 +00006365 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
6366 PDiag(diag::err_typecheck_incomplete_tag)
6367 << Base->getSourceRange()))
6368 return ExprError();
6369
John McCalla24dc2e2009-11-17 02:14:36 +00006370 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6371 LookupQualifiedName(R, BaseRecord->getDecl());
6372 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00006373
6374 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00006375 Oper != OperEnd; ++Oper) {
6376 NamedDecl *D = *Oper;
6377 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6378 if (isa<UsingShadowDecl>(D))
6379 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6380
John McCall86820f52010-01-26 01:37:31 +00006381 AddMethodCandidate(cast<CXXMethodDecl>(D), Oper.getAccess(), ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00006382 Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00006383 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00006384 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00006385
6386 // Perform overload resolution.
6387 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006388 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00006389 case OR_Success:
6390 // Overload resolution succeeded; we'll build the call below.
6391 break;
6392
6393 case OR_No_Viable_Function:
6394 if (CandidateSet.empty())
6395 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006396 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006397 else
6398 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006399 << "operator->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006400 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006401 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006402
6403 case OR_Ambiguous:
6404 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00006405 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006406 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006407 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006408
6409 case OR_Deleted:
6410 Diag(OpLoc, diag::err_ovl_deleted_oper)
6411 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00006412 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006413 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006414 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006415 }
6416
6417 // Convert the object parameter.
6418 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00006419 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006420 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00006421
6422 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006423 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006424
6425 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006426 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6427 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00006428 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00006429
6430 QualType ResultTy = Method->getResultType().getNonReferenceType();
6431 ExprOwningPtr<CXXOperatorCallExpr>
6432 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6433 &Base, 1, ResultTy, OpLoc));
6434
6435 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6436 Method))
6437 return ExprError();
6438 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00006439}
6440
Douglas Gregor904eed32008-11-10 20:40:00 +00006441/// FixOverloadedFunctionReference - E is an expression that refers to
6442/// a C++ overloaded function (possibly with some parentheses and
6443/// perhaps a '&' around it). We have resolved the overloaded function
6444/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00006445/// refer (possibly indirectly) to Fn. Returns the new expr.
6446Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006447 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor699ee522009-11-20 19:42:02 +00006448 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6449 if (SubExpr == PE->getSubExpr())
6450 return PE->Retain();
6451
6452 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6453 }
6454
6455 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6456 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00006457 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00006458 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00006459 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00006460 if (SubExpr == ICE->getSubExpr())
6461 return ICE->Retain();
6462
6463 return new (Context) ImplicitCastExpr(ICE->getType(),
6464 ICE->getCastKind(),
6465 SubExpr,
6466 ICE->isLvalueCast());
6467 }
6468
6469 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006470 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00006471 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00006472 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6473 if (Method->isStatic()) {
6474 // Do nothing: static member functions aren't any different
6475 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00006476 } else {
John McCallf7a1a742009-11-24 19:00:30 +00006477 // Fix the sub expression, which really has to be an
6478 // UnresolvedLookupExpr holding an overloaded member function
6479 // or template.
John McCallba135432009-11-21 08:51:07 +00006480 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6481 if (SubExpr == UnOp->getSubExpr())
6482 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00006483
John McCallba135432009-11-21 08:51:07 +00006484 assert(isa<DeclRefExpr>(SubExpr)
6485 && "fixed to something other than a decl ref");
6486 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6487 && "fixed to a member ref with no nested name qualifier");
6488
6489 // We have taken the address of a pointer to member
6490 // function. Perform the computation here so that we get the
6491 // appropriate pointer to member type.
6492 QualType ClassType
6493 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6494 QualType MemPtrType
6495 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6496
6497 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6498 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00006499 }
6500 }
Douglas Gregor699ee522009-11-20 19:42:02 +00006501 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6502 if (SubExpr == UnOp->getSubExpr())
6503 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00006504
Douglas Gregor699ee522009-11-20 19:42:02 +00006505 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6506 Context.getPointerType(SubExpr->getType()),
6507 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00006508 }
John McCallba135432009-11-21 08:51:07 +00006509
6510 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00006511 // FIXME: avoid copy.
6512 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00006513 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00006514 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6515 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00006516 }
6517
John McCallba135432009-11-21 08:51:07 +00006518 return DeclRefExpr::Create(Context,
6519 ULE->getQualifier(),
6520 ULE->getQualifierRange(),
6521 Fn,
6522 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006523 Fn->getType(),
6524 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00006525 }
6526
John McCall129e2df2009-11-30 22:42:35 +00006527 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00006528 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00006529 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6530 if (MemExpr->hasExplicitTemplateArgs()) {
6531 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6532 TemplateArgs = &TemplateArgsBuffer;
6533 }
John McCalld5532b62009-11-23 01:53:49 +00006534
John McCallaa81e162009-12-01 22:10:20 +00006535 Expr *Base;
6536
6537 // If we're filling in
6538 if (MemExpr->isImplicitAccess()) {
6539 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6540 return DeclRefExpr::Create(Context,
6541 MemExpr->getQualifier(),
6542 MemExpr->getQualifierRange(),
6543 Fn,
6544 MemExpr->getMemberLoc(),
6545 Fn->getType(),
6546 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00006547 } else {
6548 SourceLocation Loc = MemExpr->getMemberLoc();
6549 if (MemExpr->getQualifier())
6550 Loc = MemExpr->getQualifierRange().getBegin();
6551 Base = new (Context) CXXThisExpr(Loc,
6552 MemExpr->getBaseType(),
6553 /*isImplicit=*/true);
6554 }
John McCallaa81e162009-12-01 22:10:20 +00006555 } else
6556 Base = MemExpr->getBase()->Retain();
6557
6558 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00006559 MemExpr->isArrow(),
6560 MemExpr->getQualifier(),
6561 MemExpr->getQualifierRange(),
6562 Fn,
John McCalld5532b62009-11-23 01:53:49 +00006563 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006564 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00006565 Fn->getType());
6566 }
6567
Douglas Gregor699ee522009-11-20 19:42:02 +00006568 assert(false && "Invalid reference to overloaded function");
6569 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00006570}
6571
Douglas Gregor20093b42009-12-09 23:02:17 +00006572Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6573 FunctionDecl *Fn) {
6574 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6575}
6576
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006577} // end namespace clang