blob: a58b33f97f21a2457149cc0c984359a2fa499df3 [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor5251f1b2008-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 Gregor40cb9ad2009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000082 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +000083 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084 };
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 Lopescfca1f02009-12-23 17:49:57 +000091 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor26bee0b2008-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;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000121 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000126}
127
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-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 Gregor3edc4d52010-01-27 03:51:04 +0000151 if (getToType(1)->isBooleanType() &&
John McCall0d1da222010-01-12 00:44:57 +0000152 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregor5c407d92008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000163bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000166 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000167 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-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 Gregor1aa450a2009-12-13 21:37:05 +0000175 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000185 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000188 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000194 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000199 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000200 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000201 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000202 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000203 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000204 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000210 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000211 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000212 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000217 OS << "No conversions required";
Douglas Gregor5251f1b2008-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 Dunbar42e3df02010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000227 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000229 OS << "'" << ConversionFunction->getNameAsString() << "'";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000231 OS << " -> ";
Douglas Gregor5251f1b2008-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 Dunbar42e3df02010-01-22 02:04:41 +0000239 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 switch (ConversionKind) {
241 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000242 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000243 Standard.DebugPrint();
244 break;
245 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000246 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000247 UserDefined.DebugPrint();
248 break;
249 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 break;
John McCall0d1da222010-01-12 00:44:57 +0000252 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000254 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000255 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000256 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 break;
258 }
259
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000260 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261}
262
John McCall0d1da222010-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 Gregor5251f1b2008-10-21 16:13:35 +0000279// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-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 McCalldaa3d6b2009-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 Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +0000295// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000296//
John McCall3d988d92009-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 Gregor5251f1b2008-10-21 16:13:35 +0000301//
John McCall3d988d92009-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 Gregor5251f1b2008-10-21 16:13:35 +0000306// signature), IsOverload returns false and MatchedDecl will be set to
307// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000308Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000309Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
310 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000311 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000312 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000313 NamedDecl *OldD = (*I)->getUnderlyingDecl();
314 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000315 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000316 Match = *I;
317 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000318 }
John McCall3d988d92009-12-02 08:47:38 +0000319 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000320 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000321 Match = *I;
322 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000323 }
John McCall84d87672009-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 McCall1f82f242009-11-18 22:49:29 +0000333 // (C++ 13p1):
334 // Only function declarations can be overloaded; object and type
335 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000336 Match = *I;
337 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000338 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000339 }
John McCall1f82f242009-11-18 22:49:29 +0000340
John McCalldaa3d6b2009-12-09 03:35:25 +0000341 return Ovl_Overload;
John McCall1f82f242009-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 Gregor5251f1b2008-10-21 16:13:35 +0000414}
415
Douglas Gregor8e1cf602008-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 Gregor5251f1b2008-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 Gregor2fe98832008-11-03 19:09:14 +0000434///
435/// If @p SuppressUserConversions, then user-defined conversions are
436/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000437/// If @p AllowExplicit, then explicit user-defined conversions are
438/// permitted.
Sebastian Redl42e92c42009-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 Jahanianb3c44f92009-10-01 20:39:51 +0000441/// If @p UserCast, the implicit conversion is being done for a user-specified
442/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000443ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000444Sema::TryImplicitConversion(Expr* From, QualType ToType,
445 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000446 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000447 bool InOverloadResolution,
448 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000449 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000450 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000451 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000452 return ICS;
453 }
454
455 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000456 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000457 return ICS;
458 }
459
460 OverloadCandidateSet Conversions(From->getExprLoc());
461 OverloadingResult UserDefResult
462 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
463 !SuppressUserConversions, AllowExplicit,
464 ForceRValue, UserCast);
465
466 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000467 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000468 // C++ [over.ics.user]p4:
469 // A conversion of an expression of class type to the same class
470 // type is given Exact Match rank, and a conversion of an
471 // expression of class type to a base class of that type is
472 // given Conversion rank, in spite of the fact that a copy
473 // constructor (i.e., a user-defined conversion function) is
474 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000475 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000476 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000477 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000478 = Context.getCanonicalType(From->getType().getUnqualifiedType());
479 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000480 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000481 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000482 // Turn this into a "standard" conversion sequence, so that it
483 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000484 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000485 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000486 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000487 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000488 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000489 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000490 ICS.Standard.Second = ICK_Derived_To_Base;
491 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000492 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000493
494 // C++ [over.best.ics]p4:
495 // However, when considering the argument of a user-defined
496 // conversion function that is a candidate by 13.3.1.3 when
497 // invoked for the copying of the temporary in the second step
498 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
499 // 13.3.1.6 in all cases, only standard conversion sequences and
500 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000501 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000502 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000503 }
John McCalle8c8cd22010-01-13 22:30:33 +0000504 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000505 ICS.setAmbiguous();
506 ICS.Ambiguous.setFromType(From->getType());
507 ICS.Ambiguous.setToType(ToType);
508 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
509 Cand != Conversions.end(); ++Cand)
510 if (Cand->Viable)
511 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000512 } else {
John McCall65eb8792010-02-25 01:37:24 +0000513 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000514 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000515
516 return ICS;
517}
518
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000519/// \brief Determine whether the conversion from FromType to ToType is a valid
520/// conversion that strips "noreturn" off the nested function type.
521static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
522 QualType ToType, QualType &ResultTy) {
523 if (Context.hasSameUnqualifiedType(FromType, ToType))
524 return false;
525
526 // Strip the noreturn off the type we're converting from; noreturn can
527 // safely be removed.
528 FromType = Context.getNoReturnType(FromType, false);
529 if (!Context.hasSameUnqualifiedType(FromType, ToType))
530 return false;
531
532 ResultTy = FromType;
533 return true;
534}
535
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000536/// IsStandardConversion - Determines whether there is a standard
537/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
538/// expression From to the type ToType. Standard conversion sequences
539/// only consider non-class types; for conversions that involve class
540/// types, use TryImplicitConversion. If a conversion exists, SCS will
541/// contain the standard conversion sequence required to perform this
542/// conversion and this routine will return true. Otherwise, this
543/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000544bool
545Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000546 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000547 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000548 QualType FromType = From->getType();
549
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000550 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000551 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000552 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000553 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000554 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000555 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000556
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000557 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000558 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000559 if (FromType->isRecordType() || ToType->isRecordType()) {
560 if (getLangOptions().CPlusPlus)
561 return false;
562
Mike Stump11289f42009-09-09 15:08:12 +0000563 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000564 }
565
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000566 // The first conversion can be an lvalue-to-rvalue conversion,
567 // array-to-pointer conversion, or function-to-pointer conversion
568 // (C++ 4p1).
569
Mike Stump11289f42009-09-09 15:08:12 +0000570 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000571 // An lvalue (3.10) of a non-function, non-array type T can be
572 // converted to an rvalue.
573 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000574 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000575 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000576 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000577 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000578
579 // If T is a non-class type, the type of the rvalue is the
580 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000581 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
582 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000583 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000584 } else if (FromType->isArrayType()) {
585 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000586 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000587
588 // An lvalue or rvalue of type "array of N T" or "array of unknown
589 // bound of T" can be converted to an rvalue of type "pointer to
590 // T" (C++ 4.2p1).
591 FromType = Context.getArrayDecayedType(FromType);
592
593 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
594 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000595 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000596
597 // For the purpose of ranking in overload resolution
598 // (13.3.3.1.1), this conversion is considered an
599 // array-to-pointer conversion followed by a qualification
600 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000601 SCS.Second = ICK_Identity;
602 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000603 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000604 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000605 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000606 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
607 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000608 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000609
610 // An lvalue of function type T can be converted to an rvalue of
611 // type "pointer to T." The result is a pointer to the
612 // function. (C++ 4.3p1).
613 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000614 } else if (FunctionDecl *Fn
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000615 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000616 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000617 SCS.First = ICK_Function_To_Pointer;
618
619 // We were able to resolve the address of the overloaded function,
620 // so we can convert to the type of that function.
621 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000622 if (ToType->isLValueReferenceType())
623 FromType = Context.getLValueReferenceType(FromType);
624 else if (ToType->isRValueReferenceType())
625 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000626 else if (ToType->isMemberPointerType()) {
627 // Resolve address only succeeds if both sides are member pointers,
628 // but it doesn't have to be the same class. See DR 247.
629 // Note that this means that the type of &Derived::fn can be
630 // Ret (Base::*)(Args) if the fn overload actually found is from the
631 // base class, even if it was brought into the derived class via a
632 // using declaration. The standard isn't clear on this issue at all.
633 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
634 FromType = Context.getMemberPointerType(FromType,
635 Context.getTypeDeclType(M->getParent()).getTypePtr());
636 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000637 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000638 } else {
639 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000640 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000641 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000642 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000643
644 // The second conversion can be an integral promotion, floating
645 // point promotion, integral conversion, floating point conversion,
646 // floating-integral conversion, pointer conversion,
647 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000648 // For overloading in C, this can also be a "compatible-type"
649 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000650 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000651 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000652 // The unqualified versions of the types are the same: there's no
653 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000654 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000655 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000656 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000657 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000658 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000659 } else if (IsFloatingPointPromotion(FromType, ToType)) {
660 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000661 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000662 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000663 } else if (IsComplexPromotion(FromType, ToType)) {
664 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000665 SCS.Second = ICK_Complex_Promotion;
666 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000667 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000668 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000669 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000670 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000671 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000672 } else if (FromType->isComplexType() && ToType->isComplexType()) {
673 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000674 SCS.Second = ICK_Complex_Conversion;
675 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000676 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
677 (ToType->isComplexType() && FromType->isArithmeticType())) {
678 // Complex-real conversions (C99 6.3.1.7)
679 SCS.Second = ICK_Complex_Real;
680 FromType = ToType.getUnqualifiedType();
681 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
682 // Floating point conversions (C++ 4.8).
683 SCS.Second = ICK_Floating_Conversion;
684 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000685 } else if ((FromType->isFloatingType() &&
686 ToType->isIntegralType() && (!ToType->isBooleanType() &&
687 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000688 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000689 ToType->isFloatingType())) {
690 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000691 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000692 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000693 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
694 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000695 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000696 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000697 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000698 } else if (IsMemberPointerConversion(From, FromType, ToType,
699 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000700 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000701 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000702 } else if (ToType->isBooleanType() &&
703 (FromType->isArithmeticType() ||
704 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000705 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000706 FromType->isBlockPointerType() ||
707 FromType->isMemberPointerType() ||
708 FromType->isNullPtrType())) {
709 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000710 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000711 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000712 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000713 Context.typesAreCompatible(ToType, FromType)) {
714 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000715 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000716 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
717 // Treat a conversion that strips "noreturn" as an identity conversion.
718 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000719 } else {
720 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000721 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000722 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000723 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000724
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000725 QualType CanonFrom;
726 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000727 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000728 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000729 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000730 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000731 CanonFrom = Context.getCanonicalType(FromType);
732 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000733 } else {
734 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000735 SCS.Third = ICK_Identity;
736
Mike Stump11289f42009-09-09 15:08:12 +0000737 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000738 // [...] Any difference in top-level cv-qualification is
739 // subsumed by the initialization itself and does not constitute
740 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000741 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000742 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000743 if (CanonFrom.getLocalUnqualifiedType()
744 == CanonTo.getLocalUnqualifiedType() &&
745 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000746 FromType = ToType;
747 CanonFrom = CanonTo;
748 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000749 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000750 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000751
752 // If we have not converted the argument type to the parameter type,
753 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000754 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000755 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000756
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000757 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000758}
759
760/// IsIntegralPromotion - Determines whether the conversion from the
761/// expression From (whose potentially-adjusted type is FromType) to
762/// ToType is an integral promotion (C++ 4.5). If so, returns true and
763/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000764bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000765 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000766 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000767 if (!To) {
768 return false;
769 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000770
771 // An rvalue of type char, signed char, unsigned char, short int, or
772 // unsigned short int can be converted to an rvalue of type int if
773 // int can represent all the values of the source type; otherwise,
774 // the source rvalue can be converted to an rvalue of type unsigned
775 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +0000776 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
777 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000778 if (// We can promote any signed, promotable integer type to an int
779 (FromType->isSignedIntegerType() ||
780 // We can promote any unsigned integer type whose size is
781 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000782 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000783 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000784 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000785 }
786
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000787 return To->getKind() == BuiltinType::UInt;
788 }
789
790 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
791 // can be converted to an rvalue of the first of the following types
792 // that can represent all the values of its underlying type: int,
793 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000794
795 // We pre-calculate the promotion type for enum types.
796 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
797 if (ToType->isIntegerType())
798 return Context.hasSameUnqualifiedType(ToType,
799 FromEnumType->getDecl()->getPromotionType());
800
801 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000802 // Determine whether the type we're converting from is signed or
803 // unsigned.
804 bool FromIsSigned;
805 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000806
807 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
808 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000809
810 // The types we'll try to promote to, in the appropriate
811 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000812 QualType PromoteTypes[6] = {
813 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000814 Context.LongTy, Context.UnsignedLongTy ,
815 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000817 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000818 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
819 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000820 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000821 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
822 // We found the type that we can promote to. If this is the
823 // type we wanted, we have a promotion. Otherwise, no
824 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000825 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000826 }
827 }
828 }
829
830 // An rvalue for an integral bit-field (9.6) can be converted to an
831 // rvalue of type int if int can represent all the values of the
832 // bit-field; otherwise, it can be converted to unsigned int if
833 // unsigned int can represent all the values of the bit-field. If
834 // the bit-field is larger yet, no integral promotion applies to
835 // it. If the bit-field has an enumerated type, it is treated as any
836 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000837 // FIXME: We should delay checking of bit-fields until we actually perform the
838 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000839 using llvm::APSInt;
840 if (From)
841 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000842 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000843 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
844 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
845 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
846 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000847
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000848 // Are we promoting to an int from a bitfield that fits in an int?
849 if (BitWidth < ToSize ||
850 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
851 return To->getKind() == BuiltinType::Int;
852 }
Mike Stump11289f42009-09-09 15:08:12 +0000853
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000854 // Are we promoting to an unsigned int from an unsigned bitfield
855 // that fits into an unsigned int?
856 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
857 return To->getKind() == BuiltinType::UInt;
858 }
Mike Stump11289f42009-09-09 15:08:12 +0000859
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000860 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000861 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000862 }
Mike Stump11289f42009-09-09 15:08:12 +0000863
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000864 // An rvalue of type bool can be converted to an rvalue of type int,
865 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000866 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000867 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000868 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000869
870 return false;
871}
872
873/// IsFloatingPointPromotion - Determines whether the conversion from
874/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
875/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000876bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000877 /// An rvalue of type float can be converted to an rvalue of type
878 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000879 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
880 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000881 if (FromBuiltin->getKind() == BuiltinType::Float &&
882 ToBuiltin->getKind() == BuiltinType::Double)
883 return true;
884
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000885 // C99 6.3.1.5p1:
886 // When a float is promoted to double or long double, or a
887 // double is promoted to long double [...].
888 if (!getLangOptions().CPlusPlus &&
889 (FromBuiltin->getKind() == BuiltinType::Float ||
890 FromBuiltin->getKind() == BuiltinType::Double) &&
891 (ToBuiltin->getKind() == BuiltinType::LongDouble))
892 return true;
893 }
894
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000895 return false;
896}
897
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000898/// \brief Determine if a conversion is a complex promotion.
899///
900/// A complex promotion is defined as a complex -> complex conversion
901/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000902/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000903bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000904 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000905 if (!FromComplex)
906 return false;
907
John McCall9dd450b2009-09-21 23:43:11 +0000908 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000909 if (!ToComplex)
910 return false;
911
912 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000913 ToComplex->getElementType()) ||
914 IsIntegralPromotion(0, FromComplex->getElementType(),
915 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000916}
917
Douglas Gregor237f96c2008-11-26 23:31:11 +0000918/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
919/// the pointer type FromPtr to a pointer to type ToPointee, with the
920/// same type qualifiers as FromPtr has on its pointee type. ToType,
921/// if non-empty, will be a pointer to ToType that may or may not have
922/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000923static QualType
924BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000925 QualType ToPointee, QualType ToType,
926 ASTContext &Context) {
927 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
928 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000929 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000930
931 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000932 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000933 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000934 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000935 return ToType;
936
937 // Build a pointer to ToPointee. It has the right qualifiers
938 // already.
939 return Context.getPointerType(ToPointee);
940 }
941
942 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000943 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000944 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
945 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000946}
947
Fariborz Jahanian01cbe442009-12-16 23:13:33 +0000948/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
949/// the FromType, which is an objective-c pointer, to ToType, which may or may
950/// not have the right set of qualifiers.
951static QualType
952BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
953 QualType ToType,
954 ASTContext &Context) {
955 QualType CanonFromType = Context.getCanonicalType(FromType);
956 QualType CanonToType = Context.getCanonicalType(ToType);
957 Qualifiers Quals = CanonFromType.getQualifiers();
958
959 // Exact qualifier match -> return the pointer type we're converting to.
960 if (CanonToType.getLocalQualifiers() == Quals)
961 return ToType;
962
963 // Just build a canonical type that has the right qualifiers.
964 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
965}
966
Mike Stump11289f42009-09-09 15:08:12 +0000967static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000968 bool InOverloadResolution,
969 ASTContext &Context) {
970 // Handle value-dependent integral null pointer constants correctly.
971 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
972 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
973 Expr->getType()->isIntegralType())
974 return !InOverloadResolution;
975
Douglas Gregor56751b52009-09-25 04:25:58 +0000976 return Expr->isNullPointerConstant(Context,
977 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
978 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000979}
Mike Stump11289f42009-09-09 15:08:12 +0000980
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000981/// IsPointerConversion - Determines whether the conversion of the
982/// expression From, which has the (possibly adjusted) type FromType,
983/// can be converted to the type ToType via a pointer conversion (C++
984/// 4.10). If so, returns true and places the converted type (that
985/// might differ from ToType in its cv-qualifiers at some level) into
986/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000987///
Douglas Gregora29dc052008-11-27 01:19:21 +0000988/// This routine also supports conversions to and from block pointers
989/// and conversions with Objective-C's 'id', 'id<protocols...>', and
990/// pointers to interfaces. FIXME: Once we've determined the
991/// appropriate overloading rules for Objective-C, we may want to
992/// split the Objective-C checks into a different routine; however,
993/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000994/// conversions, so for now they live here. IncompatibleObjC will be
995/// set if the conversion is an allowed Objective-C conversion that
996/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000997bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000998 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000999 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001000 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001001 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001002 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1003 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001004
Mike Stump11289f42009-09-09 15:08:12 +00001005 // Conversion from a null pointer constant to any Objective-C pointer type.
1006 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001007 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001008 ConvertedType = ToType;
1009 return true;
1010 }
1011
Douglas Gregor231d1c62008-11-27 00:15:41 +00001012 // Blocks: Block pointers can be converted to void*.
1013 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001014 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001015 ConvertedType = ToType;
1016 return true;
1017 }
1018 // Blocks: A null pointer constant can be converted to a block
1019 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001020 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001021 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001022 ConvertedType = ToType;
1023 return true;
1024 }
1025
Sebastian Redl576fd422009-05-10 18:38:11 +00001026 // If the left-hand-side is nullptr_t, the right side can be a null
1027 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001028 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001029 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001030 ConvertedType = ToType;
1031 return true;
1032 }
1033
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001034 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001035 if (!ToTypePtr)
1036 return false;
1037
1038 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001039 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001040 ConvertedType = ToType;
1041 return true;
1042 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001043
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001044 // Beyond this point, both types need to be pointers
1045 // , including objective-c pointers.
1046 QualType ToPointeeType = ToTypePtr->getPointeeType();
1047 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1048 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1049 ToType, Context);
1050 return true;
1051
1052 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001053 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001054 if (!FromTypePtr)
1055 return false;
1056
1057 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001058
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001059 // An rvalue of type "pointer to cv T," where T is an object type,
1060 // can be converted to an rvalue of type "pointer to cv void" (C++
1061 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001062 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001063 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001064 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001065 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001066 return true;
1067 }
1068
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001069 // When we're overloading in C, we allow a special kind of pointer
1070 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001071 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001072 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001073 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001074 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001075 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001076 return true;
1077 }
1078
Douglas Gregor5c407d92008-10-23 00:40:37 +00001079 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001080 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001081 // An rvalue of type "pointer to cv D," where D is a class type,
1082 // can be converted to an rvalue of type "pointer to cv B," where
1083 // B is a base class (clause 10) of D. If B is an inaccessible
1084 // (clause 11) or ambiguous (10.2) base class of D, a program that
1085 // necessitates this conversion is ill-formed. The result of the
1086 // conversion is a pointer to the base class sub-object of the
1087 // derived class object. The null pointer value is converted to
1088 // the null pointer value of the destination type.
1089 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001090 // Note that we do not check for ambiguity or inaccessibility
1091 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001092 if (getLangOptions().CPlusPlus &&
1093 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001094 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001095 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001096 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001097 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001098 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001099 ToType, Context);
1100 return true;
1101 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001102
Douglas Gregora119f102008-12-19 19:13:09 +00001103 return false;
1104}
1105
1106/// isObjCPointerConversion - Determines whether this is an
1107/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1108/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001109bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001110 QualType& ConvertedType,
1111 bool &IncompatibleObjC) {
1112 if (!getLangOptions().ObjC1)
1113 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001114
Steve Naroff7cae42b2009-07-10 23:34:53 +00001115 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001116 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001117 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001118 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001119
Steve Naroff7cae42b2009-07-10 23:34:53 +00001120 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001121 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001122 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001123 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001124 ConvertedType = ToType;
1125 return true;
1126 }
1127 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001128 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001129 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001130 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001131 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001132 ConvertedType = ToType;
1133 return true;
1134 }
1135 // Objective C++: We're able to convert from a pointer to an
1136 // interface to a pointer to a different interface.
1137 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001138 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1139 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1140 if (getLangOptions().CPlusPlus && LHS && RHS &&
1141 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1142 FromObjCPtr->getPointeeType()))
1143 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001144 ConvertedType = ToType;
1145 return true;
1146 }
1147
1148 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1149 // Okay: this is some kind of implicit downcast of Objective-C
1150 // interfaces, which is permitted. However, we're going to
1151 // complain about it.
1152 IncompatibleObjC = true;
1153 ConvertedType = FromType;
1154 return true;
1155 }
Mike Stump11289f42009-09-09 15:08:12 +00001156 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001157 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001158 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001159 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001160 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001161 else if (const BlockPointerType *ToBlockPtr =
1162 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001163 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001164 // to a block pointer type.
1165 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1166 ConvertedType = ToType;
1167 return true;
1168 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001169 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001170 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001171 else if (FromType->getAs<BlockPointerType>() &&
1172 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1173 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001174 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001175 ConvertedType = ToType;
1176 return true;
1177 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001178 else
Douglas Gregora119f102008-12-19 19:13:09 +00001179 return false;
1180
Douglas Gregor033f56d2008-12-23 00:53:59 +00001181 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001182 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001183 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001184 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001185 FromPointeeType = FromBlockPtr->getPointeeType();
1186 else
Douglas Gregora119f102008-12-19 19:13:09 +00001187 return false;
1188
Douglas Gregora119f102008-12-19 19:13:09 +00001189 // If we have pointers to pointers, recursively check whether this
1190 // is an Objective-C conversion.
1191 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1192 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1193 IncompatibleObjC)) {
1194 // We always complain about this conversion.
1195 IncompatibleObjC = true;
1196 ConvertedType = ToType;
1197 return true;
1198 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001199 // Allow conversion of pointee being objective-c pointer to another one;
1200 // as in I* to id.
1201 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1202 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1203 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1204 IncompatibleObjC)) {
1205 ConvertedType = ToType;
1206 return true;
1207 }
1208
Douglas Gregor033f56d2008-12-23 00:53:59 +00001209 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001210 // differences in the argument and result types are in Objective-C
1211 // pointer conversions. If so, we permit the conversion (but
1212 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001213 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001214 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001215 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001216 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001217 if (FromFunctionType && ToFunctionType) {
1218 // If the function types are exactly the same, this isn't an
1219 // Objective-C pointer conversion.
1220 if (Context.getCanonicalType(FromPointeeType)
1221 == Context.getCanonicalType(ToPointeeType))
1222 return false;
1223
1224 // Perform the quick checks that will tell us whether these
1225 // function types are obviously different.
1226 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1227 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1228 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1229 return false;
1230
1231 bool HasObjCConversion = false;
1232 if (Context.getCanonicalType(FromFunctionType->getResultType())
1233 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1234 // Okay, the types match exactly. Nothing to do.
1235 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1236 ToFunctionType->getResultType(),
1237 ConvertedType, IncompatibleObjC)) {
1238 // Okay, we have an Objective-C pointer conversion.
1239 HasObjCConversion = true;
1240 } else {
1241 // Function types are too different. Abort.
1242 return false;
1243 }
Mike Stump11289f42009-09-09 15:08:12 +00001244
Douglas Gregora119f102008-12-19 19:13:09 +00001245 // Check argument types.
1246 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1247 ArgIdx != NumArgs; ++ArgIdx) {
1248 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1249 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1250 if (Context.getCanonicalType(FromArgType)
1251 == Context.getCanonicalType(ToArgType)) {
1252 // Okay, the types match exactly. Nothing to do.
1253 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1254 ConvertedType, IncompatibleObjC)) {
1255 // Okay, we have an Objective-C pointer conversion.
1256 HasObjCConversion = true;
1257 } else {
1258 // Argument types are too different. Abort.
1259 return false;
1260 }
1261 }
1262
1263 if (HasObjCConversion) {
1264 // We had an Objective-C conversion. Allow this pointer
1265 // conversion, but complain about it.
1266 ConvertedType = ToType;
1267 IncompatibleObjC = true;
1268 return true;
1269 }
1270 }
1271
Sebastian Redl72b597d2009-01-25 19:43:20 +00001272 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001273}
1274
Douglas Gregor39c16d42008-10-24 04:54:22 +00001275/// CheckPointerConversion - Check the pointer conversion from the
1276/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001277/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001278/// conversions for which IsPointerConversion has already returned
1279/// true. It returns true and produces a diagnostic if there was an
1280/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001281bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001282 CastExpr::CastKind &Kind,
1283 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001284 QualType FromType = From->getType();
1285
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001286 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1287 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001288 QualType FromPointeeType = FromPtrType->getPointeeType(),
1289 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001290
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001291 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1292 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001293 // We must have a derived-to-base conversion. Check an
1294 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001295 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1296 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001297 From->getSourceRange(),
1298 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001299 return true;
1300
1301 // The conversion was successful.
1302 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001303 }
1304 }
Mike Stump11289f42009-09-09 15:08:12 +00001305 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001306 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001307 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001308 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001309 // Objective-C++ conversions are always okay.
1310 // FIXME: We should have a different class of conversions for the
1311 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001312 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001313 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001314
Steve Naroff7cae42b2009-07-10 23:34:53 +00001315 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001316 return false;
1317}
1318
Sebastian Redl72b597d2009-01-25 19:43:20 +00001319/// IsMemberPointerConversion - Determines whether the conversion of the
1320/// expression From, which has the (possibly adjusted) type FromType, can be
1321/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1322/// If so, returns true and places the converted type (that might differ from
1323/// ToType in its cv-qualifiers at some level) into ConvertedType.
1324bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001325 QualType ToType,
1326 bool InOverloadResolution,
1327 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001328 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001329 if (!ToTypePtr)
1330 return false;
1331
1332 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001333 if (From->isNullPointerConstant(Context,
1334 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1335 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001336 ConvertedType = ToType;
1337 return true;
1338 }
1339
1340 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001341 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001342 if (!FromTypePtr)
1343 return false;
1344
1345 // A pointer to member of B can be converted to a pointer to member of D,
1346 // where D is derived from B (C++ 4.11p2).
1347 QualType FromClass(FromTypePtr->getClass(), 0);
1348 QualType ToClass(ToTypePtr->getClass(), 0);
1349 // FIXME: What happens when these are dependent? Is this function even called?
1350
1351 if (IsDerivedFrom(ToClass, FromClass)) {
1352 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1353 ToClass.getTypePtr());
1354 return true;
1355 }
1356
1357 return false;
1358}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001359
Sebastian Redl72b597d2009-01-25 19:43:20 +00001360/// CheckMemberPointerConversion - Check the member pointer conversion from the
1361/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001362/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001363/// for which IsMemberPointerConversion has already returned true. It returns
1364/// true and produces a diagnostic if there was an error, or returns false
1365/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001366bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001367 CastExpr::CastKind &Kind,
1368 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001369 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001370 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001371 if (!FromPtrType) {
1372 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001373 assert(From->isNullPointerConstant(Context,
1374 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001375 "Expr must be null pointer constant!");
1376 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001377 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001378 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001379
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001380 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001381 assert(ToPtrType && "No member pointer cast has a target type "
1382 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001383
Sebastian Redled8f2002009-01-28 18:33:18 +00001384 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1385 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001386
Sebastian Redled8f2002009-01-28 18:33:18 +00001387 // FIXME: What about dependent types?
1388 assert(FromClass->isRecordType() && "Pointer into non-class.");
1389 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001390
John McCall5b0829a2010-02-10 09:31:12 +00001391 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/ true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001392 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001393 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1394 assert(DerivationOkay &&
1395 "Should not have been called if derivation isn't OK.");
1396 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001397
Sebastian Redled8f2002009-01-28 18:33:18 +00001398 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1399 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001400 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1401 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1402 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1403 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001404 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001405
Douglas Gregor89ee6822009-02-28 01:32:25 +00001406 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001407 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1408 << FromClass << ToClass << QualType(VBase, 0)
1409 << From->getSourceRange();
1410 return true;
1411 }
1412
John McCall5b0829a2010-02-10 09:31:12 +00001413 if (!IgnoreBaseAccess)
1414 CheckBaseClassAccess(From->getExprLoc(), /*BaseToDerived*/ true,
1415 FromClass, ToClass, Paths.front());
1416
Anders Carlssond7923c62009-08-22 23:33:40 +00001417 // Must be a base to derived member conversion.
1418 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001419 return false;
1420}
1421
Douglas Gregor9a657932008-10-21 23:43:52 +00001422/// IsQualificationConversion - Determines whether the conversion from
1423/// an rvalue of type FromType to ToType is a qualification conversion
1424/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001425bool
1426Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001427 FromType = Context.getCanonicalType(FromType);
1428 ToType = Context.getCanonicalType(ToType);
1429
1430 // If FromType and ToType are the same type, this is not a
1431 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001432 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001433 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001434
Douglas Gregor9a657932008-10-21 23:43:52 +00001435 // (C++ 4.4p4):
1436 // A conversion can add cv-qualifiers at levels other than the first
1437 // in multi-level pointers, subject to the following rules: [...]
1438 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001439 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001440 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001441 // Within each iteration of the loop, we check the qualifiers to
1442 // determine if this still looks like a qualification
1443 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001444 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001445 // until there are no more pointers or pointers-to-members left to
1446 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001447 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001448
1449 // -- for every j > 0, if const is in cv 1,j then const is in cv
1450 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001451 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001452 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001453
Douglas Gregor9a657932008-10-21 23:43:52 +00001454 // -- if the cv 1,j and cv 2,j are different, then const is in
1455 // every cv for 0 < k < j.
1456 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001457 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001458 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001459
Douglas Gregor9a657932008-10-21 23:43:52 +00001460 // Keep track of whether all prior cv-qualifiers in the "to" type
1461 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001462 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001463 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001464 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001465
1466 // We are left with FromType and ToType being the pointee types
1467 // after unwrapping the original FromType and ToType the same number
1468 // of types. If we unwrapped any pointers, and if FromType and
1469 // ToType have the same unqualified type (since we checked
1470 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001471 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001472}
1473
Douglas Gregor576e98c2009-01-30 23:27:23 +00001474/// Determines whether there is a user-defined conversion sequence
1475/// (C++ [over.ics.user]) that converts expression From to the type
1476/// ToType. If such a conversion exists, User will contain the
1477/// user-defined conversion sequence that performs such a conversion
1478/// and this routine will return true. Otherwise, this routine returns
1479/// false and User is unspecified.
1480///
1481/// \param AllowConversionFunctions true if the conversion should
1482/// consider conversion functions at all. If false, only constructors
1483/// will be considered.
1484///
1485/// \param AllowExplicit true if the conversion should consider C++0x
1486/// "explicit" conversion functions as well as non-explicit conversion
1487/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001488///
1489/// \param ForceRValue true if the expression should be treated as an rvalue
1490/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001491/// \param UserCast true if looking for user defined conversion for a static
1492/// cast.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001493OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1494 UserDefinedConversionSequence& User,
1495 OverloadCandidateSet& CandidateSet,
1496 bool AllowConversionFunctions,
1497 bool AllowExplicit,
1498 bool ForceRValue,
1499 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001500 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001501 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1502 // We're not going to find any constructors.
1503 } else if (CXXRecordDecl *ToRecordDecl
1504 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001505 // C++ [over.match.ctor]p1:
1506 // When objects of class type are direct-initialized (8.5), or
1507 // copy-initialized from an expression of the same or a
1508 // derived class type (8.5), overload resolution selects the
1509 // constructor. [...] For copy-initialization, the candidate
1510 // functions are all the converting constructors (12.3.1) of
1511 // that class. The argument list is the expression-list within
1512 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001513 bool SuppressUserConversions = !UserCast;
1514 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1515 IsDerivedFrom(From->getType(), ToType)) {
1516 SuppressUserConversions = false;
1517 AllowConversionFunctions = false;
1518 }
1519
Mike Stump11289f42009-09-09 15:08:12 +00001520 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001521 = Context.DeclarationNames.getCXXConstructorName(
1522 Context.getCanonicalType(ToType).getUnqualifiedType());
1523 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001524 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001525 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001526 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001527 // Find the constructor (which may be a template).
1528 CXXConstructorDecl *Constructor = 0;
1529 FunctionTemplateDecl *ConstructorTmpl
1530 = dyn_cast<FunctionTemplateDecl>(*Con);
1531 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001532 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001533 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1534 else
1535 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001536
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001537 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001538 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001539 if (ConstructorTmpl)
John McCallb89836b2010-01-26 01:37:31 +00001540 AddTemplateOverloadCandidate(ConstructorTmpl,
1541 ConstructorTmpl->getAccess(),
1542 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001543 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001544 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001545 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001546 // Allow one user-defined conversion when user specifies a
1547 // From->ToType conversion via an static cast (c-style, etc).
John McCallb89836b2010-01-26 01:37:31 +00001548 AddOverloadCandidate(Constructor, Constructor->getAccess(),
1549 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001550 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001551 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001552 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001553 }
1554 }
1555
Douglas Gregor576e98c2009-01-30 23:27:23 +00001556 if (!AllowConversionFunctions) {
1557 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001558 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1559 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001560 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001561 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001562 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001563 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001564 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001565 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1566 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001567 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001568 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001569 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001570 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00001571 NamedDecl *D = *I;
1572 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1573 if (isa<UsingShadowDecl>(D))
1574 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1575
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001576 CXXConversionDecl *Conv;
1577 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001578 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001579 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1580 else
John McCalld14a8642009-11-21 08:51:07 +00001581 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001582
1583 if (AllowExplicit || !Conv->isExplicit()) {
1584 if (ConvTemplate)
John McCallb89836b2010-01-26 01:37:31 +00001585 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
1586 ActingContext, From, ToType,
1587 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001588 else
John McCallb89836b2010-01-26 01:37:31 +00001589 AddConversionCandidate(Conv, I.getAccess(), ActingContext,
1590 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001591 }
1592 }
1593 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001594 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001595
1596 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001597 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001598 case OR_Success:
1599 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001600 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001601 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1602 // C++ [over.ics.user]p1:
1603 // If the user-defined conversion is specified by a
1604 // constructor (12.3.1), the initial standard conversion
1605 // sequence converts the source type to the type required by
1606 // the argument of the constructor.
1607 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001608 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001609 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001610 User.EllipsisConversion = true;
1611 else {
1612 User.Before = Best->Conversions[0].Standard;
1613 User.EllipsisConversion = false;
1614 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001615 User.ConversionFunction = Constructor;
1616 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001617 User.After.setFromType(
1618 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001619 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001620 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001621 } else if (CXXConversionDecl *Conversion
1622 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1623 // C++ [over.ics.user]p1:
1624 //
1625 // [...] If the user-defined conversion is specified by a
1626 // conversion function (12.3.2), the initial standard
1627 // conversion sequence converts the source type to the
1628 // implicit object parameter of the conversion function.
1629 User.Before = Best->Conversions[0].Standard;
1630 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001631 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001632
1633 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001634 // The second standard conversion sequence converts the
1635 // result of the user-defined conversion to the target type
1636 // for the sequence. Since an implicit conversion sequence
1637 // is an initialization, the special rules for
1638 // initialization by user-defined conversion apply when
1639 // selecting the best user-defined conversion for a
1640 // user-defined conversion sequence (see 13.3.3 and
1641 // 13.3.3.1).
1642 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001643 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001644 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001645 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001646 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001647 }
Mike Stump11289f42009-09-09 15:08:12 +00001648
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001649 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001650 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001651 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001652 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001653 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001654
1655 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001656 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001657 }
1658
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001659 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001660}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001661
1662bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001663Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001664 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00001665 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001666 OverloadingResult OvResult =
1667 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1668 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001669 if (OvResult == OR_Ambiguous)
1670 Diag(From->getSourceRange().getBegin(),
1671 diag::err_typecheck_ambiguous_condition)
1672 << From->getType() << ToType << From->getSourceRange();
1673 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1674 Diag(From->getSourceRange().getBegin(),
1675 diag::err_typecheck_nonviable_condition)
1676 << From->getType() << ToType << From->getSourceRange();
1677 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001678 return false;
John McCallad907772010-01-12 07:18:19 +00001679 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001680 return true;
1681}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001682
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001683/// CompareImplicitConversionSequences - Compare two implicit
1684/// conversion sequences to determine whether one is better than the
1685/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001686ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001687Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1688 const ImplicitConversionSequence& ICS2)
1689{
1690 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1691 // conversion sequences (as defined in 13.3.3.1)
1692 // -- a standard conversion sequence (13.3.3.1.1) is a better
1693 // conversion sequence than a user-defined conversion sequence or
1694 // an ellipsis conversion sequence, and
1695 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1696 // conversion sequence than an ellipsis conversion sequence
1697 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001698 //
John McCall0d1da222010-01-12 00:44:57 +00001699 // C++0x [over.best.ics]p10:
1700 // For the purpose of ranking implicit conversion sequences as
1701 // described in 13.3.3.2, the ambiguous conversion sequence is
1702 // treated as a user-defined sequence that is indistinguishable
1703 // from any other user-defined conversion sequence.
1704 if (ICS1.getKind() < ICS2.getKind()) {
1705 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1706 return ImplicitConversionSequence::Better;
1707 } else if (ICS2.getKind() < ICS1.getKind()) {
1708 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1709 return ImplicitConversionSequence::Worse;
1710 }
1711
1712 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1713 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001714
1715 // Two implicit conversion sequences of the same form are
1716 // indistinguishable conversion sequences unless one of the
1717 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001718 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001719 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001720 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001721 // User-defined conversion sequence U1 is a better conversion
1722 // sequence than another user-defined conversion sequence U2 if
1723 // they contain the same user-defined conversion function or
1724 // constructor and if the second standard conversion sequence of
1725 // U1 is better than the second standard conversion sequence of
1726 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001727 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001728 ICS2.UserDefined.ConversionFunction)
1729 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1730 ICS2.UserDefined.After);
1731 }
1732
1733 return ImplicitConversionSequence::Indistinguishable;
1734}
1735
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001736// Per 13.3.3.2p3, compare the given standard conversion sequences to
1737// determine if one is a proper subset of the other.
1738static ImplicitConversionSequence::CompareKind
1739compareStandardConversionSubsets(ASTContext &Context,
1740 const StandardConversionSequence& SCS1,
1741 const StandardConversionSequence& SCS2) {
1742 ImplicitConversionSequence::CompareKind Result
1743 = ImplicitConversionSequence::Indistinguishable;
1744
1745 if (SCS1.Second != SCS2.Second) {
1746 if (SCS1.Second == ICK_Identity)
1747 Result = ImplicitConversionSequence::Better;
1748 else if (SCS2.Second == ICK_Identity)
1749 Result = ImplicitConversionSequence::Worse;
1750 else
1751 return ImplicitConversionSequence::Indistinguishable;
1752 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1753 return ImplicitConversionSequence::Indistinguishable;
1754
1755 if (SCS1.Third == SCS2.Third) {
1756 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1757 : ImplicitConversionSequence::Indistinguishable;
1758 }
1759
1760 if (SCS1.Third == ICK_Identity)
1761 return Result == ImplicitConversionSequence::Worse
1762 ? ImplicitConversionSequence::Indistinguishable
1763 : ImplicitConversionSequence::Better;
1764
1765 if (SCS2.Third == ICK_Identity)
1766 return Result == ImplicitConversionSequence::Better
1767 ? ImplicitConversionSequence::Indistinguishable
1768 : ImplicitConversionSequence::Worse;
1769
1770 return ImplicitConversionSequence::Indistinguishable;
1771}
1772
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001773/// CompareStandardConversionSequences - Compare two standard
1774/// conversion sequences to determine whether one is better than the
1775/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001776ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001777Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1778 const StandardConversionSequence& SCS2)
1779{
1780 // Standard conversion sequence S1 is a better conversion sequence
1781 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1782
1783 // -- S1 is a proper subsequence of S2 (comparing the conversion
1784 // sequences in the canonical form defined by 13.3.3.1.1,
1785 // excluding any Lvalue Transformation; the identity conversion
1786 // sequence is considered to be a subsequence of any
1787 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001788 if (ImplicitConversionSequence::CompareKind CK
1789 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1790 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001791
1792 // -- the rank of S1 is better than the rank of S2 (by the rules
1793 // defined below), or, if not that,
1794 ImplicitConversionRank Rank1 = SCS1.getRank();
1795 ImplicitConversionRank Rank2 = SCS2.getRank();
1796 if (Rank1 < Rank2)
1797 return ImplicitConversionSequence::Better;
1798 else if (Rank2 < Rank1)
1799 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001800
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001801 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1802 // are indistinguishable unless one of the following rules
1803 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001804
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001805 // A conversion that is not a conversion of a pointer, or
1806 // pointer to member, to bool is better than another conversion
1807 // that is such a conversion.
1808 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1809 return SCS2.isPointerConversionToBool()
1810 ? ImplicitConversionSequence::Better
1811 : ImplicitConversionSequence::Worse;
1812
Douglas Gregor5c407d92008-10-23 00:40:37 +00001813 // C++ [over.ics.rank]p4b2:
1814 //
1815 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001816 // conversion of B* to A* is better than conversion of B* to
1817 // void*, and conversion of A* to void* is better than conversion
1818 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001819 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001820 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001821 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001822 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001823 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1824 // Exactly one of the conversion sequences is a conversion to
1825 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001826 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1827 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001828 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1829 // Neither conversion sequence converts to a void pointer; compare
1830 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001831 if (ImplicitConversionSequence::CompareKind DerivedCK
1832 = CompareDerivedToBaseConversions(SCS1, SCS2))
1833 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001834 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1835 // Both conversion sequences are conversions to void
1836 // pointers. Compare the source types to determine if there's an
1837 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001838 QualType FromType1 = SCS1.getFromType();
1839 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001840
1841 // Adjust the types we're converting from via the array-to-pointer
1842 // conversion, if we need to.
1843 if (SCS1.First == ICK_Array_To_Pointer)
1844 FromType1 = Context.getArrayDecayedType(FromType1);
1845 if (SCS2.First == ICK_Array_To_Pointer)
1846 FromType2 = Context.getArrayDecayedType(FromType2);
1847
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001848 QualType FromPointee1
1849 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1850 QualType FromPointee2
1851 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001852
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001853 if (IsDerivedFrom(FromPointee2, FromPointee1))
1854 return ImplicitConversionSequence::Better;
1855 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1856 return ImplicitConversionSequence::Worse;
1857
1858 // Objective-C++: If one interface is more specific than the
1859 // other, it is the better one.
1860 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1861 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1862 if (FromIface1 && FromIface1) {
1863 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1864 return ImplicitConversionSequence::Better;
1865 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1866 return ImplicitConversionSequence::Worse;
1867 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001868 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001869
1870 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1871 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001872 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001873 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001874 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001875
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001876 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001877 // C++0x [over.ics.rank]p3b4:
1878 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1879 // implicit object parameter of a non-static member function declared
1880 // without a ref-qualifier, and S1 binds an rvalue reference to an
1881 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001882 // FIXME: We don't know if we're dealing with the implicit object parameter,
1883 // or if the member function in this case has a ref qualifier.
1884 // (Of course, we don't have ref qualifiers yet.)
1885 if (SCS1.RRefBinding != SCS2.RRefBinding)
1886 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1887 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001888
1889 // C++ [over.ics.rank]p3b4:
1890 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1891 // which the references refer are the same type except for
1892 // top-level cv-qualifiers, and the type to which the reference
1893 // initialized by S2 refers is more cv-qualified than the type
1894 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001895 QualType T1 = SCS1.getToType(2);
1896 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001897 T1 = Context.getCanonicalType(T1);
1898 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001899 Qualifiers T1Quals, T2Quals;
1900 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1901 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1902 if (UnqualT1 == UnqualT2) {
1903 // If the type is an array type, promote the element qualifiers to the type
1904 // for comparison.
1905 if (isa<ArrayType>(T1) && T1Quals)
1906 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1907 if (isa<ArrayType>(T2) && T2Quals)
1908 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001909 if (T2.isMoreQualifiedThan(T1))
1910 return ImplicitConversionSequence::Better;
1911 else if (T1.isMoreQualifiedThan(T2))
1912 return ImplicitConversionSequence::Worse;
1913 }
1914 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001915
1916 return ImplicitConversionSequence::Indistinguishable;
1917}
1918
1919/// CompareQualificationConversions - Compares two standard conversion
1920/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001921/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1922ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001923Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001924 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001925 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001926 // -- S1 and S2 differ only in their qualification conversion and
1927 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1928 // cv-qualification signature of type T1 is a proper subset of
1929 // the cv-qualification signature of type T2, and S1 is not the
1930 // deprecated string literal array-to-pointer conversion (4.2).
1931 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1932 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1933 return ImplicitConversionSequence::Indistinguishable;
1934
1935 // FIXME: the example in the standard doesn't use a qualification
1936 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001937 QualType T1 = SCS1.getToType(2);
1938 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001939 T1 = Context.getCanonicalType(T1);
1940 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001941 Qualifiers T1Quals, T2Quals;
1942 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1943 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001944
1945 // If the types are the same, we won't learn anything by unwrapped
1946 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00001947 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001948 return ImplicitConversionSequence::Indistinguishable;
1949
Chandler Carruth607f38e2009-12-29 07:16:59 +00001950 // If the type is an array type, promote the element qualifiers to the type
1951 // for comparison.
1952 if (isa<ArrayType>(T1) && T1Quals)
1953 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1954 if (isa<ArrayType>(T2) && T2Quals)
1955 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1956
Mike Stump11289f42009-09-09 15:08:12 +00001957 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001958 = ImplicitConversionSequence::Indistinguishable;
1959 while (UnwrapSimilarPointerTypes(T1, T2)) {
1960 // Within each iteration of the loop, we check the qualifiers to
1961 // determine if this still looks like a qualification
1962 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001963 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001964 // until there are no more pointers or pointers-to-members left
1965 // to unwrap. This essentially mimics what
1966 // IsQualificationConversion does, but here we're checking for a
1967 // strict subset of qualifiers.
1968 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1969 // The qualifiers are the same, so this doesn't tell us anything
1970 // about how the sequences rank.
1971 ;
1972 else if (T2.isMoreQualifiedThan(T1)) {
1973 // T1 has fewer qualifiers, so it could be the better sequence.
1974 if (Result == ImplicitConversionSequence::Worse)
1975 // Neither has qualifiers that are a subset of the other's
1976 // qualifiers.
1977 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001978
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001979 Result = ImplicitConversionSequence::Better;
1980 } else if (T1.isMoreQualifiedThan(T2)) {
1981 // T2 has fewer qualifiers, so it could be the better sequence.
1982 if (Result == ImplicitConversionSequence::Better)
1983 // Neither has qualifiers that are a subset of the other's
1984 // qualifiers.
1985 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001986
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001987 Result = ImplicitConversionSequence::Worse;
1988 } else {
1989 // Qualifiers are disjoint.
1990 return ImplicitConversionSequence::Indistinguishable;
1991 }
1992
1993 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001994 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001995 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001996 }
1997
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001998 // Check that the winning standard conversion sequence isn't using
1999 // the deprecated string literal array to pointer conversion.
2000 switch (Result) {
2001 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002002 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002003 Result = ImplicitConversionSequence::Indistinguishable;
2004 break;
2005
2006 case ImplicitConversionSequence::Indistinguishable:
2007 break;
2008
2009 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002010 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002011 Result = ImplicitConversionSequence::Indistinguishable;
2012 break;
2013 }
2014
2015 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002016}
2017
Douglas Gregor5c407d92008-10-23 00:40:37 +00002018/// CompareDerivedToBaseConversions - Compares two standard conversion
2019/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002020/// various kinds of derived-to-base conversions (C++
2021/// [over.ics.rank]p4b3). As part of these checks, we also look at
2022/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002023ImplicitConversionSequence::CompareKind
2024Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2025 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002026 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002027 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002028 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002029 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002030
2031 // Adjust the types we're converting from via the array-to-pointer
2032 // conversion, if we need to.
2033 if (SCS1.First == ICK_Array_To_Pointer)
2034 FromType1 = Context.getArrayDecayedType(FromType1);
2035 if (SCS2.First == ICK_Array_To_Pointer)
2036 FromType2 = Context.getArrayDecayedType(FromType2);
2037
2038 // Canonicalize all of the types.
2039 FromType1 = Context.getCanonicalType(FromType1);
2040 ToType1 = Context.getCanonicalType(ToType1);
2041 FromType2 = Context.getCanonicalType(FromType2);
2042 ToType2 = Context.getCanonicalType(ToType2);
2043
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002044 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002045 //
2046 // If class B is derived directly or indirectly from class A and
2047 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002048 //
2049 // For Objective-C, we let A, B, and C also be Objective-C
2050 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002051
2052 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002053 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002054 SCS2.Second == ICK_Pointer_Conversion &&
2055 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2056 FromType1->isPointerType() && FromType2->isPointerType() &&
2057 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002058 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002059 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002060 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002061 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002062 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002063 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002064 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002065 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002066
John McCall9dd450b2009-09-21 23:43:11 +00002067 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2068 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2069 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2070 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002071
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002072 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002073 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2074 if (IsDerivedFrom(ToPointee1, ToPointee2))
2075 return ImplicitConversionSequence::Better;
2076 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2077 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002078
2079 if (ToIface1 && ToIface2) {
2080 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2081 return ImplicitConversionSequence::Better;
2082 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2083 return ImplicitConversionSequence::Worse;
2084 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002085 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002086
2087 // -- conversion of B* to A* is better than conversion of C* to A*,
2088 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2089 if (IsDerivedFrom(FromPointee2, FromPointee1))
2090 return ImplicitConversionSequence::Better;
2091 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2092 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002093
Douglas Gregor237f96c2008-11-26 23:31:11 +00002094 if (FromIface1 && FromIface2) {
2095 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2096 return ImplicitConversionSequence::Better;
2097 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2098 return ImplicitConversionSequence::Worse;
2099 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002100 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002101 }
2102
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002103 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002104 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2105 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2106 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2107 const MemberPointerType * FromMemPointer1 =
2108 FromType1->getAs<MemberPointerType>();
2109 const MemberPointerType * ToMemPointer1 =
2110 ToType1->getAs<MemberPointerType>();
2111 const MemberPointerType * FromMemPointer2 =
2112 FromType2->getAs<MemberPointerType>();
2113 const MemberPointerType * ToMemPointer2 =
2114 ToType2->getAs<MemberPointerType>();
2115 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2116 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2117 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2118 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2119 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2120 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2121 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2122 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002123 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002124 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2125 if (IsDerivedFrom(ToPointee1, ToPointee2))
2126 return ImplicitConversionSequence::Worse;
2127 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2128 return ImplicitConversionSequence::Better;
2129 }
2130 // conversion of B::* to C::* is better than conversion of A::* to C::*
2131 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2132 if (IsDerivedFrom(FromPointee1, FromPointee2))
2133 return ImplicitConversionSequence::Better;
2134 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2135 return ImplicitConversionSequence::Worse;
2136 }
2137 }
2138
Douglas Gregor83af86a2010-02-25 19:01:05 +00002139 if ((SCS1.ReferenceBinding || SCS1.CopyConstructor) &&
2140 (SCS2.ReferenceBinding || SCS2.CopyConstructor) &&
Douglas Gregor2fe98832008-11-03 19:09:14 +00002141 SCS1.Second == ICK_Derived_To_Base) {
2142 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002143 // -- binding of an expression of type C to a reference of type
2144 // B& is better than binding an expression of type C to a
2145 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002146 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2147 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002148 if (IsDerivedFrom(ToType1, ToType2))
2149 return ImplicitConversionSequence::Better;
2150 else if (IsDerivedFrom(ToType2, ToType1))
2151 return ImplicitConversionSequence::Worse;
2152 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002153
Douglas Gregor2fe98832008-11-03 19:09:14 +00002154 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002155 // -- binding of an expression of type B to a reference of type
2156 // A& is better than binding an expression of type C to a
2157 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002158 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2159 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002160 if (IsDerivedFrom(FromType2, FromType1))
2161 return ImplicitConversionSequence::Better;
2162 else if (IsDerivedFrom(FromType1, FromType2))
2163 return ImplicitConversionSequence::Worse;
2164 }
2165 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002166
Douglas Gregor5c407d92008-10-23 00:40:37 +00002167 return ImplicitConversionSequence::Indistinguishable;
2168}
2169
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002170/// TryCopyInitialization - Try to copy-initialize a value of type
2171/// ToType from the expression From. Return the implicit conversion
2172/// sequence required to pass this argument, which may be a bad
2173/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002174/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002175/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2176/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002177ImplicitConversionSequence
2178Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002179 bool SuppressUserConversions, bool ForceRValue,
2180 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002181 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002182 ImplicitConversionSequence ICS;
John McCall65eb8792010-02-25 01:37:24 +00002183 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002184 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002185 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002186 SuppressUserConversions,
2187 /*AllowExplicit=*/false,
2188 ForceRValue,
2189 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002190 return ICS;
2191 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002192 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002193 SuppressUserConversions,
2194 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002195 ForceRValue,
2196 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002197 }
2198}
2199
Sebastian Redl42e92c42009-04-12 17:16:29 +00002200/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2201/// the expression @p From. Returns true (and emits a diagnostic) if there was
2202/// an error, returns false if the initialization succeeded. Elidable should
2203/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2204/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002205bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002206 AssignmentAction Action, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002207 if (!getLangOptions().CPlusPlus) {
2208 // In C, argument passing is the same as performing an assignment.
2209 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002210
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002211 AssignConvertType ConvTy =
2212 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002213 if (ConvTy != Compatible &&
2214 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2215 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002216
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002217 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002218 FromType, From, Action);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002219 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002220
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002221 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002222 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002223 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002224 /*SuppressUserConversions=*/false,
2225 /*AllowExplicit=*/false,
2226 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002227
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002228 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002229 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002230 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002231 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002232 return Diag(From->getSourceRange().getBegin(),
2233 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002234 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002235 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002236}
2237
Douglas Gregor436424c2008-11-18 23:14:02 +00002238/// TryObjectArgumentInitialization - Try to initialize the object
2239/// parameter of the given member function (@c Method) from the
2240/// expression @p From.
2241ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002242Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002243 CXXMethodDecl *Method,
2244 CXXRecordDecl *ActingContext) {
2245 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002246 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2247 // const volatile object.
2248 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2249 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2250 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002251
2252 // Set up the conversion sequence as a "bad" conversion, to allow us
2253 // to exit early.
2254 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002255
2256 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002257 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002258 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002259 FromType = PT->getPointeeType();
2260
2261 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002262
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002263 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002264 // where X is the class of which the function is a member
2265 // (C++ [over.match.funcs]p4). However, when finding an implicit
2266 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002267 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002268 // (C++ [over.match.funcs]p5). We perform a simplified version of
2269 // reference binding here, that allows class rvalues to bind to
2270 // non-constant references.
2271
2272 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2273 // with the implicit object parameter (C++ [over.match.funcs]p5).
2274 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002275 if (ImplicitParamType.getCVRQualifiers()
2276 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002277 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002278 ICS.setBad(BadConversionSequence::bad_qualifiers,
2279 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002280 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002281 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002282
2283 // Check that we have either the same type or a derived type. It
2284 // affects the conversion rank.
2285 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002286 ImplicitConversionKind SecondKind;
2287 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2288 SecondKind = ICK_Identity;
2289 } else if (IsDerivedFrom(FromType, ClassType))
2290 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002291 else {
John McCall65eb8792010-02-25 01:37:24 +00002292 ICS.setBad(BadConversionSequence::unrelated_class,
2293 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002294 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002295 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002296
2297 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002298 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002299 ICS.Standard.setAsIdentityConversion();
2300 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002301 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002302 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002303 ICS.Standard.ReferenceBinding = true;
2304 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002305 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002306 return ICS;
2307}
2308
2309/// PerformObjectArgumentInitialization - Perform initialization of
2310/// the implicit object parameter for the given Method with the given
2311/// expression.
2312bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002313Sema::PerformObjectArgumentInitialization(Expr *&From,
2314 NestedNameSpecifier *Qualifier,
2315 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002316 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002317 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002318 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002319
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002320 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002321 FromRecordType = PT->getPointeeType();
2322 DestType = Method->getThisType(Context);
2323 } else {
2324 FromRecordType = From->getType();
2325 DestType = ImplicitParamRecordType;
2326 }
2327
John McCall6e9f8f62009-12-03 04:06:58 +00002328 // Note that we always use the true parent context when performing
2329 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002330 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002331 = TryObjectArgumentInitialization(From->getType(), Method,
2332 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002333 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002334 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002335 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002336 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002337
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002338 if (ICS.Standard.Second == ICK_Derived_To_Base)
2339 return PerformObjectMemberConversion(From, Qualifier, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002340
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002341 if (!Context.hasSameType(From->getType(), DestType))
2342 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2343 /*isLvalue=*/!From->getType()->getAs<PointerType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002344 return false;
2345}
2346
Douglas Gregor5fb53972009-01-14 15:45:31 +00002347/// TryContextuallyConvertToBool - Attempt to contextually convert the
2348/// expression From to bool (C++0x [conv]p3).
2349ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002350 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002351 // FIXME: Are these flags correct?
2352 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002353 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002354 /*ForceRValue=*/false,
2355 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002356}
2357
2358/// PerformContextuallyConvertToBool - Perform a contextual conversion
2359/// of the expression From to bool (C++0x [conv]p3).
2360bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2361 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002362 if (!ICS.isBad())
2363 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002364
Fariborz Jahanian76197412009-11-18 18:26:29 +00002365 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002366 return Diag(From->getSourceRange().getBegin(),
2367 diag::err_typecheck_bool_condition)
2368 << From->getType() << From->getSourceRange();
2369 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002370}
2371
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002372/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002373/// candidate functions, using the given function call arguments. If
2374/// @p SuppressUserConversions, then don't allow user-defined
2375/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002376/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2377/// hacky way to implement the overloading rules for elidable copy
2378/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002379///
2380/// \para PartialOverloading true if we are performing "partial" overloading
2381/// based on an incomplete set of function arguments. This feature is used by
2382/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002383void
2384Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCallb89836b2010-01-26 01:37:31 +00002385 AccessSpecifier Access,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002386 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002387 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002388 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002389 bool ForceRValue,
2390 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002391 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002392 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002393 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002394 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002395 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002396
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002397 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002398 if (!isa<CXXConstructorDecl>(Method)) {
2399 // If we get here, it's because we're calling a member function
2400 // that is named without a member access expression (e.g.,
2401 // "this->f") that was either written explicitly or created
2402 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002403 // function, e.g., X::f(). We use an empty type for the implied
2404 // object argument (C++ [over.call.func]p3), and the acting context
2405 // is irrelevant.
John McCallb89836b2010-01-26 01:37:31 +00002406 AddMethodCandidate(Method, Access, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002407 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002408 SuppressUserConversions, ForceRValue);
2409 return;
2410 }
2411 // We treat a constructor like a non-member function, since its object
2412 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002413 }
2414
Douglas Gregorff7028a2009-11-13 23:59:09 +00002415 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002416 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002417
Douglas Gregor27381f32009-11-23 12:27:39 +00002418 // Overload resolution is always an unevaluated context.
2419 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2420
Douglas Gregorffe14e32009-11-14 01:20:54 +00002421 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2422 // C++ [class.copy]p3:
2423 // A member function template is never instantiated to perform the copy
2424 // of a class object to an object of its class type.
2425 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2426 if (NumArgs == 1 &&
2427 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00002428 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2429 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00002430 return;
2431 }
2432
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002433 // Add this candidate
2434 CandidateSet.push_back(OverloadCandidate());
2435 OverloadCandidate& Candidate = CandidateSet.back();
2436 Candidate.Function = Function;
John McCallb89836b2010-01-26 01:37:31 +00002437 Candidate.Access = Access;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002438 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002439 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002440 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002441
2442 unsigned NumArgsInProto = Proto->getNumArgs();
2443
2444 // (C++ 13.3.2p2): A candidate function having fewer than m
2445 // parameters is viable only if it has an ellipsis in its parameter
2446 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002447 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2448 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002449 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002450 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002451 return;
2452 }
2453
2454 // (C++ 13.3.2p2): A candidate function having more than m parameters
2455 // is viable only if the (m+1)st parameter has a default argument
2456 // (8.3.6). For the purposes of overload resolution, the
2457 // parameter list is truncated on the right, so that there are
2458 // exactly m parameters.
2459 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002460 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002461 // Not enough arguments.
2462 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002463 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002464 return;
2465 }
2466
2467 // Determine the implicit conversion sequences for each of the
2468 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002469 Candidate.Conversions.resize(NumArgs);
2470 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2471 if (ArgIdx < NumArgsInProto) {
2472 // (C++ 13.3.2p3): for F to be a viable function, there shall
2473 // exist for each argument an implicit conversion sequence
2474 // (13.3.3.1) that converts that argument to the corresponding
2475 // parameter of F.
2476 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002477 Candidate.Conversions[ArgIdx]
2478 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002479 SuppressUserConversions, ForceRValue,
2480 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002481 if (Candidate.Conversions[ArgIdx].isBad()) {
2482 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002483 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002484 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002485 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002486 } else {
2487 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2488 // argument for which there is no corresponding parameter is
2489 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002490 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002491 }
2492 }
2493}
2494
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002495/// \brief Add all of the function declarations in the given function set to
2496/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00002497void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002498 Expr **Args, unsigned NumArgs,
2499 OverloadCandidateSet& CandidateSet,
2500 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00002501 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002502 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002503 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2504 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall4c4c1df2010-01-26 03:27:55 +00002505 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getAccess(),
John McCall6e9f8f62009-12-03 04:06:58 +00002506 cast<CXXMethodDecl>(FD)->getParent(),
2507 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002508 CandidateSet, SuppressUserConversions);
2509 else
John McCallb89836b2010-01-26 01:37:31 +00002510 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002511 SuppressUserConversions);
2512 } else {
2513 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2514 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2515 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall4c4c1df2010-01-26 03:27:55 +00002516 AddMethodTemplateCandidate(FunTmpl, F.getAccess(),
John McCall6e9f8f62009-12-03 04:06:58 +00002517 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002518 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002519 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002520 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002521 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002522 else
John McCallb89836b2010-01-26 01:37:31 +00002523 AddTemplateOverloadCandidate(FunTmpl, AS_none,
John McCall6b51f282009-11-23 01:53:49 +00002524 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002525 Args, NumArgs, CandidateSet,
2526 SuppressUserConversions);
2527 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002528 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002529}
2530
John McCallf0f1cf02009-11-17 07:50:12 +00002531/// AddMethodCandidate - Adds a named decl (which is some kind of
2532/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002533void Sema::AddMethodCandidate(NamedDecl *Decl,
John McCallb89836b2010-01-26 01:37:31 +00002534 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002535 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002536 Expr **Args, unsigned NumArgs,
2537 OverloadCandidateSet& CandidateSet,
2538 bool SuppressUserConversions, bool ForceRValue) {
John McCall6e9f8f62009-12-03 04:06:58 +00002539 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002540
2541 if (isa<UsingShadowDecl>(Decl))
2542 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2543
2544 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2545 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2546 "Expected a member function template");
John McCallb89836b2010-01-26 01:37:31 +00002547 AddMethodTemplateCandidate(TD, Access, ActingContext, /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002548 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002549 CandidateSet,
2550 SuppressUserConversions,
2551 ForceRValue);
2552 } else {
John McCallb89836b2010-01-26 01:37:31 +00002553 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Access, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00002554 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002555 CandidateSet, SuppressUserConversions, ForceRValue);
2556 }
2557}
2558
Douglas Gregor436424c2008-11-18 23:14:02 +00002559/// AddMethodCandidate - Adds the given C++ member function to the set
2560/// of candidate functions, using the given function call arguments
2561/// and the object argument (@c Object). For example, in a call
2562/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2563/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2564/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002565/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2566/// a slightly hacky way to implement the overloading rules for elidable copy
2567/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002568void
John McCallb89836b2010-01-26 01:37:31 +00002569Sema::AddMethodCandidate(CXXMethodDecl *Method, AccessSpecifier Access,
2570 CXXRecordDecl *ActingContext, QualType ObjectType,
2571 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002572 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002573 bool SuppressUserConversions, bool ForceRValue) {
2574 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002575 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002576 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002577 assert(!isa<CXXConstructorDecl>(Method) &&
2578 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002579
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002580 if (!CandidateSet.isNewCandidate(Method))
2581 return;
2582
Douglas Gregor27381f32009-11-23 12:27:39 +00002583 // Overload resolution is always an unevaluated context.
2584 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2585
Douglas Gregor436424c2008-11-18 23:14:02 +00002586 // Add this candidate
2587 CandidateSet.push_back(OverloadCandidate());
2588 OverloadCandidate& Candidate = CandidateSet.back();
2589 Candidate.Function = Method;
John McCallb89836b2010-01-26 01:37:31 +00002590 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002591 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002592 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002593
2594 unsigned NumArgsInProto = Proto->getNumArgs();
2595
2596 // (C++ 13.3.2p2): A candidate function having fewer than m
2597 // parameters is viable only if it has an ellipsis in its parameter
2598 // list (8.3.5).
2599 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2600 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002601 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002602 return;
2603 }
2604
2605 // (C++ 13.3.2p2): A candidate function having more than m parameters
2606 // is viable only if the (m+1)st parameter has a default argument
2607 // (8.3.6). For the purposes of overload resolution, the
2608 // parameter list is truncated on the right, so that there are
2609 // exactly m parameters.
2610 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2611 if (NumArgs < MinRequiredArgs) {
2612 // Not enough arguments.
2613 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002614 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002615 return;
2616 }
2617
2618 Candidate.Viable = true;
2619 Candidate.Conversions.resize(NumArgs + 1);
2620
John McCall6e9f8f62009-12-03 04:06:58 +00002621 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002622 // The implicit object argument is ignored.
2623 Candidate.IgnoreObjectArgument = true;
2624 else {
2625 // Determine the implicit conversion sequence for the object
2626 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002627 Candidate.Conversions[0]
2628 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002629 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002630 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002631 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002632 return;
2633 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002634 }
2635
2636 // Determine the implicit conversion sequences for each of the
2637 // arguments.
2638 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2639 if (ArgIdx < NumArgsInProto) {
2640 // (C++ 13.3.2p3): for F to be a viable function, there shall
2641 // exist for each argument an implicit conversion sequence
2642 // (13.3.3.1) that converts that argument to the corresponding
2643 // parameter of F.
2644 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002645 Candidate.Conversions[ArgIdx + 1]
2646 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002647 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002648 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002649 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002650 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002651 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002652 break;
2653 }
2654 } else {
2655 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2656 // argument for which there is no corresponding parameter is
2657 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002658 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002659 }
2660 }
2661}
2662
Douglas Gregor97628d62009-08-21 00:16:32 +00002663/// \brief Add a C++ member function template as a candidate to the candidate
2664/// set, using template argument deduction to produce an appropriate member
2665/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002666void
Douglas Gregor97628d62009-08-21 00:16:32 +00002667Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCallb89836b2010-01-26 01:37:31 +00002668 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002669 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002670 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002671 QualType ObjectType,
2672 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002673 OverloadCandidateSet& CandidateSet,
2674 bool SuppressUserConversions,
2675 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002676 if (!CandidateSet.isNewCandidate(MethodTmpl))
2677 return;
2678
Douglas Gregor97628d62009-08-21 00:16:32 +00002679 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002680 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002681 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002682 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002683 // candidate functions in the usual way.113) A given name can refer to one
2684 // or more function templates and also to a set of overloaded non-template
2685 // functions. In such a case, the candidate functions generated from each
2686 // function template are combined with the set of non-template candidate
2687 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00002688 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00002689 FunctionDecl *Specialization = 0;
2690 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002691 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002692 Args, NumArgs, Specialization, Info)) {
2693 // FIXME: Record what happened with template argument deduction, so
2694 // that we can give the user a beautiful diagnostic.
2695 (void)Result;
2696 return;
2697 }
Mike Stump11289f42009-09-09 15:08:12 +00002698
Douglas Gregor97628d62009-08-21 00:16:32 +00002699 // Add the function template specialization produced by template argument
2700 // deduction as a candidate.
2701 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002702 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002703 "Specialization is not a member function?");
John McCallb89836b2010-01-26 01:37:31 +00002704 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Access,
2705 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002706 CandidateSet, SuppressUserConversions, ForceRValue);
2707}
2708
Douglas Gregor05155d82009-08-21 23:19:43 +00002709/// \brief Add a C++ function template specialization as a candidate
2710/// in the candidate set, using template argument deduction to produce
2711/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002712void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002713Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCallb89836b2010-01-26 01:37:31 +00002714 AccessSpecifier Access,
John McCall6b51f282009-11-23 01:53:49 +00002715 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002716 Expr **Args, unsigned NumArgs,
2717 OverloadCandidateSet& CandidateSet,
2718 bool SuppressUserConversions,
2719 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002720 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2721 return;
2722
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002723 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002724 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002725 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002726 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002727 // candidate functions in the usual way.113) A given name can refer to one
2728 // or more function templates and also to a set of overloaded non-template
2729 // functions. In such a case, the candidate functions generated from each
2730 // function template are combined with the set of non-template candidate
2731 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00002732 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002733 FunctionDecl *Specialization = 0;
2734 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002735 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002736 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00002737 CandidateSet.push_back(OverloadCandidate());
2738 OverloadCandidate &Candidate = CandidateSet.back();
2739 Candidate.Function = FunctionTemplate->getTemplatedDecl();
John McCallb89836b2010-01-26 01:37:31 +00002740 Candidate.Access = Access;
John McCalld681c392009-12-16 08:11:27 +00002741 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002742 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00002743 Candidate.IsSurrogate = false;
2744 Candidate.IgnoreObjectArgument = false;
John McCall8b9ed552010-02-01 18:53:26 +00002745
2746 // TODO: record more information about failed template arguments
2747 Candidate.DeductionFailure.Result = Result;
2748 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002749 return;
2750 }
Mike Stump11289f42009-09-09 15:08:12 +00002751
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002752 // Add the function template specialization produced by template argument
2753 // deduction as a candidate.
2754 assert(Specialization && "Missing function template specialization?");
John McCallb89836b2010-01-26 01:37:31 +00002755 AddOverloadCandidate(Specialization, Access, Args, NumArgs, CandidateSet,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002756 SuppressUserConversions, ForceRValue);
2757}
Mike Stump11289f42009-09-09 15:08:12 +00002758
Douglas Gregora1f013e2008-11-07 22:36:19 +00002759/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002760/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002761/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002762/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002763/// (which may or may not be the same type as the type that the
2764/// conversion function produces).
2765void
2766Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCallb89836b2010-01-26 01:37:31 +00002767 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002768 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002769 Expr *From, QualType ToType,
2770 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002771 assert(!Conversion->getDescribedFunctionTemplate() &&
2772 "Conversion function templates use AddTemplateConversionCandidate");
2773
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002774 if (!CandidateSet.isNewCandidate(Conversion))
2775 return;
2776
Douglas Gregor27381f32009-11-23 12:27:39 +00002777 // Overload resolution is always an unevaluated context.
2778 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2779
Douglas Gregora1f013e2008-11-07 22:36:19 +00002780 // Add this candidate
2781 CandidateSet.push_back(OverloadCandidate());
2782 OverloadCandidate& Candidate = CandidateSet.back();
2783 Candidate.Function = Conversion;
John McCallb89836b2010-01-26 01:37:31 +00002784 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002785 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002786 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002787 Candidate.FinalConversion.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002788 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002789 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00002790
Douglas Gregor436424c2008-11-18 23:14:02 +00002791 // Determine the implicit conversion sequence for the implicit
2792 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002793 Candidate.Viable = true;
2794 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002795 Candidate.Conversions[0]
2796 = TryObjectArgumentInitialization(From->getType(), Conversion,
2797 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002798 // Conversion functions to a different type in the base class is visible in
2799 // the derived class. So, a derived to base conversion should not participate
2800 // in overload resolution.
2801 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2802 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00002803 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002804 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002805 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002806 return;
2807 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002808
2809 // We won't go through a user-define type conversion function to convert a
2810 // derived to base as such conversions are given Conversion Rank. They only
2811 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2812 QualType FromCanon
2813 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2814 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2815 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2816 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00002817 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002818 return;
2819 }
2820
Douglas Gregora1f013e2008-11-07 22:36:19 +00002821
2822 // To determine what the conversion from the result of calling the
2823 // conversion function to the type we're eventually trying to
2824 // convert to (ToType), we need to synthesize a call to the
2825 // conversion function and attempt copy initialization from it. This
2826 // makes sure that we get the right semantics with respect to
2827 // lvalues/rvalues and the type. Fortunately, we can allocate this
2828 // call on the stack and we don't need its arguments to be
2829 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002830 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002831 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002832 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002833 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002834 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002835
2836 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002837 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2838 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002839 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002840 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002841 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002842 ImplicitConversionSequence ICS =
2843 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002844 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002845 /*ForceRValue=*/false,
2846 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002847
John McCall0d1da222010-01-12 00:44:57 +00002848 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002849 case ImplicitConversionSequence::StandardConversion:
2850 Candidate.FinalConversion = ICS.Standard;
2851 break;
2852
2853 case ImplicitConversionSequence::BadConversion:
2854 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00002855 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002856 break;
2857
2858 default:
Mike Stump11289f42009-09-09 15:08:12 +00002859 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002860 "Can only end up with a standard conversion sequence or failure");
2861 }
2862}
2863
Douglas Gregor05155d82009-08-21 23:19:43 +00002864/// \brief Adds a conversion function template specialization
2865/// candidate to the overload set, using template argument deduction
2866/// to deduce the template arguments of the conversion function
2867/// template from the type that we are converting to (C++
2868/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002869void
Douglas Gregor05155d82009-08-21 23:19:43 +00002870Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCallb89836b2010-01-26 01:37:31 +00002871 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002872 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002873 Expr *From, QualType ToType,
2874 OverloadCandidateSet &CandidateSet) {
2875 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2876 "Only conversion function templates permitted here");
2877
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002878 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2879 return;
2880
John McCallbc077cf2010-02-08 23:07:23 +00002881 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00002882 CXXConversionDecl *Specialization = 0;
2883 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002884 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002885 Specialization, Info)) {
2886 // FIXME: Record what happened with template argument deduction, so
2887 // that we can give the user a beautiful diagnostic.
2888 (void)Result;
2889 return;
2890 }
Mike Stump11289f42009-09-09 15:08:12 +00002891
Douglas Gregor05155d82009-08-21 23:19:43 +00002892 // Add the conversion function template specialization produced by
2893 // template argument deduction as a candidate.
2894 assert(Specialization && "Missing function template specialization?");
John McCallb89836b2010-01-26 01:37:31 +00002895 AddConversionCandidate(Specialization, Access, ActingDC, From, ToType,
2896 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002897}
2898
Douglas Gregorab7897a2008-11-19 22:57:39 +00002899/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2900/// converts the given @c Object to a function pointer via the
2901/// conversion function @c Conversion, and then attempts to call it
2902/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2903/// the type of function that we'll eventually be calling.
2904void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCallb89836b2010-01-26 01:37:31 +00002905 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002906 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002907 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002908 QualType ObjectType,
2909 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002910 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002911 if (!CandidateSet.isNewCandidate(Conversion))
2912 return;
2913
Douglas Gregor27381f32009-11-23 12:27:39 +00002914 // Overload resolution is always an unevaluated context.
2915 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2916
Douglas Gregorab7897a2008-11-19 22:57:39 +00002917 CandidateSet.push_back(OverloadCandidate());
2918 OverloadCandidate& Candidate = CandidateSet.back();
2919 Candidate.Function = 0;
John McCallb89836b2010-01-26 01:37:31 +00002920 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002921 Candidate.Surrogate = Conversion;
2922 Candidate.Viable = true;
2923 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002924 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002925 Candidate.Conversions.resize(NumArgs + 1);
2926
2927 // Determine the implicit conversion sequence for the implicit
2928 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002929 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002930 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002931 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002932 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002933 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00002934 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002935 return;
2936 }
2937
2938 // The first conversion is actually a user-defined conversion whose
2939 // first conversion is ObjectInit's standard conversion (which is
2940 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00002941 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002942 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002943 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002944 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002945 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002946 = Candidate.Conversions[0].UserDefined.Before;
2947 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2948
Mike Stump11289f42009-09-09 15:08:12 +00002949 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002950 unsigned NumArgsInProto = Proto->getNumArgs();
2951
2952 // (C++ 13.3.2p2): A candidate function having fewer than m
2953 // parameters is viable only if it has an ellipsis in its parameter
2954 // list (8.3.5).
2955 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2956 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002957 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002958 return;
2959 }
2960
2961 // Function types don't have any default arguments, so just check if
2962 // we have enough arguments.
2963 if (NumArgs < NumArgsInProto) {
2964 // Not enough arguments.
2965 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002966 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002967 return;
2968 }
2969
2970 // Determine the implicit conversion sequences for each of the
2971 // arguments.
2972 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2973 if (ArgIdx < NumArgsInProto) {
2974 // (C++ 13.3.2p3): for F to be a viable function, there shall
2975 // exist for each argument an implicit conversion sequence
2976 // (13.3.3.1) that converts that argument to the corresponding
2977 // parameter of F.
2978 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002979 Candidate.Conversions[ArgIdx + 1]
2980 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002981 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002982 /*ForceRValue=*/false,
2983 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00002984 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002985 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002986 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002987 break;
2988 }
2989 } else {
2990 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2991 // argument for which there is no corresponding parameter is
2992 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002993 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002994 }
2995 }
2996}
2997
Mike Stump87c57ac2009-05-16 07:39:55 +00002998// FIXME: This will eventually be removed, once we've migrated all of the
2999// operator overloading logic over to the scheme used by binary operators, which
3000// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003001void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003002 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00003003 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003004 OverloadCandidateSet& CandidateSet,
3005 SourceRange OpRange) {
John McCall4c4c1df2010-01-26 03:27:55 +00003006 UnresolvedSet<16> Fns;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003007
3008 QualType T1 = Args[0]->getType();
3009 QualType T2;
3010 if (NumArgs > 1)
3011 T2 = Args[1]->getType();
3012
3013 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003014 if (S)
John McCall4c4c1df2010-01-26 03:27:55 +00003015 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3016 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3017 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3018 CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003019 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003020 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003021}
3022
3023/// \brief Add overload candidates for overloaded operators that are
3024/// member functions.
3025///
3026/// Add the overloaded operator candidates that are member functions
3027/// for the operator Op that was used in an operator expression such
3028/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3029/// CandidateSet will store the added overload candidates. (C++
3030/// [over.match.oper]).
3031void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3032 SourceLocation OpLoc,
3033 Expr **Args, unsigned NumArgs,
3034 OverloadCandidateSet& CandidateSet,
3035 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003036 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3037
3038 // C++ [over.match.oper]p3:
3039 // For a unary operator @ with an operand of a type whose
3040 // cv-unqualified version is T1, and for a binary operator @ with
3041 // a left operand of a type whose cv-unqualified version is T1 and
3042 // a right operand of a type whose cv-unqualified version is T2,
3043 // three sets of candidate functions, designated member
3044 // candidates, non-member candidates and built-in candidates, are
3045 // constructed as follows:
3046 QualType T1 = Args[0]->getType();
3047 QualType T2;
3048 if (NumArgs > 1)
3049 T2 = Args[1]->getType();
3050
3051 // -- If T1 is a class type, the set of member candidates is the
3052 // result of the qualified lookup of T1::operator@
3053 // (13.3.1.1.1); otherwise, the set of member candidates is
3054 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003055 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003056 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003057 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003058 return;
Mike Stump11289f42009-09-09 15:08:12 +00003059
John McCall27b18f82009-11-17 02:14:36 +00003060 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3061 LookupQualifiedName(Operators, T1Rec->getDecl());
3062 Operators.suppressDiagnostics();
3063
Mike Stump11289f42009-09-09 15:08:12 +00003064 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003065 OperEnd = Operators.end();
3066 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003067 ++Oper)
John McCallb89836b2010-01-26 01:37:31 +00003068 AddMethodCandidate(*Oper, Oper.getAccess(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003069 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003070 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003071 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003072}
3073
Douglas Gregora11693b2008-11-12 17:17:38 +00003074/// AddBuiltinCandidate - Add a candidate for a built-in
3075/// operator. ResultTy and ParamTys are the result and parameter types
3076/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003077/// arguments being passed to the candidate. IsAssignmentOperator
3078/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003079/// operator. NumContextualBoolArguments is the number of arguments
3080/// (at the beginning of the argument list) that will be contextually
3081/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003082void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003083 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003084 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003085 bool IsAssignmentOperator,
3086 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003087 // Overload resolution is always an unevaluated context.
3088 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3089
Douglas Gregora11693b2008-11-12 17:17:38 +00003090 // Add this candidate
3091 CandidateSet.push_back(OverloadCandidate());
3092 OverloadCandidate& Candidate = CandidateSet.back();
3093 Candidate.Function = 0;
John McCallb89836b2010-01-26 01:37:31 +00003094 Candidate.Access = AS_none;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003095 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003096 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003097 Candidate.BuiltinTypes.ResultTy = ResultTy;
3098 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3099 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3100
3101 // Determine the implicit conversion sequences for each of the
3102 // arguments.
3103 Candidate.Viable = true;
3104 Candidate.Conversions.resize(NumArgs);
3105 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003106 // C++ [over.match.oper]p4:
3107 // For the built-in assignment operators, conversions of the
3108 // left operand are restricted as follows:
3109 // -- no temporaries are introduced to hold the left operand, and
3110 // -- no user-defined conversions are applied to the left
3111 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003112 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003113 //
3114 // We block these conversions by turning off user-defined
3115 // conversions, since that is the only way that initialization of
3116 // a reference to a non-class type can occur from something that
3117 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003118 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003119 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003120 "Contextual conversion to bool requires bool type");
3121 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3122 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003123 Candidate.Conversions[ArgIdx]
3124 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003125 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003126 /*ForceRValue=*/false,
3127 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003128 }
John McCall0d1da222010-01-12 00:44:57 +00003129 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003130 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003131 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003132 break;
3133 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003134 }
3135}
3136
3137/// BuiltinCandidateTypeSet - A set of types that will be used for the
3138/// candidate operator functions for built-in operators (C++
3139/// [over.built]). The types are separated into pointer types and
3140/// enumeration types.
3141class BuiltinCandidateTypeSet {
3142 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003143 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003144
3145 /// PointerTypes - The set of pointer types that will be used in the
3146 /// built-in candidates.
3147 TypeSet PointerTypes;
3148
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003149 /// MemberPointerTypes - The set of member pointer types that will be
3150 /// used in the built-in candidates.
3151 TypeSet MemberPointerTypes;
3152
Douglas Gregora11693b2008-11-12 17:17:38 +00003153 /// EnumerationTypes - The set of enumeration types that will be
3154 /// used in the built-in candidates.
3155 TypeSet EnumerationTypes;
3156
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003157 /// Sema - The semantic analysis instance where we are building the
3158 /// candidate type set.
3159 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003160
Douglas Gregora11693b2008-11-12 17:17:38 +00003161 /// Context - The AST context in which we will build the type sets.
3162 ASTContext &Context;
3163
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003164 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3165 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003166 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003167
3168public:
3169 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003170 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003171
Mike Stump11289f42009-09-09 15:08:12 +00003172 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003173 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003174
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003175 void AddTypesConvertedFrom(QualType Ty,
3176 SourceLocation Loc,
3177 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003178 bool AllowExplicitConversions,
3179 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003180
3181 /// pointer_begin - First pointer type found;
3182 iterator pointer_begin() { return PointerTypes.begin(); }
3183
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003184 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003185 iterator pointer_end() { return PointerTypes.end(); }
3186
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003187 /// member_pointer_begin - First member pointer type found;
3188 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3189
3190 /// member_pointer_end - Past the last member pointer type found;
3191 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3192
Douglas Gregora11693b2008-11-12 17:17:38 +00003193 /// enumeration_begin - First enumeration type found;
3194 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3195
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003196 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003197 iterator enumeration_end() { return EnumerationTypes.end(); }
3198};
3199
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003200/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003201/// the set of pointer types along with any more-qualified variants of
3202/// that type. For example, if @p Ty is "int const *", this routine
3203/// will add "int const *", "int const volatile *", "int const
3204/// restrict *", and "int const volatile restrict *" to the set of
3205/// pointer types. Returns true if the add of @p Ty itself succeeded,
3206/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003207///
3208/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003209bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003210BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3211 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003212
Douglas Gregora11693b2008-11-12 17:17:38 +00003213 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003214 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003215 return false;
3216
John McCall8ccfcb52009-09-24 19:53:00 +00003217 const PointerType *PointerTy = Ty->getAs<PointerType>();
3218 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003219
John McCall8ccfcb52009-09-24 19:53:00 +00003220 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003221 // Don't add qualified variants of arrays. For one, they're not allowed
3222 // (the qualifier would sink to the element type), and for another, the
3223 // only overload situation where it matters is subscript or pointer +- int,
3224 // and those shouldn't have qualifier variants anyway.
3225 if (PointeeTy->isArrayType())
3226 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003227 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003228 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003229 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003230 bool hasVolatile = VisibleQuals.hasVolatile();
3231 bool hasRestrict = VisibleQuals.hasRestrict();
3232
John McCall8ccfcb52009-09-24 19:53:00 +00003233 // Iterate through all strict supersets of BaseCVR.
3234 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3235 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003236 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3237 // in the types.
3238 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3239 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003240 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3241 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003242 }
3243
3244 return true;
3245}
3246
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003247/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3248/// to the set of pointer types along with any more-qualified variants of
3249/// that type. For example, if @p Ty is "int const *", this routine
3250/// will add "int const *", "int const volatile *", "int const
3251/// restrict *", and "int const volatile restrict *" to the set of
3252/// pointer types. Returns true if the add of @p Ty itself succeeded,
3253/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003254///
3255/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003256bool
3257BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3258 QualType Ty) {
3259 // Insert this type.
3260 if (!MemberPointerTypes.insert(Ty))
3261 return false;
3262
John McCall8ccfcb52009-09-24 19:53:00 +00003263 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3264 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003265
John McCall8ccfcb52009-09-24 19:53:00 +00003266 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003267 // Don't add qualified variants of arrays. For one, they're not allowed
3268 // (the qualifier would sink to the element type), and for another, the
3269 // only overload situation where it matters is subscript or pointer +- int,
3270 // and those shouldn't have qualifier variants anyway.
3271 if (PointeeTy->isArrayType())
3272 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003273 const Type *ClassTy = PointerTy->getClass();
3274
3275 // Iterate through all strict supersets of the pointee type's CVR
3276 // qualifiers.
3277 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3278 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3279 if ((CVR | BaseCVR) != CVR) continue;
3280
3281 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3282 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003283 }
3284
3285 return true;
3286}
3287
Douglas Gregora11693b2008-11-12 17:17:38 +00003288/// AddTypesConvertedFrom - Add each of the types to which the type @p
3289/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003290/// primarily interested in pointer types and enumeration types. We also
3291/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003292/// AllowUserConversions is true if we should look at the conversion
3293/// functions of a class type, and AllowExplicitConversions if we
3294/// should also include the explicit conversion functions of a class
3295/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003296void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003297BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003298 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003299 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003300 bool AllowExplicitConversions,
3301 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003302 // Only deal with canonical types.
3303 Ty = Context.getCanonicalType(Ty);
3304
3305 // Look through reference types; they aren't part of the type of an
3306 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003307 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003308 Ty = RefTy->getPointeeType();
3309
3310 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003311 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003312
Sebastian Redl65ae2002009-11-05 16:36:20 +00003313 // If we're dealing with an array type, decay to the pointer.
3314 if (Ty->isArrayType())
3315 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3316
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003317 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003318 QualType PointeeTy = PointerTy->getPointeeType();
3319
3320 // Insert our type, and its more-qualified variants, into the set
3321 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003322 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003323 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003324 } else if (Ty->isMemberPointerType()) {
3325 // Member pointers are far easier, since the pointee can't be converted.
3326 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3327 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003328 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003329 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003330 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003331 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003332 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003333 // No conversion functions in incomplete types.
3334 return;
3335 }
Mike Stump11289f42009-09-09 15:08:12 +00003336
Douglas Gregora11693b2008-11-12 17:17:38 +00003337 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003338 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003339 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003340 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003341 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003342
Mike Stump11289f42009-09-09 15:08:12 +00003343 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003344 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003345 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003346 continue;
3347
John McCalld14a8642009-11-21 08:51:07 +00003348 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003349 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003350 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003351 VisibleQuals);
3352 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003353 }
3354 }
3355 }
3356}
3357
Douglas Gregor84605ae2009-08-24 13:43:27 +00003358/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3359/// the volatile- and non-volatile-qualified assignment operators for the
3360/// given type to the candidate set.
3361static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3362 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003363 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003364 unsigned NumArgs,
3365 OverloadCandidateSet &CandidateSet) {
3366 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003367
Douglas Gregor84605ae2009-08-24 13:43:27 +00003368 // T& operator=(T&, T)
3369 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3370 ParamTypes[1] = T;
3371 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3372 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003373
Douglas Gregor84605ae2009-08-24 13:43:27 +00003374 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3375 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003376 ParamTypes[0]
3377 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003378 ParamTypes[1] = T;
3379 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003380 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003381 }
3382}
Mike Stump11289f42009-09-09 15:08:12 +00003383
Sebastian Redl1054fae2009-10-25 17:03:50 +00003384/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3385/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003386static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3387 Qualifiers VRQuals;
3388 const RecordType *TyRec;
3389 if (const MemberPointerType *RHSMPType =
3390 ArgExpr->getType()->getAs<MemberPointerType>())
3391 TyRec = cast<RecordType>(RHSMPType->getClass());
3392 else
3393 TyRec = ArgExpr->getType()->getAs<RecordType>();
3394 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003395 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003396 VRQuals.addVolatile();
3397 VRQuals.addRestrict();
3398 return VRQuals;
3399 }
3400
3401 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003402 if (!ClassDecl->hasDefinition())
3403 return VRQuals;
3404
John McCallad371252010-01-20 00:46:10 +00003405 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003406 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003407
John McCallad371252010-01-20 00:46:10 +00003408 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003409 E = Conversions->end(); I != E; ++I) {
3410 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003411 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3412 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3413 CanTy = ResTypeRef->getPointeeType();
3414 // Need to go down the pointer/mempointer chain and add qualifiers
3415 // as see them.
3416 bool done = false;
3417 while (!done) {
3418 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3419 CanTy = ResTypePtr->getPointeeType();
3420 else if (const MemberPointerType *ResTypeMPtr =
3421 CanTy->getAs<MemberPointerType>())
3422 CanTy = ResTypeMPtr->getPointeeType();
3423 else
3424 done = true;
3425 if (CanTy.isVolatileQualified())
3426 VRQuals.addVolatile();
3427 if (CanTy.isRestrictQualified())
3428 VRQuals.addRestrict();
3429 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3430 return VRQuals;
3431 }
3432 }
3433 }
3434 return VRQuals;
3435}
3436
Douglas Gregord08452f2008-11-19 15:42:04 +00003437/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3438/// operator overloads to the candidate set (C++ [over.built]), based
3439/// on the operator @p Op and the arguments given. For example, if the
3440/// operator is a binary '+', this routine might add "int
3441/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003442void
Mike Stump11289f42009-09-09 15:08:12 +00003443Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003444 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003445 Expr **Args, unsigned NumArgs,
3446 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003447 // The set of "promoted arithmetic types", which are the arithmetic
3448 // types are that preserved by promotion (C++ [over.built]p2). Note
3449 // that the first few of these types are the promoted integral
3450 // types; these types need to be first.
3451 // FIXME: What about complex?
3452 const unsigned FirstIntegralType = 0;
3453 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003454 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003455 LastPromotedIntegralType = 13;
3456 const unsigned FirstPromotedArithmeticType = 7,
3457 LastPromotedArithmeticType = 16;
3458 const unsigned NumArithmeticTypes = 16;
3459 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003460 Context.BoolTy, Context.CharTy, Context.WCharTy,
3461// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003462 Context.SignedCharTy, Context.ShortTy,
3463 Context.UnsignedCharTy, Context.UnsignedShortTy,
3464 Context.IntTy, Context.LongTy, Context.LongLongTy,
3465 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3466 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3467 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003468 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3469 "Invalid first promoted integral type");
3470 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3471 == Context.UnsignedLongLongTy &&
3472 "Invalid last promoted integral type");
3473 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3474 "Invalid first promoted arithmetic type");
3475 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3476 == Context.LongDoubleTy &&
3477 "Invalid last promoted arithmetic type");
3478
Douglas Gregora11693b2008-11-12 17:17:38 +00003479 // Find all of the types that the arguments can convert to, but only
3480 // if the operator we're looking at has built-in operator candidates
3481 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003482 Qualifiers VisibleTypeConversionsQuals;
3483 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003484 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3485 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3486
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003487 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003488 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3489 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003490 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003491 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003492 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003493 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003494 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003495 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003496 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003497 true,
3498 (Op == OO_Exclaim ||
3499 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003500 Op == OO_PipePipe),
3501 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003502 }
3503
3504 bool isComparison = false;
3505 switch (Op) {
3506 case OO_None:
3507 case NUM_OVERLOADED_OPERATORS:
3508 assert(false && "Expected an overloaded operator");
3509 break;
3510
Douglas Gregord08452f2008-11-19 15:42:04 +00003511 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003512 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003513 goto UnaryStar;
3514 else
3515 goto BinaryStar;
3516 break;
3517
3518 case OO_Plus: // '+' is either unary or binary
3519 if (NumArgs == 1)
3520 goto UnaryPlus;
3521 else
3522 goto BinaryPlus;
3523 break;
3524
3525 case OO_Minus: // '-' is either unary or binary
3526 if (NumArgs == 1)
3527 goto UnaryMinus;
3528 else
3529 goto BinaryMinus;
3530 break;
3531
3532 case OO_Amp: // '&' is either unary or binary
3533 if (NumArgs == 1)
3534 goto UnaryAmp;
3535 else
3536 goto BinaryAmp;
3537
3538 case OO_PlusPlus:
3539 case OO_MinusMinus:
3540 // C++ [over.built]p3:
3541 //
3542 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3543 // is either volatile or empty, there exist candidate operator
3544 // functions of the form
3545 //
3546 // VQ T& operator++(VQ T&);
3547 // T operator++(VQ T&, int);
3548 //
3549 // C++ [over.built]p4:
3550 //
3551 // For every pair (T, VQ), where T is an arithmetic type other
3552 // than bool, and VQ is either volatile or empty, there exist
3553 // candidate operator functions of the form
3554 //
3555 // VQ T& operator--(VQ T&);
3556 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003557 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003558 Arith < NumArithmeticTypes; ++Arith) {
3559 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003560 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003561 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003562
3563 // Non-volatile version.
3564 if (NumArgs == 1)
3565 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3566 else
3567 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003568 // heuristic to reduce number of builtin candidates in the set.
3569 // Add volatile version only if there are conversions to a volatile type.
3570 if (VisibleTypeConversionsQuals.hasVolatile()) {
3571 // Volatile version
3572 ParamTypes[0]
3573 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3574 if (NumArgs == 1)
3575 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3576 else
3577 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3578 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003579 }
3580
3581 // C++ [over.built]p5:
3582 //
3583 // For every pair (T, VQ), where T is a cv-qualified or
3584 // cv-unqualified object type, and VQ is either volatile or
3585 // empty, there exist candidate operator functions of the form
3586 //
3587 // T*VQ& operator++(T*VQ&);
3588 // T*VQ& operator--(T*VQ&);
3589 // T* operator++(T*VQ&, int);
3590 // T* operator--(T*VQ&, int);
3591 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3592 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3593 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003594 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003595 continue;
3596
Mike Stump11289f42009-09-09 15:08:12 +00003597 QualType ParamTypes[2] = {
3598 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003599 };
Mike Stump11289f42009-09-09 15:08:12 +00003600
Douglas Gregord08452f2008-11-19 15:42:04 +00003601 // Without volatile
3602 if (NumArgs == 1)
3603 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3604 else
3605 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3606
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003607 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3608 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003609 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003610 ParamTypes[0]
3611 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003612 if (NumArgs == 1)
3613 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3614 else
3615 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3616 }
3617 }
3618 break;
3619
3620 UnaryStar:
3621 // C++ [over.built]p6:
3622 // For every cv-qualified or cv-unqualified object type T, there
3623 // exist candidate operator functions of the form
3624 //
3625 // T& operator*(T*);
3626 //
3627 // C++ [over.built]p7:
3628 // For every function type T, there exist candidate operator
3629 // functions of the form
3630 // T& operator*(T*);
3631 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3632 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3633 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003634 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003635 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003636 &ParamTy, Args, 1, CandidateSet);
3637 }
3638 break;
3639
3640 UnaryPlus:
3641 // C++ [over.built]p8:
3642 // For every type T, there exist candidate operator functions of
3643 // the form
3644 //
3645 // T* operator+(T*);
3646 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3647 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3648 QualType ParamTy = *Ptr;
3649 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3650 }
Mike Stump11289f42009-09-09 15:08:12 +00003651
Douglas Gregord08452f2008-11-19 15:42:04 +00003652 // Fall through
3653
3654 UnaryMinus:
3655 // C++ [over.built]p9:
3656 // For every promoted arithmetic type T, there exist candidate
3657 // operator functions of the form
3658 //
3659 // T operator+(T);
3660 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003661 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003662 Arith < LastPromotedArithmeticType; ++Arith) {
3663 QualType ArithTy = ArithmeticTypes[Arith];
3664 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3665 }
3666 break;
3667
3668 case OO_Tilde:
3669 // C++ [over.built]p10:
3670 // For every promoted integral type T, there exist candidate
3671 // operator functions of the form
3672 //
3673 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003674 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003675 Int < LastPromotedIntegralType; ++Int) {
3676 QualType IntTy = ArithmeticTypes[Int];
3677 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3678 }
3679 break;
3680
Douglas Gregora11693b2008-11-12 17:17:38 +00003681 case OO_New:
3682 case OO_Delete:
3683 case OO_Array_New:
3684 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003685 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003686 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003687 break;
3688
3689 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003690 UnaryAmp:
3691 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003692 // C++ [over.match.oper]p3:
3693 // -- For the operator ',', the unary operator '&', or the
3694 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003695 break;
3696
Douglas Gregor84605ae2009-08-24 13:43:27 +00003697 case OO_EqualEqual:
3698 case OO_ExclaimEqual:
3699 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003700 // For every pointer to member type T, there exist candidate operator
3701 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003702 //
3703 // bool operator==(T,T);
3704 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003705 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003706 MemPtr = CandidateTypes.member_pointer_begin(),
3707 MemPtrEnd = CandidateTypes.member_pointer_end();
3708 MemPtr != MemPtrEnd;
3709 ++MemPtr) {
3710 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3711 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3712 }
Mike Stump11289f42009-09-09 15:08:12 +00003713
Douglas Gregor84605ae2009-08-24 13:43:27 +00003714 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003715
Douglas Gregora11693b2008-11-12 17:17:38 +00003716 case OO_Less:
3717 case OO_Greater:
3718 case OO_LessEqual:
3719 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003720 // C++ [over.built]p15:
3721 //
3722 // For every pointer or enumeration type T, there exist
3723 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003724 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003725 // bool operator<(T, T);
3726 // bool operator>(T, T);
3727 // bool operator<=(T, T);
3728 // bool operator>=(T, T);
3729 // bool operator==(T, T);
3730 // bool operator!=(T, T);
3731 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3732 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3733 QualType ParamTypes[2] = { *Ptr, *Ptr };
3734 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3735 }
Mike Stump11289f42009-09-09 15:08:12 +00003736 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003737 = CandidateTypes.enumeration_begin();
3738 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3739 QualType ParamTypes[2] = { *Enum, *Enum };
3740 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3741 }
3742
3743 // Fall through.
3744 isComparison = true;
3745
Douglas Gregord08452f2008-11-19 15:42:04 +00003746 BinaryPlus:
3747 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003748 if (!isComparison) {
3749 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3750
3751 // C++ [over.built]p13:
3752 //
3753 // For every cv-qualified or cv-unqualified object type T
3754 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003755 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003756 // T* operator+(T*, ptrdiff_t);
3757 // T& operator[](T*, ptrdiff_t); [BELOW]
3758 // T* operator-(T*, ptrdiff_t);
3759 // T* operator+(ptrdiff_t, T*);
3760 // T& operator[](ptrdiff_t, T*); [BELOW]
3761 //
3762 // C++ [over.built]p14:
3763 //
3764 // For every T, where T is a pointer to object type, there
3765 // exist candidate operator functions of the form
3766 //
3767 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003768 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003769 = CandidateTypes.pointer_begin();
3770 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3771 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3772
3773 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3774 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3775
3776 if (Op == OO_Plus) {
3777 // T* operator+(ptrdiff_t, T*);
3778 ParamTypes[0] = ParamTypes[1];
3779 ParamTypes[1] = *Ptr;
3780 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3781 } else {
3782 // ptrdiff_t operator-(T, T);
3783 ParamTypes[1] = *Ptr;
3784 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3785 Args, 2, CandidateSet);
3786 }
3787 }
3788 }
3789 // Fall through
3790
Douglas Gregora11693b2008-11-12 17:17:38 +00003791 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003792 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003793 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003794 // C++ [over.built]p12:
3795 //
3796 // For every pair of promoted arithmetic types L and R, there
3797 // exist candidate operator functions of the form
3798 //
3799 // LR operator*(L, R);
3800 // LR operator/(L, R);
3801 // LR operator+(L, R);
3802 // LR operator-(L, R);
3803 // bool operator<(L, R);
3804 // bool operator>(L, R);
3805 // bool operator<=(L, R);
3806 // bool operator>=(L, R);
3807 // bool operator==(L, R);
3808 // bool operator!=(L, R);
3809 //
3810 // where LR is the result of the usual arithmetic conversions
3811 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003812 //
3813 // C++ [over.built]p24:
3814 //
3815 // For every pair of promoted arithmetic types L and R, there exist
3816 // candidate operator functions of the form
3817 //
3818 // LR operator?(bool, L, R);
3819 //
3820 // where LR is the result of the usual arithmetic conversions
3821 // between types L and R.
3822 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003823 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003824 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003825 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003826 Right < LastPromotedArithmeticType; ++Right) {
3827 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003828 QualType Result
3829 = isComparison
3830 ? Context.BoolTy
3831 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003832 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3833 }
3834 }
3835 break;
3836
3837 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003838 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003839 case OO_Caret:
3840 case OO_Pipe:
3841 case OO_LessLess:
3842 case OO_GreaterGreater:
3843 // C++ [over.built]p17:
3844 //
3845 // For every pair of promoted integral types L and R, there
3846 // exist candidate operator functions of the form
3847 //
3848 // LR operator%(L, R);
3849 // LR operator&(L, R);
3850 // LR operator^(L, R);
3851 // LR operator|(L, R);
3852 // L operator<<(L, R);
3853 // L operator>>(L, R);
3854 //
3855 // where LR is the result of the usual arithmetic conversions
3856 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003857 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003858 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003859 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003860 Right < LastPromotedIntegralType; ++Right) {
3861 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3862 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3863 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003864 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003865 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3866 }
3867 }
3868 break;
3869
3870 case OO_Equal:
3871 // C++ [over.built]p20:
3872 //
3873 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003874 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003875 // empty, there exist candidate operator functions of the form
3876 //
3877 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003878 for (BuiltinCandidateTypeSet::iterator
3879 Enum = CandidateTypes.enumeration_begin(),
3880 EnumEnd = CandidateTypes.enumeration_end();
3881 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003882 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003883 CandidateSet);
3884 for (BuiltinCandidateTypeSet::iterator
3885 MemPtr = CandidateTypes.member_pointer_begin(),
3886 MemPtrEnd = CandidateTypes.member_pointer_end();
3887 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003888 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003889 CandidateSet);
3890 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003891
3892 case OO_PlusEqual:
3893 case OO_MinusEqual:
3894 // C++ [over.built]p19:
3895 //
3896 // For every pair (T, VQ), where T is any type and VQ is either
3897 // volatile or empty, there exist candidate operator functions
3898 // of the form
3899 //
3900 // T*VQ& operator=(T*VQ&, T*);
3901 //
3902 // C++ [over.built]p21:
3903 //
3904 // For every pair (T, VQ), where T is a cv-qualified or
3905 // cv-unqualified object type and VQ is either volatile or
3906 // empty, there exist candidate operator functions of the form
3907 //
3908 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3909 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3910 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3911 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3912 QualType ParamTypes[2];
3913 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3914
3915 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003916 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003917 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3918 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003919
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003920 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3921 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003922 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003923 ParamTypes[0]
3924 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003925 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3926 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003927 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003928 }
3929 // Fall through.
3930
3931 case OO_StarEqual:
3932 case OO_SlashEqual:
3933 // C++ [over.built]p18:
3934 //
3935 // For every triple (L, VQ, R), where L is an arithmetic type,
3936 // VQ is either volatile or empty, and R is a promoted
3937 // arithmetic type, there exist candidate operator functions of
3938 // the form
3939 //
3940 // VQ L& operator=(VQ L&, R);
3941 // VQ L& operator*=(VQ L&, R);
3942 // VQ L& operator/=(VQ L&, R);
3943 // VQ L& operator+=(VQ L&, R);
3944 // VQ L& operator-=(VQ L&, R);
3945 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003946 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003947 Right < LastPromotedArithmeticType; ++Right) {
3948 QualType ParamTypes[2];
3949 ParamTypes[1] = ArithmeticTypes[Right];
3950
3951 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003952 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003953 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3954 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003955
3956 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003957 if (VisibleTypeConversionsQuals.hasVolatile()) {
3958 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3959 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3960 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3961 /*IsAssigmentOperator=*/Op == OO_Equal);
3962 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003963 }
3964 }
3965 break;
3966
3967 case OO_PercentEqual:
3968 case OO_LessLessEqual:
3969 case OO_GreaterGreaterEqual:
3970 case OO_AmpEqual:
3971 case OO_CaretEqual:
3972 case OO_PipeEqual:
3973 // C++ [over.built]p22:
3974 //
3975 // For every triple (L, VQ, R), where L is an integral type, VQ
3976 // is either volatile or empty, and R is a promoted integral
3977 // type, there exist candidate operator functions of the form
3978 //
3979 // VQ L& operator%=(VQ L&, R);
3980 // VQ L& operator<<=(VQ L&, R);
3981 // VQ L& operator>>=(VQ L&, R);
3982 // VQ L& operator&=(VQ L&, R);
3983 // VQ L& operator^=(VQ L&, R);
3984 // VQ L& operator|=(VQ L&, R);
3985 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003986 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003987 Right < LastPromotedIntegralType; ++Right) {
3988 QualType ParamTypes[2];
3989 ParamTypes[1] = ArithmeticTypes[Right];
3990
3991 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003992 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003993 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003994 if (VisibleTypeConversionsQuals.hasVolatile()) {
3995 // Add this built-in operator as a candidate (VQ is 'volatile').
3996 ParamTypes[0] = ArithmeticTypes[Left];
3997 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3998 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3999 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4000 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004001 }
4002 }
4003 break;
4004
Douglas Gregord08452f2008-11-19 15:42:04 +00004005 case OO_Exclaim: {
4006 // C++ [over.operator]p23:
4007 //
4008 // There also exist candidate operator functions of the form
4009 //
Mike Stump11289f42009-09-09 15:08:12 +00004010 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004011 // bool operator&&(bool, bool); [BELOW]
4012 // bool operator||(bool, bool); [BELOW]
4013 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004014 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4015 /*IsAssignmentOperator=*/false,
4016 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004017 break;
4018 }
4019
Douglas Gregora11693b2008-11-12 17:17:38 +00004020 case OO_AmpAmp:
4021 case OO_PipePipe: {
4022 // C++ [over.operator]p23:
4023 //
4024 // There also exist candidate operator functions of the form
4025 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004026 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004027 // bool operator&&(bool, bool);
4028 // bool operator||(bool, bool);
4029 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004030 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4031 /*IsAssignmentOperator=*/false,
4032 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004033 break;
4034 }
4035
4036 case OO_Subscript:
4037 // C++ [over.built]p13:
4038 //
4039 // For every cv-qualified or cv-unqualified object type T there
4040 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004041 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004042 // T* operator+(T*, ptrdiff_t); [ABOVE]
4043 // T& operator[](T*, ptrdiff_t);
4044 // T* operator-(T*, ptrdiff_t); [ABOVE]
4045 // T* operator+(ptrdiff_t, T*); [ABOVE]
4046 // T& operator[](ptrdiff_t, T*);
4047 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4048 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4049 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004050 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004051 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004052
4053 // T& operator[](T*, ptrdiff_t)
4054 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4055
4056 // T& operator[](ptrdiff_t, T*);
4057 ParamTypes[0] = ParamTypes[1];
4058 ParamTypes[1] = *Ptr;
4059 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4060 }
4061 break;
4062
4063 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004064 // C++ [over.built]p11:
4065 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4066 // C1 is the same type as C2 or is a derived class of C2, T is an object
4067 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4068 // there exist candidate operator functions of the form
4069 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4070 // where CV12 is the union of CV1 and CV2.
4071 {
4072 for (BuiltinCandidateTypeSet::iterator Ptr =
4073 CandidateTypes.pointer_begin();
4074 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4075 QualType C1Ty = (*Ptr);
4076 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004077 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004078 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004079 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004080 if (!isa<RecordType>(C1))
4081 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004082 // heuristic to reduce number of builtin candidates in the set.
4083 // Add volatile/restrict version only if there are conversions to a
4084 // volatile/restrict type.
4085 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4086 continue;
4087 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4088 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004089 }
4090 for (BuiltinCandidateTypeSet::iterator
4091 MemPtr = CandidateTypes.member_pointer_begin(),
4092 MemPtrEnd = CandidateTypes.member_pointer_end();
4093 MemPtr != MemPtrEnd; ++MemPtr) {
4094 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4095 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004096 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004097 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4098 break;
4099 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4100 // build CV12 T&
4101 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004102 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4103 T.isVolatileQualified())
4104 continue;
4105 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4106 T.isRestrictQualified())
4107 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004108 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004109 QualType ResultTy = Context.getLValueReferenceType(T);
4110 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4111 }
4112 }
4113 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004114 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004115
4116 case OO_Conditional:
4117 // Note that we don't consider the first argument, since it has been
4118 // contextually converted to bool long ago. The candidates below are
4119 // therefore added as binary.
4120 //
4121 // C++ [over.built]p24:
4122 // For every type T, where T is a pointer or pointer-to-member type,
4123 // there exist candidate operator functions of the form
4124 //
4125 // T operator?(bool, T, T);
4126 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004127 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4128 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4129 QualType ParamTypes[2] = { *Ptr, *Ptr };
4130 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4131 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004132 for (BuiltinCandidateTypeSet::iterator Ptr =
4133 CandidateTypes.member_pointer_begin(),
4134 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4135 QualType ParamTypes[2] = { *Ptr, *Ptr };
4136 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4137 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004138 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004139 }
4140}
4141
Douglas Gregore254f902009-02-04 00:32:51 +00004142/// \brief Add function candidates found via argument-dependent lookup
4143/// to the set of overloading candidates.
4144///
4145/// This routine performs argument-dependent name lookup based on the
4146/// given function name (which may also be an operator name) and adds
4147/// all of the overload candidates found by ADL to the overload
4148/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004149void
Douglas Gregore254f902009-02-04 00:32:51 +00004150Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004151 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004152 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004153 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004154 OverloadCandidateSet& CandidateSet,
4155 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004156 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004157
John McCall91f61fc2010-01-26 06:04:06 +00004158 // FIXME: This approach for uniquing ADL results (and removing
4159 // redundant candidates from the set) relies on pointer-equality,
4160 // which means we need to key off the canonical decl. However,
4161 // always going back to the canonical decl might not get us the
4162 // right set of default arguments. What default arguments are
4163 // we supposed to consider on ADL candidates, anyway?
4164
Douglas Gregorcabea402009-09-22 15:41:20 +00004165 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004166 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004167
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004168 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004169 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4170 CandEnd = CandidateSet.end();
4171 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004172 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004173 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004174 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004175 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004176 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004177
4178 // For each of the ADL candidates we found, add it to the overload
4179 // set.
John McCall8fe68082010-01-26 07:16:45 +00004180 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00004181 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004182 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004183 continue;
4184
John McCallb89836b2010-01-26 01:37:31 +00004185 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00004186 false, false, PartialOverloading);
4187 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004188 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCallb89836b2010-01-26 01:37:31 +00004189 AS_none, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004190 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004191 }
Douglas Gregore254f902009-02-04 00:32:51 +00004192}
4193
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004194/// isBetterOverloadCandidate - Determines whether the first overload
4195/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004196bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004197Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004198 const OverloadCandidate& Cand2,
4199 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004200 // Define viable functions to be better candidates than non-viable
4201 // functions.
4202 if (!Cand2.Viable)
4203 return Cand1.Viable;
4204 else if (!Cand1.Viable)
4205 return false;
4206
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004207 // C++ [over.match.best]p1:
4208 //
4209 // -- if F is a static member function, ICS1(F) is defined such
4210 // that ICS1(F) is neither better nor worse than ICS1(G) for
4211 // any function G, and, symmetrically, ICS1(G) is neither
4212 // better nor worse than ICS1(F).
4213 unsigned StartArg = 0;
4214 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4215 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004216
Douglas Gregord3cb3562009-07-07 23:38:56 +00004217 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004218 // A viable function F1 is defined to be a better function than another
4219 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004220 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004221 unsigned NumArgs = Cand1.Conversions.size();
4222 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4223 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004224 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004225 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4226 Cand2.Conversions[ArgIdx])) {
4227 case ImplicitConversionSequence::Better:
4228 // Cand1 has a better conversion sequence.
4229 HasBetterConversion = true;
4230 break;
4231
4232 case ImplicitConversionSequence::Worse:
4233 // Cand1 can't be better than Cand2.
4234 return false;
4235
4236 case ImplicitConversionSequence::Indistinguishable:
4237 // Do nothing.
4238 break;
4239 }
4240 }
4241
Mike Stump11289f42009-09-09 15:08:12 +00004242 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004243 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004244 if (HasBetterConversion)
4245 return true;
4246
Mike Stump11289f42009-09-09 15:08:12 +00004247 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004248 // specialization, or, if not that,
4249 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4250 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4251 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004252
4253 // -- F1 and F2 are function template specializations, and the function
4254 // template for F1 is more specialized than the template for F2
4255 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004256 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004257 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4258 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004259 if (FunctionTemplateDecl *BetterTemplate
4260 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4261 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004262 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004263 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4264 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004265 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004266
Douglas Gregora1f013e2008-11-07 22:36:19 +00004267 // -- the context is an initialization by user-defined conversion
4268 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4269 // from the return type of F1 to the destination type (i.e.,
4270 // the type of the entity being initialized) is a better
4271 // conversion sequence than the standard conversion sequence
4272 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004273 if (Cand1.Function && Cand2.Function &&
4274 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004275 isa<CXXConversionDecl>(Cand2.Function)) {
4276 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4277 Cand2.FinalConversion)) {
4278 case ImplicitConversionSequence::Better:
4279 // Cand1 has a better conversion sequence.
4280 return true;
4281
4282 case ImplicitConversionSequence::Worse:
4283 // Cand1 can't be better than Cand2.
4284 return false;
4285
4286 case ImplicitConversionSequence::Indistinguishable:
4287 // Do nothing
4288 break;
4289 }
4290 }
4291
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004292 return false;
4293}
4294
Mike Stump11289f42009-09-09 15:08:12 +00004295/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004296/// within an overload candidate set.
4297///
4298/// \param CandidateSet the set of candidate functions.
4299///
4300/// \param Loc the location of the function name (or operator symbol) for
4301/// which overload resolution occurs.
4302///
Mike Stump11289f42009-09-09 15:08:12 +00004303/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004304/// function, Best points to the candidate function found.
4305///
4306/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004307OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4308 SourceLocation Loc,
4309 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004310 // Find the best viable function.
4311 Best = CandidateSet.end();
4312 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4313 Cand != CandidateSet.end(); ++Cand) {
4314 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004315 if (Best == CandidateSet.end() ||
4316 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004317 Best = Cand;
4318 }
4319 }
4320
4321 // If we didn't find any viable functions, abort.
4322 if (Best == CandidateSet.end())
4323 return OR_No_Viable_Function;
4324
4325 // Make sure that this function is better than every other viable
4326 // function. If not, we have an ambiguity.
4327 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4328 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004329 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004330 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004331 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004332 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004333 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004334 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004335 }
Mike Stump11289f42009-09-09 15:08:12 +00004336
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004337 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004338 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004339 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004340 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004341 return OR_Deleted;
4342
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004343 // C++ [basic.def.odr]p2:
4344 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004345 // when referred to from a potentially-evaluated expression. [Note: this
4346 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004347 // (clause 13), user-defined conversions (12.3.2), allocation function for
4348 // placement new (5.3.4), as well as non-default initialization (8.5).
4349 if (Best->Function)
4350 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004351 return OR_Success;
4352}
4353
John McCall53262c92010-01-12 02:15:36 +00004354namespace {
4355
4356enum OverloadCandidateKind {
4357 oc_function,
4358 oc_method,
4359 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004360 oc_function_template,
4361 oc_method_template,
4362 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004363 oc_implicit_default_constructor,
4364 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004365 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004366};
4367
John McCalle1ac8d12010-01-13 00:25:19 +00004368OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4369 FunctionDecl *Fn,
4370 std::string &Description) {
4371 bool isTemplate = false;
4372
4373 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4374 isTemplate = true;
4375 Description = S.getTemplateArgumentBindingsText(
4376 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4377 }
John McCallfd0b2f82010-01-06 09:43:14 +00004378
4379 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004380 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004381 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004382
John McCall53262c92010-01-12 02:15:36 +00004383 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4384 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004385 }
4386
4387 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4388 // This actually gets spelled 'candidate function' for now, but
4389 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004390 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004391 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004392
4393 assert(Meth->isCopyAssignment()
4394 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004395 return oc_implicit_copy_assignment;
4396 }
4397
John McCalle1ac8d12010-01-13 00:25:19 +00004398 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004399}
4400
4401} // end anonymous namespace
4402
4403// Notes the location of an overload candidate.
4404void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004405 std::string FnDesc;
4406 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4407 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4408 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004409}
4410
John McCall0d1da222010-01-12 00:44:57 +00004411/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4412/// "lead" diagnostic; it will be given two arguments, the source and
4413/// target types of the conversion.
4414void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4415 SourceLocation CaretLoc,
4416 const PartialDiagnostic &PDiag) {
4417 Diag(CaretLoc, PDiag)
4418 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4419 for (AmbiguousConversionSequence::const_iterator
4420 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4421 NoteOverloadCandidate(*I);
4422 }
John McCall12f97bc2010-01-08 04:41:39 +00004423}
4424
John McCall0d1da222010-01-12 00:44:57 +00004425namespace {
4426
John McCall6a61b522010-01-13 09:16:55 +00004427void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4428 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4429 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004430 assert(Cand->Function && "for now, candidate must be a function");
4431 FunctionDecl *Fn = Cand->Function;
4432
4433 // There's a conversion slot for the object argument if this is a
4434 // non-constructor method. Note that 'I' corresponds the
4435 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004436 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004437 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004438 if (I == 0)
4439 isObjectArgument = true;
4440 else
4441 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004442 }
4443
John McCalle1ac8d12010-01-13 00:25:19 +00004444 std::string FnDesc;
4445 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4446
John McCall6a61b522010-01-13 09:16:55 +00004447 Expr *FromExpr = Conv.Bad.FromExpr;
4448 QualType FromTy = Conv.Bad.getFromType();
4449 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004450
John McCallfb7ad0f2010-02-02 02:42:52 +00004451 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00004452 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00004453 Expr *E = FromExpr->IgnoreParens();
4454 if (isa<UnaryOperator>(E))
4455 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004456 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004457
4458 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4459 << (unsigned) FnKind << FnDesc
4460 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4461 << ToTy << Name << I+1;
4462 return;
4463 }
4464
John McCall6d174642010-01-23 08:10:49 +00004465 // Do some hand-waving analysis to see if the non-viability is due
4466 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004467 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4468 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4469 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4470 CToTy = RT->getPointeeType();
4471 else {
4472 // TODO: detect and diagnose the full richness of const mismatches.
4473 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4474 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4475 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4476 }
4477
4478 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4479 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4480 // It is dumb that we have to do this here.
4481 while (isa<ArrayType>(CFromTy))
4482 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4483 while (isa<ArrayType>(CToTy))
4484 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4485
4486 Qualifiers FromQs = CFromTy.getQualifiers();
4487 Qualifiers ToQs = CToTy.getQualifiers();
4488
4489 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4490 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4491 << (unsigned) FnKind << FnDesc
4492 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4493 << FromTy
4494 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4495 << (unsigned) isObjectArgument << I+1;
4496 return;
4497 }
4498
4499 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4500 assert(CVR && "unexpected qualifiers mismatch");
4501
4502 if (isObjectArgument) {
4503 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4504 << (unsigned) FnKind << FnDesc
4505 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4506 << FromTy << (CVR - 1);
4507 } else {
4508 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4509 << (unsigned) FnKind << FnDesc
4510 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4511 << FromTy << (CVR - 1) << I+1;
4512 }
4513 return;
4514 }
4515
John McCall6d174642010-01-23 08:10:49 +00004516 // Diagnose references or pointers to incomplete types differently,
4517 // since it's far from impossible that the incompleteness triggered
4518 // the failure.
4519 QualType TempFromTy = FromTy.getNonReferenceType();
4520 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4521 TempFromTy = PTy->getPointeeType();
4522 if (TempFromTy->isIncompleteType()) {
4523 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4524 << (unsigned) FnKind << FnDesc
4525 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4526 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4527 return;
4528 }
4529
John McCall47000992010-01-14 03:28:57 +00004530 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004531 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4532 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004533 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004534 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004535}
4536
4537void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4538 unsigned NumFormalArgs) {
4539 // TODO: treat calls to a missing default constructor as a special case
4540
4541 FunctionDecl *Fn = Cand->Function;
4542 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4543
4544 unsigned MinParams = Fn->getMinRequiredArguments();
4545
4546 // at least / at most / exactly
4547 unsigned mode, modeCount;
4548 if (NumFormalArgs < MinParams) {
4549 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4550 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4551 mode = 0; // "at least"
4552 else
4553 mode = 2; // "exactly"
4554 modeCount = MinParams;
4555 } else {
4556 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4557 if (MinParams != FnTy->getNumArgs())
4558 mode = 1; // "at most"
4559 else
4560 mode = 2; // "exactly"
4561 modeCount = FnTy->getNumArgs();
4562 }
4563
4564 std::string Description;
4565 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4566
4567 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4568 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004569}
4570
John McCall8b9ed552010-02-01 18:53:26 +00004571/// Diagnose a failed template-argument deduction.
4572void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4573 Expr **Args, unsigned NumArgs) {
4574 FunctionDecl *Fn = Cand->Function; // pattern
4575
4576 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4577 Cand->DeductionFailure.TemplateParameter);
4578
4579 switch (Cand->DeductionFailure.Result) {
4580 case Sema::TDK_Success:
4581 llvm_unreachable("TDK_success while diagnosing bad deduction");
4582
4583 case Sema::TDK_Incomplete: {
4584 NamedDecl *ParamD;
4585 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4586 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4587 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4588 assert(ParamD && "no parameter found for incomplete deduction result");
4589 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4590 << ParamD->getDeclName();
4591 return;
4592 }
4593
4594 // TODO: diagnose these individually, then kill off
4595 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4596 case Sema::TDK_InstantiationDepth:
4597 case Sema::TDK_Inconsistent:
4598 case Sema::TDK_InconsistentQuals:
4599 case Sema::TDK_SubstitutionFailure:
4600 case Sema::TDK_NonDeducedMismatch:
4601 case Sema::TDK_TooManyArguments:
4602 case Sema::TDK_TooFewArguments:
4603 case Sema::TDK_InvalidExplicitArguments:
4604 case Sema::TDK_FailedOverloadResolution:
4605 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4606 return;
4607 }
4608}
4609
4610/// Generates a 'note' diagnostic for an overload candidate. We've
4611/// already generated a primary error at the call site.
4612///
4613/// It really does need to be a single diagnostic with its caret
4614/// pointed at the candidate declaration. Yes, this creates some
4615/// major challenges of technical writing. Yes, this makes pointing
4616/// out problems with specific arguments quite awkward. It's still
4617/// better than generating twenty screens of text for every failed
4618/// overload.
4619///
4620/// It would be great to be able to express per-candidate problems
4621/// more richly for those diagnostic clients that cared, but we'd
4622/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00004623void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4624 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004625 FunctionDecl *Fn = Cand->Function;
4626
John McCall12f97bc2010-01-08 04:41:39 +00004627 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004628 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004629 std::string FnDesc;
4630 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004631
4632 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004633 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004634 return;
John McCall12f97bc2010-01-08 04:41:39 +00004635 }
4636
John McCalle1ac8d12010-01-13 00:25:19 +00004637 // We don't really have anything else to say about viable candidates.
4638 if (Cand->Viable) {
4639 S.NoteOverloadCandidate(Fn);
4640 return;
4641 }
John McCall0d1da222010-01-12 00:44:57 +00004642
John McCall6a61b522010-01-13 09:16:55 +00004643 switch (Cand->FailureKind) {
4644 case ovl_fail_too_many_arguments:
4645 case ovl_fail_too_few_arguments:
4646 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004647
John McCall6a61b522010-01-13 09:16:55 +00004648 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00004649 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4650
John McCallfe796dd2010-01-23 05:17:32 +00004651 case ovl_fail_trivial_conversion:
4652 case ovl_fail_bad_final_conversion:
John McCall6a61b522010-01-13 09:16:55 +00004653 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004654
John McCall65eb8792010-02-25 01:37:24 +00004655 case ovl_fail_bad_conversion: {
4656 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
4657 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00004658 if (Cand->Conversions[I].isBad())
4659 return DiagnoseBadConversion(S, Cand, I);
4660
4661 // FIXME: this currently happens when we're called from SemaInit
4662 // when user-conversion overload fails. Figure out how to handle
4663 // those conditions and diagnose them well.
4664 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004665 }
John McCall65eb8792010-02-25 01:37:24 +00004666 }
John McCalld3224162010-01-08 00:58:21 +00004667}
4668
4669void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4670 // Desugar the type of the surrogate down to a function type,
4671 // retaining as many typedefs as possible while still showing
4672 // the function type (and, therefore, its parameter types).
4673 QualType FnType = Cand->Surrogate->getConversionType();
4674 bool isLValueReference = false;
4675 bool isRValueReference = false;
4676 bool isPointer = false;
4677 if (const LValueReferenceType *FnTypeRef =
4678 FnType->getAs<LValueReferenceType>()) {
4679 FnType = FnTypeRef->getPointeeType();
4680 isLValueReference = true;
4681 } else if (const RValueReferenceType *FnTypeRef =
4682 FnType->getAs<RValueReferenceType>()) {
4683 FnType = FnTypeRef->getPointeeType();
4684 isRValueReference = true;
4685 }
4686 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4687 FnType = FnTypePtr->getPointeeType();
4688 isPointer = true;
4689 }
4690 // Desugar down to a function type.
4691 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4692 // Reconstruct the pointer/reference as appropriate.
4693 if (isPointer) FnType = S.Context.getPointerType(FnType);
4694 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4695 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4696
4697 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4698 << FnType;
4699}
4700
4701void NoteBuiltinOperatorCandidate(Sema &S,
4702 const char *Opc,
4703 SourceLocation OpLoc,
4704 OverloadCandidate *Cand) {
4705 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4706 std::string TypeStr("operator");
4707 TypeStr += Opc;
4708 TypeStr += "(";
4709 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4710 if (Cand->Conversions.size() == 1) {
4711 TypeStr += ")";
4712 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4713 } else {
4714 TypeStr += ", ";
4715 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4716 TypeStr += ")";
4717 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4718 }
4719}
4720
4721void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4722 OverloadCandidate *Cand) {
4723 unsigned NoOperands = Cand->Conversions.size();
4724 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4725 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00004726 if (ICS.isBad()) break; // all meaningless after first invalid
4727 if (!ICS.isAmbiguous()) continue;
4728
4729 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4730 PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00004731 }
4732}
4733
John McCall3712d9e2010-01-15 23:32:50 +00004734SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4735 if (Cand->Function)
4736 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00004737 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00004738 return Cand->Surrogate->getLocation();
4739 return SourceLocation();
4740}
4741
John McCallad2587a2010-01-12 00:48:53 +00004742struct CompareOverloadCandidatesForDisplay {
4743 Sema &S;
4744 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00004745
4746 bool operator()(const OverloadCandidate *L,
4747 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00004748 // Fast-path this check.
4749 if (L == R) return false;
4750
John McCall12f97bc2010-01-08 04:41:39 +00004751 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00004752 if (L->Viable) {
4753 if (!R->Viable) return true;
4754
4755 // TODO: introduce a tri-valued comparison for overload
4756 // candidates. Would be more worthwhile if we had a sort
4757 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00004758 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
4759 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00004760 } else if (R->Viable)
4761 return false;
John McCall12f97bc2010-01-08 04:41:39 +00004762
John McCall3712d9e2010-01-15 23:32:50 +00004763 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00004764
John McCall3712d9e2010-01-15 23:32:50 +00004765 // Criteria by which we can sort non-viable candidates:
4766 if (!L->Viable) {
4767 // 1. Arity mismatches come after other candidates.
4768 if (L->FailureKind == ovl_fail_too_many_arguments ||
4769 L->FailureKind == ovl_fail_too_few_arguments)
4770 return false;
4771 if (R->FailureKind == ovl_fail_too_many_arguments ||
4772 R->FailureKind == ovl_fail_too_few_arguments)
4773 return true;
John McCall12f97bc2010-01-08 04:41:39 +00004774
John McCallfe796dd2010-01-23 05:17:32 +00004775 // 2. Bad conversions come first and are ordered by the number
4776 // of bad conversions and quality of good conversions.
4777 if (L->FailureKind == ovl_fail_bad_conversion) {
4778 if (R->FailureKind != ovl_fail_bad_conversion)
4779 return true;
4780
4781 // If there's any ordering between the defined conversions...
4782 // FIXME: this might not be transitive.
4783 assert(L->Conversions.size() == R->Conversions.size());
4784
4785 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00004786 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
4787 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00004788 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
4789 R->Conversions[I])) {
4790 case ImplicitConversionSequence::Better:
4791 leftBetter++;
4792 break;
4793
4794 case ImplicitConversionSequence::Worse:
4795 leftBetter--;
4796 break;
4797
4798 case ImplicitConversionSequence::Indistinguishable:
4799 break;
4800 }
4801 }
4802 if (leftBetter > 0) return true;
4803 if (leftBetter < 0) return false;
4804
4805 } else if (R->FailureKind == ovl_fail_bad_conversion)
4806 return false;
4807
John McCall3712d9e2010-01-15 23:32:50 +00004808 // TODO: others?
4809 }
4810
4811 // Sort everything else by location.
4812 SourceLocation LLoc = GetLocationForCandidate(L);
4813 SourceLocation RLoc = GetLocationForCandidate(R);
4814
4815 // Put candidates without locations (e.g. builtins) at the end.
4816 if (LLoc.isInvalid()) return false;
4817 if (RLoc.isInvalid()) return true;
4818
4819 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00004820 }
4821};
4822
John McCallfe796dd2010-01-23 05:17:32 +00004823/// CompleteNonViableCandidate - Normally, overload resolution only
4824/// computes up to the first
4825void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
4826 Expr **Args, unsigned NumArgs) {
4827 assert(!Cand->Viable);
4828
4829 // Don't do anything on failures other than bad conversion.
4830 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
4831
4832 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00004833 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00004834 unsigned ConvCount = Cand->Conversions.size();
4835 while (true) {
4836 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
4837 ConvIdx++;
4838 if (Cand->Conversions[ConvIdx - 1].isBad())
4839 break;
4840 }
4841
4842 if (ConvIdx == ConvCount)
4843 return;
4844
John McCall65eb8792010-02-25 01:37:24 +00004845 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
4846 "remaining conversion is initialized?");
4847
John McCallfe796dd2010-01-23 05:17:32 +00004848 // FIXME: these should probably be preserved from the overload
4849 // operation somehow.
4850 bool SuppressUserConversions = false;
4851 bool ForceRValue = false;
4852
4853 const FunctionProtoType* Proto;
4854 unsigned ArgIdx = ConvIdx;
4855
4856 if (Cand->IsSurrogate) {
4857 QualType ConvType
4858 = Cand->Surrogate->getConversionType().getNonReferenceType();
4859 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4860 ConvType = ConvPtrType->getPointeeType();
4861 Proto = ConvType->getAs<FunctionProtoType>();
4862 ArgIdx--;
4863 } else if (Cand->Function) {
4864 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
4865 if (isa<CXXMethodDecl>(Cand->Function) &&
4866 !isa<CXXConstructorDecl>(Cand->Function))
4867 ArgIdx--;
4868 } else {
4869 // Builtin binary operator with a bad first conversion.
4870 assert(ConvCount <= 3);
4871 for (; ConvIdx != ConvCount; ++ConvIdx)
4872 Cand->Conversions[ConvIdx]
4873 = S.TryCopyInitialization(Args[ConvIdx],
4874 Cand->BuiltinTypes.ParamTypes[ConvIdx],
4875 SuppressUserConversions, ForceRValue,
4876 /*InOverloadResolution*/ true);
4877 return;
4878 }
4879
4880 // Fill in the rest of the conversions.
4881 unsigned NumArgsInProto = Proto->getNumArgs();
4882 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
4883 if (ArgIdx < NumArgsInProto)
4884 Cand->Conversions[ConvIdx]
4885 = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx),
4886 SuppressUserConversions, ForceRValue,
4887 /*InOverloadResolution=*/true);
4888 else
4889 Cand->Conversions[ConvIdx].setEllipsis();
4890 }
4891}
4892
John McCalld3224162010-01-08 00:58:21 +00004893} // end anonymous namespace
4894
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004895/// PrintOverloadCandidates - When overload resolution fails, prints
4896/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00004897/// set.
Mike Stump11289f42009-09-09 15:08:12 +00004898void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004899Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00004900 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00004901 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004902 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004903 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00004904 // Sort the candidates by viability and position. Sorting directly would
4905 // be prohibitive, so we make a set of pointers and sort those.
4906 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4907 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4908 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4909 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00004910 Cand != LastCand; ++Cand) {
4911 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00004912 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00004913 else if (OCD == OCD_AllCandidates) {
4914 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
4915 Cands.push_back(Cand);
4916 }
4917 }
4918
John McCallad2587a2010-01-12 00:48:53 +00004919 std::sort(Cands.begin(), Cands.end(),
4920 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00004921
John McCall0d1da222010-01-12 00:44:57 +00004922 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00004923
John McCall12f97bc2010-01-08 04:41:39 +00004924 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4925 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4926 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004927
John McCalld3224162010-01-08 00:58:21 +00004928 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00004929 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00004930 else if (Cand->IsSurrogate)
4931 NoteSurrogateCandidate(*this, Cand);
4932
4933 // This a builtin candidate. We do not, in general, want to list
4934 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00004935 else if (Cand->Viable) {
4936 // Generally we only see ambiguities including viable builtin
4937 // operators if overload resolution got screwed up by an
4938 // ambiguous user-defined conversion.
4939 //
4940 // FIXME: It's quite possible for different conversions to see
4941 // different ambiguities, though.
4942 if (!ReportedAmbiguousConversions) {
4943 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4944 ReportedAmbiguousConversions = true;
4945 }
John McCalld3224162010-01-08 00:58:21 +00004946
John McCall0d1da222010-01-12 00:44:57 +00004947 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00004948 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00004949 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004950 }
4951}
4952
John McCall1acbbb52010-02-02 06:20:04 +00004953static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, NamedDecl *D,
John McCall58cc69d2010-01-27 01:50:18 +00004954 AccessSpecifier AS) {
4955 if (isa<UnresolvedLookupExpr>(E))
4956 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D, AS);
4957
4958 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D, AS);
4959}
4960
Douglas Gregorcd695e52008-11-10 20:40:00 +00004961/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4962/// an overloaded function (C++ [over.over]), where @p From is an
4963/// expression with overloaded function type and @p ToType is the type
4964/// we're trying to resolve to. For example:
4965///
4966/// @code
4967/// int f(double);
4968/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004969///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004970/// int (*pfd)(double) = f; // selects f(double)
4971/// @endcode
4972///
4973/// This routine returns the resulting FunctionDecl if it could be
4974/// resolved, and NULL otherwise. When @p Complain is true, this
4975/// routine will emit diagnostics if there is an error.
4976FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004977Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004978 bool Complain) {
4979 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004980 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004981 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004982 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004983 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004984 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004985 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004986 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004987 FunctionType = MemTypePtr->getPointeeType();
4988 IsMember = true;
4989 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004990
4991 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004992 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004993 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004994 return 0;
4995
4996 // Find the actual overloaded function declaration.
John McCall1acbbb52010-02-02 06:20:04 +00004997 if (From->getType() != Context.OverloadTy)
4998 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004999
Douglas Gregorcd695e52008-11-10 20:40:00 +00005000 // C++ [over.over]p1:
5001 // [...] [Note: any redundant set of parentheses surrounding the
5002 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005003 // C++ [over.over]p1:
5004 // [...] The overloaded function name can be preceded by the &
5005 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005006 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5007 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5008 if (OvlExpr->hasExplicitTemplateArgs()) {
5009 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5010 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005011 }
5012
Douglas Gregorcd695e52008-11-10 20:40:00 +00005013 // Look through all of the overloaded functions, searching for one
5014 // whose type matches exactly.
John McCall58cc69d2010-01-27 01:50:18 +00005015 UnresolvedSet<4> Matches; // contains only FunctionDecls
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005016 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005017 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5018 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005019 // Look through any using declarations to find the underlying function.
5020 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5021
Douglas Gregorcd695e52008-11-10 20:40:00 +00005022 // C++ [over.over]p3:
5023 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005024 // targets of type "pointer-to-function" or "reference-to-function."
5025 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005026 // type "pointer-to-member-function."
5027 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005028
Mike Stump11289f42009-09-09 15:08:12 +00005029 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005030 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005031 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005032 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005033 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005034 // static when converting to member pointer.
5035 if (Method->isStatic() == IsMember)
5036 continue;
5037 } else if (IsMember)
5038 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005039
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005040 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005041 // If the name is a function template, template argument deduction is
5042 // done (14.8.2.2), and if the argument deduction succeeds, the
5043 // resulting template argument list is used to generate a single
5044 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005045 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005046 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005047 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005048 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005049 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005050 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005051 FunctionType, Specialization, Info)) {
5052 // FIXME: make a note of the failed deduction for diagnostics.
5053 (void)Result;
5054 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005055 // FIXME: If the match isn't exact, shouldn't we just drop this as
5056 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005057 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005058 == Context.getCanonicalType(Specialization->getType()));
John McCall58cc69d2010-01-27 01:50:18 +00005059 Matches.addDecl(cast<FunctionDecl>(Specialization->getCanonicalDecl()),
5060 I.getAccess());
Douglas Gregor9b146582009-07-08 20:55:45 +00005061 }
John McCalld14a8642009-11-21 08:51:07 +00005062
5063 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005064 }
Mike Stump11289f42009-09-09 15:08:12 +00005065
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005066 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005067 // Skip non-static functions when converting to pointer, and static
5068 // when converting to member pointer.
5069 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005070 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005071
5072 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005073 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005074 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005075 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005076 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005077
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005078 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005079 QualType ResultTy;
5080 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5081 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5082 ResultTy)) {
John McCall58cc69d2010-01-27 01:50:18 +00005083 Matches.addDecl(cast<FunctionDecl>(FunDecl->getCanonicalDecl()),
5084 I.getAccess());
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005085 FoundNonTemplateFunction = true;
5086 }
Mike Stump11289f42009-09-09 15:08:12 +00005087 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005088 }
5089
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005090 // If there were 0 or 1 matches, we're done.
5091 if (Matches.empty())
5092 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005093 else if (Matches.size() == 1) {
John McCall58cc69d2010-01-27 01:50:18 +00005094 FunctionDecl *Result = cast<FunctionDecl>(*Matches.begin());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005095 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005096 if (Complain)
5097 CheckUnresolvedAccess(*this, OvlExpr, Result, Matches.begin().getAccess());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005098 return Result;
5099 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005100
5101 // C++ [over.over]p4:
5102 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005103 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005104 // [...] and any given function template specialization F1 is
5105 // eliminated if the set contains a second function template
5106 // specialization whose function template is more specialized
5107 // than the function template of F1 according to the partial
5108 // ordering rules of 14.5.5.2.
5109
5110 // The algorithm specified above is quadratic. We instead use a
5111 // two-pass algorithm (similar to the one used to identify the
5112 // best viable function in an overload set) that identifies the
5113 // best function template (if it exists).
John McCall58cc69d2010-01-27 01:50:18 +00005114
5115 UnresolvedSetIterator Result =
5116 getMostSpecialized(Matches.begin(), Matches.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005117 TPOC_Other, From->getLocStart(),
5118 PDiag(),
5119 PDiag(diag::err_addr_ovl_ambiguous)
John McCall58cc69d2010-01-27 01:50:18 +00005120 << Matches[0]->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005121 PDiag(diag::note_ovl_candidate)
5122 << (unsigned) oc_function_template);
John McCall58cc69d2010-01-27 01:50:18 +00005123 assert(Result != Matches.end() && "no most-specialized template");
5124 MarkDeclarationReferenced(From->getLocStart(), *Result);
5125 if (Complain)
5126 CheckUnresolvedAccess(*this, OvlExpr, *Result, Result.getAccess());
5127 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005128 }
Mike Stump11289f42009-09-09 15:08:12 +00005129
Douglas Gregorfae1d712009-09-26 03:56:17 +00005130 // [...] any function template specializations in the set are
5131 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005132 for (unsigned I = 0, N = Matches.size(); I != N; ) {
5133 if (cast<FunctionDecl>(Matches[I].getDecl())->getPrimaryTemplate() == 0)
5134 ++I;
5135 else {
5136 Matches.erase(I);
5137 --N;
5138 }
5139 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005140
Mike Stump11289f42009-09-09 15:08:12 +00005141 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005142 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005143 if (Matches.size() == 1) {
5144 UnresolvedSetIterator Match = Matches.begin();
5145 MarkDeclarationReferenced(From->getLocStart(), *Match);
5146 if (Complain)
5147 CheckUnresolvedAccess(*this, OvlExpr, *Match, Match.getAccess());
5148 return cast<FunctionDecl>(*Match);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005149 }
Mike Stump11289f42009-09-09 15:08:12 +00005150
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005151 // FIXME: We should probably return the same thing that BestViableFunction
5152 // returns (even if we issue the diagnostics here).
5153 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall58cc69d2010-01-27 01:50:18 +00005154 << Matches[0]->getDeclName();
5155 for (UnresolvedSetIterator I = Matches.begin(),
5156 E = Matches.end(); I != E; ++I)
5157 NoteOverloadCandidate(cast<FunctionDecl>(*I));
Douglas Gregorcd695e52008-11-10 20:40:00 +00005158 return 0;
5159}
5160
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005161/// \brief Given an expression that refers to an overloaded function, try to
5162/// resolve that overloaded function expression down to a single function.
5163///
5164/// This routine can only resolve template-ids that refer to a single function
5165/// template, where that template-id refers to a single template whose template
5166/// arguments are either provided by the template-id or have defaults,
5167/// as described in C++0x [temp.arg.explicit]p3.
5168FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5169 // C++ [over.over]p1:
5170 // [...] [Note: any redundant set of parentheses surrounding the
5171 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005172 // C++ [over.over]p1:
5173 // [...] The overloaded function name can be preceded by the &
5174 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005175
5176 if (From->getType() != Context.OverloadTy)
5177 return 0;
5178
5179 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005180
5181 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005182 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005183 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005184
5185 TemplateArgumentListInfo ExplicitTemplateArgs;
5186 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005187
5188 // Look through all of the overloaded functions, searching for one
5189 // whose type matches exactly.
5190 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005191 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5192 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005193 // C++0x [temp.arg.explicit]p3:
5194 // [...] In contexts where deduction is done and fails, or in contexts
5195 // where deduction is not done, if a template argument list is
5196 // specified and it, along with any default template arguments,
5197 // identifies a single function template specialization, then the
5198 // template-id is an lvalue for the function template specialization.
5199 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5200
5201 // C++ [over.over]p2:
5202 // If the name is a function template, template argument deduction is
5203 // done (14.8.2.2), and if the argument deduction succeeds, the
5204 // resulting template argument list is used to generate a single
5205 // function template specialization, which is added to the set of
5206 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005207 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005208 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005209 if (TemplateDeductionResult Result
5210 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5211 Specialization, Info)) {
5212 // FIXME: make a note of the failed deduction for diagnostics.
5213 (void)Result;
5214 continue;
5215 }
5216
5217 // Multiple matches; we can't resolve to a single declaration.
5218 if (Matched)
5219 return 0;
5220
5221 Matched = Specialization;
5222 }
5223
5224 return Matched;
5225}
5226
Douglas Gregorcabea402009-09-22 15:41:20 +00005227/// \brief Add a single candidate to the overload set.
5228static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00005229 NamedDecl *Callee,
John McCallb89836b2010-01-26 01:37:31 +00005230 AccessSpecifier Access,
John McCall6b51f282009-11-23 01:53:49 +00005231 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005232 Expr **Args, unsigned NumArgs,
5233 OverloadCandidateSet &CandidateSet,
5234 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005235 if (isa<UsingShadowDecl>(Callee))
5236 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5237
Douglas Gregorcabea402009-09-22 15:41:20 +00005238 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005239 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCallb89836b2010-01-26 01:37:31 +00005240 S.AddOverloadCandidate(Func, Access, Args, NumArgs, CandidateSet,
5241 false, false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005242 return;
John McCalld14a8642009-11-21 08:51:07 +00005243 }
5244
5245 if (FunctionTemplateDecl *FuncTemplate
5246 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCallb89836b2010-01-26 01:37:31 +00005247 S.AddTemplateOverloadCandidate(FuncTemplate, Access, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005248 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005249 return;
5250 }
5251
5252 assert(false && "unhandled case in overloaded call candidate");
5253
5254 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005255}
5256
5257/// \brief Add the overload candidates named by callee and/or found by argument
5258/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005259void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005260 Expr **Args, unsigned NumArgs,
5261 OverloadCandidateSet &CandidateSet,
5262 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005263
5264#ifndef NDEBUG
5265 // Verify that ArgumentDependentLookup is consistent with the rules
5266 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005267 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005268 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5269 // and let Y be the lookup set produced by argument dependent
5270 // lookup (defined as follows). If X contains
5271 //
5272 // -- a declaration of a class member, or
5273 //
5274 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005275 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005276 //
5277 // -- a declaration that is neither a function or a function
5278 // template
5279 //
5280 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005281
John McCall57500772009-12-16 12:17:52 +00005282 if (ULE->requiresADL()) {
5283 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5284 E = ULE->decls_end(); I != E; ++I) {
5285 assert(!(*I)->getDeclContext()->isRecord());
5286 assert(isa<UsingShadowDecl>(*I) ||
5287 !(*I)->getDeclContext()->isFunctionOrMethod());
5288 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005289 }
5290 }
5291#endif
5292
John McCall57500772009-12-16 12:17:52 +00005293 // It would be nice to avoid this copy.
5294 TemplateArgumentListInfo TABuffer;
5295 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5296 if (ULE->hasExplicitTemplateArgs()) {
5297 ULE->copyTemplateArgumentsInto(TABuffer);
5298 ExplicitTemplateArgs = &TABuffer;
5299 }
5300
5301 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5302 E = ULE->decls_end(); I != E; ++I)
John McCallb89836b2010-01-26 01:37:31 +00005303 AddOverloadedCallCandidate(*this, *I, I.getAccess(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005304 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005305 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005306
John McCall57500772009-12-16 12:17:52 +00005307 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005308 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5309 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005310 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005311 CandidateSet,
5312 PartialOverloading);
5313}
John McCalld681c392009-12-16 08:11:27 +00005314
John McCall57500772009-12-16 12:17:52 +00005315static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5316 Expr **Args, unsigned NumArgs) {
5317 Fn->Destroy(SemaRef.Context);
5318 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5319 Args[Arg]->Destroy(SemaRef.Context);
5320 return SemaRef.ExprError();
5321}
5322
John McCalld681c392009-12-16 08:11:27 +00005323/// Attempts to recover from a call where no functions were found.
5324///
5325/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005326static Sema::OwningExprResult
5327BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5328 UnresolvedLookupExpr *ULE,
5329 SourceLocation LParenLoc,
5330 Expr **Args, unsigned NumArgs,
5331 SourceLocation *CommaLocs,
5332 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005333
5334 CXXScopeSpec SS;
5335 if (ULE->getQualifier()) {
5336 SS.setScopeRep(ULE->getQualifier());
5337 SS.setRange(ULE->getQualifierRange());
5338 }
5339
John McCall57500772009-12-16 12:17:52 +00005340 TemplateArgumentListInfo TABuffer;
5341 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5342 if (ULE->hasExplicitTemplateArgs()) {
5343 ULE->copyTemplateArgumentsInto(TABuffer);
5344 ExplicitTemplateArgs = &TABuffer;
5345 }
5346
John McCalld681c392009-12-16 08:11:27 +00005347 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5348 Sema::LookupOrdinaryName);
Douglas Gregor598b08f2009-12-31 05:20:13 +00005349 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall57500772009-12-16 12:17:52 +00005350 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005351
John McCall57500772009-12-16 12:17:52 +00005352 assert(!R.empty() && "lookup results empty despite recovery");
5353
5354 // Build an implicit member call if appropriate. Just drop the
5355 // casts and such from the call, we don't really care.
5356 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5357 if ((*R.begin())->isCXXClassMember())
5358 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5359 else if (ExplicitTemplateArgs)
5360 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5361 else
5362 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5363
5364 if (NewFn.isInvalid())
5365 return Destroy(SemaRef, Fn, Args, NumArgs);
5366
5367 Fn->Destroy(SemaRef.Context);
5368
5369 // This shouldn't cause an infinite loop because we're giving it
5370 // an expression with non-empty lookup results, which should never
5371 // end up here.
5372 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5373 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5374 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005375}
Douglas Gregorcabea402009-09-22 15:41:20 +00005376
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005377/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005378/// (which eventually refers to the declaration Func) and the call
5379/// arguments Args/NumArgs, attempt to resolve the function call down
5380/// to a specific function. If overload resolution succeeds, returns
5381/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005382/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005383/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005384Sema::OwningExprResult
5385Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5386 SourceLocation LParenLoc,
5387 Expr **Args, unsigned NumArgs,
5388 SourceLocation *CommaLocs,
5389 SourceLocation RParenLoc) {
5390#ifndef NDEBUG
5391 if (ULE->requiresADL()) {
5392 // To do ADL, we must have found an unqualified name.
5393 assert(!ULE->getQualifier() && "qualified name with ADL");
5394
5395 // We don't perform ADL for implicit declarations of builtins.
5396 // Verify that this was correctly set up.
5397 FunctionDecl *F;
5398 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5399 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5400 F->getBuiltinID() && F->isImplicit())
5401 assert(0 && "performing ADL for builtin");
5402
5403 // We don't perform ADL in C.
5404 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5405 }
5406#endif
5407
John McCallbc077cf2010-02-08 23:07:23 +00005408 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005409
John McCall57500772009-12-16 12:17:52 +00005410 // Add the functions denoted by the callee to the set of candidate
5411 // functions, including those from argument-dependent lookup.
5412 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005413
5414 // If we found nothing, try to recover.
5415 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5416 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005417 if (CandidateSet.empty())
5418 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5419 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005420
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005421 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005422 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005423 case OR_Success: {
5424 FunctionDecl *FDecl = Best->Function;
John McCall58cc69d2010-01-27 01:50:18 +00005425 CheckUnresolvedLookupAccess(ULE, FDecl, Best->getAccess());
John McCall57500772009-12-16 12:17:52 +00005426 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5427 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5428 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005429
5430 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005431 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005432 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005433 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005434 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005435 break;
5436
5437 case OR_Ambiguous:
5438 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005439 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005440 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005441 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005442
5443 case OR_Deleted:
5444 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5445 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005446 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005447 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005448 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005449 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005450 }
5451
5452 // Overload resolution failed. Destroy all of the subexpressions and
5453 // return NULL.
5454 Fn->Destroy(Context);
5455 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5456 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005457 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005458}
5459
John McCall4c4c1df2010-01-26 03:27:55 +00005460static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00005461 return Functions.size() > 1 ||
5462 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5463}
5464
Douglas Gregor084d8552009-03-13 23:49:33 +00005465/// \brief Create a unary operation that may resolve to an overloaded
5466/// operator.
5467///
5468/// \param OpLoc The location of the operator itself (e.g., '*').
5469///
5470/// \param OpcIn The UnaryOperator::Opcode that describes this
5471/// operator.
5472///
5473/// \param Functions The set of non-member functions that will be
5474/// considered by overload resolution. The caller needs to build this
5475/// set based on the context using, e.g.,
5476/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5477/// set should not contain any member functions; those will be added
5478/// by CreateOverloadedUnaryOp().
5479///
5480/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00005481Sema::OwningExprResult
5482Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5483 const UnresolvedSetImpl &Fns,
5484 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005485 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5486 Expr *Input = (Expr *)input.get();
5487
5488 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5489 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5490 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5491
5492 Expr *Args[2] = { Input, 0 };
5493 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005494
Douglas Gregor084d8552009-03-13 23:49:33 +00005495 // For post-increment and post-decrement, add the implicit '0' as
5496 // the second argument, so that we know this is a post-increment or
5497 // post-decrement.
5498 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5499 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005500 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005501 SourceLocation());
5502 NumArgs = 2;
5503 }
5504
5505 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00005506 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005507 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005508 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005509 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005510 /*ADL*/ true, IsOverloaded(Fns));
5511 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00005512
Douglas Gregor084d8552009-03-13 23:49:33 +00005513 input.release();
5514 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5515 &Args[0], NumArgs,
5516 Context.DependentTy,
5517 OpLoc));
5518 }
5519
5520 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005521 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005522
5523 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005524 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00005525
5526 // Add operator candidates that are member functions.
5527 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5528
John McCall4c4c1df2010-01-26 03:27:55 +00005529 // Add candidates from ADL.
5530 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00005531 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00005532 /*ExplicitTemplateArgs*/ 0,
5533 CandidateSet);
5534
Douglas Gregor084d8552009-03-13 23:49:33 +00005535 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005536 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005537
5538 // Perform overload resolution.
5539 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005540 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005541 case OR_Success: {
5542 // We found a built-in operator or an overloaded operator.
5543 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005544
Douglas Gregor084d8552009-03-13 23:49:33 +00005545 if (FnDecl) {
5546 // We matched an overloaded operator. Build a call to that
5547 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005548
Douglas Gregor084d8552009-03-13 23:49:33 +00005549 // Convert the arguments.
5550 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00005551 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5552
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005553 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00005554 return ExprError();
5555 } else {
5556 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005557 OwningExprResult InputInit
5558 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005559 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005560 SourceLocation(),
5561 move(input));
5562 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005563 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005564
Douglas Gregore6600372009-12-23 17:40:29 +00005565 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005566 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005567 }
5568
5569 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005570 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005571
Douglas Gregor084d8552009-03-13 23:49:33 +00005572 // Build the actual expression node.
5573 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5574 SourceLocation());
5575 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005576
Douglas Gregor084d8552009-03-13 23:49:33 +00005577 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005578 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005579 ExprOwningPtr<CallExpr> TheCall(this,
5580 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005581 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005582
5583 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5584 FnDecl))
5585 return ExprError();
5586
5587 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005588 } else {
5589 // We matched a built-in operator. Convert the arguments, then
5590 // break out so that we will build the appropriate built-in
5591 // operator node.
5592 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005593 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005594 return ExprError();
5595
5596 break;
5597 }
5598 }
5599
5600 case OR_No_Viable_Function:
5601 // No viable function; fall through to handling this as a
5602 // built-in operator, which will produce an error message for us.
5603 break;
5604
5605 case OR_Ambiguous:
5606 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5607 << UnaryOperator::getOpcodeStr(Opc)
5608 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005609 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005610 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005611 return ExprError();
5612
5613 case OR_Deleted:
5614 Diag(OpLoc, diag::err_ovl_deleted_oper)
5615 << Best->Function->isDeleted()
5616 << UnaryOperator::getOpcodeStr(Opc)
5617 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005618 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005619 return ExprError();
5620 }
5621
5622 // Either we found no viable overloaded operator or we matched a
5623 // built-in operator. In either case, fall through to trying to
5624 // build a built-in operation.
5625 input.release();
5626 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5627}
5628
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005629/// \brief Create a binary operation that may resolve to an overloaded
5630/// operator.
5631///
5632/// \param OpLoc The location of the operator itself (e.g., '+').
5633///
5634/// \param OpcIn The BinaryOperator::Opcode that describes this
5635/// operator.
5636///
5637/// \param Functions The set of non-member functions that will be
5638/// considered by overload resolution. The caller needs to build this
5639/// set based on the context using, e.g.,
5640/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5641/// set should not contain any member functions; those will be added
5642/// by CreateOverloadedBinOp().
5643///
5644/// \param LHS Left-hand argument.
5645/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005646Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005647Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005648 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00005649 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005650 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005651 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005652 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005653
5654 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5655 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5656 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5657
5658 // If either side is type-dependent, create an appropriate dependent
5659 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005660 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00005661 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005662 // If there are no functions to store, just build a dependent
5663 // BinaryOperator or CompoundAssignment.
5664 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5665 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5666 Context.DependentTy, OpLoc));
5667
5668 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5669 Context.DependentTy,
5670 Context.DependentTy,
5671 Context.DependentTy,
5672 OpLoc));
5673 }
John McCall4c4c1df2010-01-26 03:27:55 +00005674
5675 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00005676 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005677 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005678 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005679 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005680 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00005681
John McCall4c4c1df2010-01-26 03:27:55 +00005682 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005683 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00005684 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005685 Context.DependentTy,
5686 OpLoc));
5687 }
5688
5689 // If this is the .* operator, which is not overloadable, just
5690 // create a built-in binary operator.
5691 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00005692 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005693
Sebastian Redl6a96bf72009-11-18 23:10:33 +00005694 // If this is the assignment operator, we only perform overload resolution
5695 // if the left-hand side is a class or enumeration type. This is actually
5696 // a hack. The standard requires that we do overload resolution between the
5697 // various built-in candidates, but as DR507 points out, this can lead to
5698 // problems. So we do it this way, which pretty much follows what GCC does.
5699 // Note that we go the traditional code path for compound assignment forms.
5700 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00005701 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005702
Douglas Gregor084d8552009-03-13 23:49:33 +00005703 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005704 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005705
5706 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005707 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005708
5709 // Add operator candidates that are member functions.
5710 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5711
John McCall4c4c1df2010-01-26 03:27:55 +00005712 // Add candidates from ADL.
5713 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5714 Args, 2,
5715 /*ExplicitTemplateArgs*/ 0,
5716 CandidateSet);
5717
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005718 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005719 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005720
5721 // Perform overload resolution.
5722 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005723 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005724 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005725 // We found a built-in operator or an overloaded operator.
5726 FunctionDecl *FnDecl = Best->Function;
5727
5728 if (FnDecl) {
5729 // We matched an overloaded operator. Build a call to that
5730 // operator.
5731
5732 // Convert the arguments.
5733 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00005734 // Best->Access is only meaningful for class members.
5735 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5736
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005737 OwningExprResult Arg1
5738 = PerformCopyInitialization(
5739 InitializedEntity::InitializeParameter(
5740 FnDecl->getParamDecl(0)),
5741 SourceLocation(),
5742 Owned(Args[1]));
5743 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005744 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005745
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005746 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
5747 Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005748 return ExprError();
5749
5750 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005751 } else {
5752 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005753 OwningExprResult Arg0
5754 = PerformCopyInitialization(
5755 InitializedEntity::InitializeParameter(
5756 FnDecl->getParamDecl(0)),
5757 SourceLocation(),
5758 Owned(Args[0]));
5759 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005760 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005761
5762 OwningExprResult Arg1
5763 = PerformCopyInitialization(
5764 InitializedEntity::InitializeParameter(
5765 FnDecl->getParamDecl(1)),
5766 SourceLocation(),
5767 Owned(Args[1]));
5768 if (Arg1.isInvalid())
5769 return ExprError();
5770 Args[0] = LHS = Arg0.takeAs<Expr>();
5771 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005772 }
5773
5774 // Determine the result type
5775 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00005776 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005777 ResultTy = ResultTy.getNonReferenceType();
5778
5779 // Build the actual expression node.
5780 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00005781 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005782 UsualUnaryConversions(FnExpr);
5783
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005784 ExprOwningPtr<CXXOperatorCallExpr>
5785 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5786 Args, 2, ResultTy,
5787 OpLoc));
5788
5789 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5790 FnDecl))
5791 return ExprError();
5792
5793 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005794 } else {
5795 // We matched a built-in operator. Convert the arguments, then
5796 // break out so that we will build the appropriate built-in
5797 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00005798 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005799 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00005800 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005801 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005802 return ExprError();
5803
5804 break;
5805 }
5806 }
5807
Douglas Gregor66950a32009-09-30 21:46:01 +00005808 case OR_No_Viable_Function: {
5809 // C++ [over.match.oper]p9:
5810 // If the operator is the operator , [...] and there are no
5811 // viable functions, then the operator is assumed to be the
5812 // built-in operator and interpreted according to clause 5.
5813 if (Opc == BinaryOperator::Comma)
5814 break;
5815
Sebastian Redl027de2a2009-05-21 11:50:50 +00005816 // For class as left operand for assignment or compound assigment operator
5817 // do not fall through to handling in built-in, but report that no overloaded
5818 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005819 OwningExprResult Result = ExprError();
5820 if (Args[0]->getType()->isRecordType() &&
5821 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005822 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5823 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005824 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005825 } else {
5826 // No viable function; try to create a built-in operation, which will
5827 // produce an error. Then, show the non-viable candidates.
5828 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005829 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005830 assert(Result.isInvalid() &&
5831 "C++ binary operator overloading is missing candidates!");
5832 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00005833 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005834 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005835 return move(Result);
5836 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005837
5838 case OR_Ambiguous:
5839 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5840 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005841 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005842 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005843 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005844 return ExprError();
5845
5846 case OR_Deleted:
5847 Diag(OpLoc, diag::err_ovl_deleted_oper)
5848 << Best->Function->isDeleted()
5849 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005850 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005851 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005852 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00005853 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005854
Douglas Gregor66950a32009-09-30 21:46:01 +00005855 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005856 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005857}
5858
Sebastian Redladba46e2009-10-29 20:17:01 +00005859Action::OwningExprResult
5860Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5861 SourceLocation RLoc,
5862 ExprArg Base, ExprArg Idx) {
5863 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5864 static_cast<Expr*>(Idx.get()) };
5865 DeclarationName OpName =
5866 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5867
5868 // If either side is type-dependent, create an appropriate dependent
5869 // expression.
5870 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5871
John McCall58cc69d2010-01-27 01:50:18 +00005872 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005873 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005874 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005875 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005876 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005877 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005878
5879 Base.release();
5880 Idx.release();
5881 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5882 Args, 2,
5883 Context.DependentTy,
5884 RLoc));
5885 }
5886
5887 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005888 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005889
5890 // Subscript can only be overloaded as a member function.
5891
5892 // Add operator candidates that are member functions.
5893 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5894
5895 // Add builtin operator candidates.
5896 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5897
5898 // Perform overload resolution.
5899 OverloadCandidateSet::iterator Best;
5900 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5901 case OR_Success: {
5902 // We found a built-in operator or an overloaded operator.
5903 FunctionDecl *FnDecl = Best->Function;
5904
5905 if (FnDecl) {
5906 // We matched an overloaded operator. Build a call to that
5907 // operator.
5908
John McCallb3a44002010-01-28 01:42:12 +00005909 CheckMemberOperatorAccess(LLoc, Args[0], FnDecl, Best->getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005910
Sebastian Redladba46e2009-10-29 20:17:01 +00005911 // Convert the arguments.
5912 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005913 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
5914 Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00005915 return ExprError();
5916
Anders Carlssona68e51e2010-01-29 18:37:50 +00005917 // Convert the arguments.
5918 OwningExprResult InputInit
5919 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5920 FnDecl->getParamDecl(0)),
5921 SourceLocation(),
5922 Owned(Args[1]));
5923 if (InputInit.isInvalid())
5924 return ExprError();
5925
5926 Args[1] = InputInit.takeAs<Expr>();
5927
Sebastian Redladba46e2009-10-29 20:17:01 +00005928 // Determine the result type
5929 QualType ResultTy
5930 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5931 ResultTy = ResultTy.getNonReferenceType();
5932
5933 // Build the actual expression node.
5934 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5935 LLoc);
5936 UsualUnaryConversions(FnExpr);
5937
5938 Base.release();
5939 Idx.release();
5940 ExprOwningPtr<CXXOperatorCallExpr>
5941 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5942 FnExpr, Args, 2,
5943 ResultTy, RLoc));
5944
5945 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5946 FnDecl))
5947 return ExprError();
5948
5949 return MaybeBindToTemporary(TheCall.release());
5950 } else {
5951 // We matched a built-in operator. Convert the arguments, then
5952 // break out so that we will build the appropriate built-in
5953 // operator node.
5954 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005955 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00005956 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005957 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005958 return ExprError();
5959
5960 break;
5961 }
5962 }
5963
5964 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00005965 if (CandidateSet.empty())
5966 Diag(LLoc, diag::err_ovl_no_oper)
5967 << Args[0]->getType() << /*subscript*/ 0
5968 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5969 else
5970 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5971 << Args[0]->getType()
5972 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005973 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00005974 "[]", LLoc);
5975 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00005976 }
5977
5978 case OR_Ambiguous:
5979 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5980 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005981 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00005982 "[]", LLoc);
5983 return ExprError();
5984
5985 case OR_Deleted:
5986 Diag(LLoc, diag::err_ovl_deleted_oper)
5987 << Best->Function->isDeleted() << "[]"
5988 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005989 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00005990 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005991 return ExprError();
5992 }
5993
5994 // We matched a built-in operator; build it.
5995 Base.release();
5996 Idx.release();
5997 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5998 Owned(Args[1]), RLoc);
5999}
6000
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006001/// BuildCallToMemberFunction - Build a call to a member
6002/// function. MemExpr is the expression that refers to the member
6003/// function (and includes the object parameter), Args/NumArgs are the
6004/// arguments to the function call (not including the object
6005/// parameter). The caller needs to validate that the member
6006/// expression refers to a member function or an overloaded member
6007/// function.
John McCall2d74de92009-12-01 22:10:20 +00006008Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006009Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6010 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006011 unsigned NumArgs, SourceLocation *CommaLocs,
6012 SourceLocation RParenLoc) {
6013 // Dig out the member expression. This holds both the object
6014 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006015 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6016
John McCall10eae182009-11-30 22:42:35 +00006017 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006018 CXXMethodDecl *Method = 0;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006019 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006020 if (isa<MemberExpr>(NakedMemExpr)) {
6021 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006022 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006023 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006024 } else {
6025 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006026 Qualifier = UnresExpr->getQualifier();
6027
John McCall6e9f8f62009-12-03 04:06:58 +00006028 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006029
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006030 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006031 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006032
John McCall2d74de92009-12-01 22:10:20 +00006033 // FIXME: avoid copy.
6034 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6035 if (UnresExpr->hasExplicitTemplateArgs()) {
6036 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6037 TemplateArgs = &TemplateArgsBuffer;
6038 }
6039
John McCall10eae182009-11-30 22:42:35 +00006040 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6041 E = UnresExpr->decls_end(); I != E; ++I) {
6042
John McCall6e9f8f62009-12-03 04:06:58 +00006043 NamedDecl *Func = *I;
6044 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6045 if (isa<UsingShadowDecl>(Func))
6046 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6047
John McCall10eae182009-11-30 22:42:35 +00006048 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006049 // If explicit template arguments were provided, we can't call a
6050 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006051 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006052 continue;
6053
John McCallb89836b2010-01-26 01:37:31 +00006054 AddMethodCandidate(Method, I.getAccess(), ActingDC, ObjectType,
6055 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006056 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006057 } else {
John McCall10eae182009-11-30 22:42:35 +00006058 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCallb89836b2010-01-26 01:37:31 +00006059 I.getAccess(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006060 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006061 CandidateSet,
6062 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006063 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006064 }
Mike Stump11289f42009-09-09 15:08:12 +00006065
John McCall10eae182009-11-30 22:42:35 +00006066 DeclarationName DeclName = UnresExpr->getMemberName();
6067
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006068 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006069 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006070 case OR_Success:
6071 Method = cast<CXXMethodDecl>(Best->Function);
John McCall58cc69d2010-01-27 01:50:18 +00006072 CheckUnresolvedMemberAccess(UnresExpr, Method, Best->getAccess());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006073 break;
6074
6075 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006076 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006077 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006078 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006079 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006080 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006081 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006082
6083 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006084 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006085 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006086 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006087 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006088 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006089
6090 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006091 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006092 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006093 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006094 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006095 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006096 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006097 }
6098
Douglas Gregor51c538b2009-11-20 19:42:02 +00006099 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00006100
John McCall2d74de92009-12-01 22:10:20 +00006101 // If overload resolution picked a static member, build a
6102 // non-member call based on that function.
6103 if (Method->isStatic()) {
6104 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6105 Args, NumArgs, RParenLoc);
6106 }
6107
John McCall10eae182009-11-30 22:42:35 +00006108 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006109 }
6110
6111 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006112 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006113 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006114 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006115 Method->getResultType().getNonReferenceType(),
6116 RParenLoc));
6117
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006118 // Check for a valid return type.
6119 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6120 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006121 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006122
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006123 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00006124 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006125 if (!Method->isStatic() &&
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006126 PerformObjectArgumentInitialization(ObjectArg, Qualifier, Method))
John McCall2d74de92009-12-01 22:10:20 +00006127 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006128 MemExpr->setBase(ObjectArg);
6129
6130 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006131 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00006132 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006133 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006134 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006135
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006136 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006137 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006138
John McCall2d74de92009-12-01 22:10:20 +00006139 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006140}
6141
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006142/// BuildCallToObjectOfClassType - Build a call to an object of class
6143/// type (C++ [over.call.object]), which can end up invoking an
6144/// overloaded function call operator (@c operator()) or performing a
6145/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006146Sema::ExprResult
6147Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006148 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006149 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006150 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006151 SourceLocation RParenLoc) {
6152 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006153 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006154
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006155 // C++ [over.call.object]p1:
6156 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006157 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006158 // candidate functions includes at least the function call
6159 // operators of T. The function call operators of T are obtained by
6160 // ordinary lookup of the name operator() in the context of
6161 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006162 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006163 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006164
6165 if (RequireCompleteType(LParenLoc, Object->getType(),
6166 PartialDiagnostic(diag::err_incomplete_object_call)
6167 << Object->getSourceRange()))
6168 return true;
6169
John McCall27b18f82009-11-17 02:14:36 +00006170 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6171 LookupQualifiedName(R, Record->getDecl());
6172 R.suppressDiagnostics();
6173
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006174 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006175 Oper != OperEnd; ++Oper) {
John McCallb89836b2010-01-26 01:37:31 +00006176 AddMethodCandidate(*Oper, Oper.getAccess(), Object->getType(),
6177 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006178 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006179 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006180
Douglas Gregorab7897a2008-11-19 22:57:39 +00006181 // C++ [over.call.object]p2:
6182 // In addition, for each conversion function declared in T of the
6183 // form
6184 //
6185 // operator conversion-type-id () cv-qualifier;
6186 //
6187 // where cv-qualifier is the same cv-qualification as, or a
6188 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006189 // denotes the type "pointer to function of (P1,...,Pn) returning
6190 // R", or the type "reference to pointer to function of
6191 // (P1,...,Pn) returning R", or the type "reference to function
6192 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006193 // is also considered as a candidate function. Similarly,
6194 // surrogate call functions are added to the set of candidate
6195 // functions for each conversion function declared in an
6196 // accessible base class provided the function is not hidden
6197 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006198 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006199 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006200 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006201 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006202 NamedDecl *D = *I;
6203 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6204 if (isa<UsingShadowDecl>(D))
6205 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6206
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006207 // Skip over templated conversion functions; they aren't
6208 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006209 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006210 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006211
John McCall6e9f8f62009-12-03 04:06:58 +00006212 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006213
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006214 // Strip the reference type (if any) and then the pointer type (if
6215 // any) to get down to what might be a function type.
6216 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6217 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6218 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006219
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006220 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCallb89836b2010-01-26 01:37:31 +00006221 AddSurrogateCandidate(Conv, I.getAccess(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006222 Object->getType(), Args, NumArgs,
6223 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006224 }
Mike Stump11289f42009-09-09 15:08:12 +00006225
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006226 // Perform overload resolution.
6227 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006228 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006229 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006230 // Overload resolution succeeded; we'll build the appropriate call
6231 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006232 break;
6233
6234 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006235 if (CandidateSet.empty())
6236 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6237 << Object->getType() << /*call*/ 1
6238 << Object->getSourceRange();
6239 else
6240 Diag(Object->getSourceRange().getBegin(),
6241 diag::err_ovl_no_viable_object_call)
6242 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006243 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006244 break;
6245
6246 case OR_Ambiguous:
6247 Diag(Object->getSourceRange().getBegin(),
6248 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006249 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006250 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006251 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006252
6253 case OR_Deleted:
6254 Diag(Object->getSourceRange().getBegin(),
6255 diag::err_ovl_deleted_object_call)
6256 << Best->Function->isDeleted()
6257 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006258 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006259 break;
Mike Stump11289f42009-09-09 15:08:12 +00006260 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006261
Douglas Gregorab7897a2008-11-19 22:57:39 +00006262 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006263 // We had an error; delete all of the subexpressions and return
6264 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006265 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006266 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006267 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006268 return true;
6269 }
6270
Douglas Gregorab7897a2008-11-19 22:57:39 +00006271 if (Best->Function == 0) {
6272 // Since there is no function declaration, this is one of the
6273 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006274 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006275 = cast<CXXConversionDecl>(
6276 Best->Conversions[0].UserDefined.ConversionFunction);
6277
John McCall2cb94162010-01-28 07:38:46 +00006278 CheckMemberOperatorAccess(LParenLoc, Object, Conv, Best->getAccess());
John McCall49ec2e62010-01-28 01:54:34 +00006279
Douglas Gregorab7897a2008-11-19 22:57:39 +00006280 // We selected one of the surrogate functions that converts the
6281 // object parameter to a function pointer. Perform the conversion
6282 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006283
6284 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006285 // and then call it.
Eli Friedmana958a012009-12-09 04:52:43 +00006286 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006287
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006288 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006289 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6290 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006291 }
6292
John McCall2cb94162010-01-28 07:38:46 +00006293 CheckMemberOperatorAccess(LParenLoc, Object,
6294 Best->Function, Best->getAccess());
John McCall49ec2e62010-01-28 01:54:34 +00006295
Douglas Gregorab7897a2008-11-19 22:57:39 +00006296 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6297 // that calls this method, using Object for the implicit object
6298 // parameter and passing along the remaining arguments.
6299 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006300 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006301
6302 unsigned NumArgsInProto = Proto->getNumArgs();
6303 unsigned NumArgsToCheck = NumArgs;
6304
6305 // Build the full argument list for the method call (the
6306 // implicit object parameter is placed at the beginning of the
6307 // list).
6308 Expr **MethodArgs;
6309 if (NumArgs < NumArgsInProto) {
6310 NumArgsToCheck = NumArgsInProto;
6311 MethodArgs = new Expr*[NumArgsInProto + 1];
6312 } else {
6313 MethodArgs = new Expr*[NumArgs + 1];
6314 }
6315 MethodArgs[0] = Object;
6316 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6317 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006318
6319 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006320 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006321 UsualUnaryConversions(NewFn);
6322
6323 // Once we've built TheCall, all of the expressions are properly
6324 // owned.
6325 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006326 ExprOwningPtr<CXXOperatorCallExpr>
6327 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006328 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006329 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006330 delete [] MethodArgs;
6331
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006332 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6333 Method))
6334 return true;
6335
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006336 // We may have default arguments. If so, we need to allocate more
6337 // slots in the call for them.
6338 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006339 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006340 else if (NumArgs > NumArgsInProto)
6341 NumArgsToCheck = NumArgsInProto;
6342
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006343 bool IsError = false;
6344
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006345 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006346 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
6347 Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006348 TheCall->setArg(0, Object);
6349
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006350
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006351 // Check the argument types.
6352 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006353 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006354 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006355 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006356
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006357 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006358
6359 OwningExprResult InputInit
6360 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6361 Method->getParamDecl(i)),
6362 SourceLocation(), Owned(Arg));
6363
6364 IsError |= InputInit.isInvalid();
6365 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006366 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006367 OwningExprResult DefArg
6368 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6369 if (DefArg.isInvalid()) {
6370 IsError = true;
6371 break;
6372 }
6373
6374 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006375 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006376
6377 TheCall->setArg(i + 1, Arg);
6378 }
6379
6380 // If this is a variadic call, handle args passed through "...".
6381 if (Proto->isVariadic()) {
6382 // Promote the arguments (C99 6.5.2.2p7).
6383 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6384 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006385 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006386 TheCall->setArg(i + 1, Arg);
6387 }
6388 }
6389
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006390 if (IsError) return true;
6391
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006392 if (CheckFunctionCall(Method, TheCall.get()))
6393 return true;
6394
Anders Carlsson1c83deb2009-08-16 03:53:54 +00006395 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006396}
6397
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006398/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006399/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006400/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006401Sema::OwningExprResult
6402Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6403 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006404 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006405
John McCallbc077cf2010-02-08 23:07:23 +00006406 SourceLocation Loc = Base->getExprLoc();
6407
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006408 // C++ [over.ref]p1:
6409 //
6410 // [...] An expression x->m is interpreted as (x.operator->())->m
6411 // for a class object x of type T if T::operator->() exists and if
6412 // the operator is selected as the best match function by the
6413 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006414 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00006415 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006416 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006417
John McCallbc077cf2010-02-08 23:07:23 +00006418 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00006419 PDiag(diag::err_typecheck_incomplete_tag)
6420 << Base->getSourceRange()))
6421 return ExprError();
6422
John McCall27b18f82009-11-17 02:14:36 +00006423 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6424 LookupQualifiedName(R, BaseRecord->getDecl());
6425 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006426
6427 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006428 Oper != OperEnd; ++Oper) {
6429 NamedDecl *D = *Oper;
6430 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6431 if (isa<UsingShadowDecl>(D))
6432 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6433
John McCallb89836b2010-01-26 01:37:31 +00006434 AddMethodCandidate(cast<CXXMethodDecl>(D), Oper.getAccess(), ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00006435 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006436 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006437 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006438
6439 // Perform overload resolution.
6440 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006441 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006442 case OR_Success:
6443 // Overload resolution succeeded; we'll build the call below.
6444 break;
6445
6446 case OR_No_Viable_Function:
6447 if (CandidateSet.empty())
6448 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006449 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006450 else
6451 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006452 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006453 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006454 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006455
6456 case OR_Ambiguous:
6457 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006458 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006459 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006460 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006461
6462 case OR_Deleted:
6463 Diag(OpLoc, diag::err_ovl_deleted_oper)
6464 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006465 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006466 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006467 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006468 }
6469
6470 // Convert the object parameter.
6471 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006472 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006473 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006474
6475 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006476 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006477
6478 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006479 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6480 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006481 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006482
6483 QualType ResultTy = Method->getResultType().getNonReferenceType();
6484 ExprOwningPtr<CXXOperatorCallExpr>
6485 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6486 &Base, 1, ResultTy, OpLoc));
6487
6488 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6489 Method))
6490 return ExprError();
6491 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006492}
6493
Douglas Gregorcd695e52008-11-10 20:40:00 +00006494/// FixOverloadedFunctionReference - E is an expression that refers to
6495/// a C++ overloaded function (possibly with some parentheses and
6496/// perhaps a '&' around it). We have resolved the overloaded function
6497/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006498/// refer (possibly indirectly) to Fn. Returns the new expr.
6499Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006500 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00006501 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6502 if (SubExpr == PE->getSubExpr())
6503 return PE->Retain();
6504
6505 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6506 }
6507
6508 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6509 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006510 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006511 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006512 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006513 if (SubExpr == ICE->getSubExpr())
6514 return ICE->Retain();
6515
6516 return new (Context) ImplicitCastExpr(ICE->getType(),
6517 ICE->getCastKind(),
6518 SubExpr,
6519 ICE->isLvalueCast());
6520 }
6521
6522 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006523 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006524 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006525 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6526 if (Method->isStatic()) {
6527 // Do nothing: static member functions aren't any different
6528 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006529 } else {
John McCalle66edc12009-11-24 19:00:30 +00006530 // Fix the sub expression, which really has to be an
6531 // UnresolvedLookupExpr holding an overloaded member function
6532 // or template.
John McCalld14a8642009-11-21 08:51:07 +00006533 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6534 if (SubExpr == UnOp->getSubExpr())
6535 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006536
John McCalld14a8642009-11-21 08:51:07 +00006537 assert(isa<DeclRefExpr>(SubExpr)
6538 && "fixed to something other than a decl ref");
6539 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6540 && "fixed to a member ref with no nested name qualifier");
6541
6542 // We have taken the address of a pointer to member
6543 // function. Perform the computation here so that we get the
6544 // appropriate pointer to member type.
6545 QualType ClassType
6546 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6547 QualType MemPtrType
6548 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6549
6550 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6551 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006552 }
6553 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00006554 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6555 if (SubExpr == UnOp->getSubExpr())
6556 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006557
Douglas Gregor51c538b2009-11-20 19:42:02 +00006558 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6559 Context.getPointerType(SubExpr->getType()),
6560 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006561 }
John McCalld14a8642009-11-21 08:51:07 +00006562
6563 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006564 // FIXME: avoid copy.
6565 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006566 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006567 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6568 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006569 }
6570
John McCalld14a8642009-11-21 08:51:07 +00006571 return DeclRefExpr::Create(Context,
6572 ULE->getQualifier(),
6573 ULE->getQualifierRange(),
6574 Fn,
6575 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006576 Fn->getType(),
6577 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006578 }
6579
John McCall10eae182009-11-30 22:42:35 +00006580 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006581 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006582 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6583 if (MemExpr->hasExplicitTemplateArgs()) {
6584 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6585 TemplateArgs = &TemplateArgsBuffer;
6586 }
John McCall6b51f282009-11-23 01:53:49 +00006587
John McCall2d74de92009-12-01 22:10:20 +00006588 Expr *Base;
6589
6590 // If we're filling in
6591 if (MemExpr->isImplicitAccess()) {
6592 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6593 return DeclRefExpr::Create(Context,
6594 MemExpr->getQualifier(),
6595 MemExpr->getQualifierRange(),
6596 Fn,
6597 MemExpr->getMemberLoc(),
6598 Fn->getType(),
6599 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006600 } else {
6601 SourceLocation Loc = MemExpr->getMemberLoc();
6602 if (MemExpr->getQualifier())
6603 Loc = MemExpr->getQualifierRange().getBegin();
6604 Base = new (Context) CXXThisExpr(Loc,
6605 MemExpr->getBaseType(),
6606 /*isImplicit=*/true);
6607 }
John McCall2d74de92009-12-01 22:10:20 +00006608 } else
6609 Base = MemExpr->getBase()->Retain();
6610
6611 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006612 MemExpr->isArrow(),
6613 MemExpr->getQualifier(),
6614 MemExpr->getQualifierRange(),
6615 Fn,
John McCall6b51f282009-11-23 01:53:49 +00006616 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006617 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006618 Fn->getType());
6619 }
6620
Douglas Gregor51c538b2009-11-20 19:42:02 +00006621 assert(false && "Invalid reference to overloaded function");
6622 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006623}
6624
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006625Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6626 FunctionDecl *Fn) {
6627 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6628}
6629
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006630} // end namespace clang