blob: 452901cf225b0164c390faf19cf3079cba0f2919 [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,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000083 ICR_Conversion
84 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno 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;
121 Deprecated = false;
122 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) {
456 ICS.setBad();
457 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
458 return ICS;
459 }
460
461 OverloadCandidateSet Conversions(From->getExprLoc());
462 OverloadingResult UserDefResult
463 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
464 !SuppressUserConversions, AllowExplicit,
465 ForceRValue, UserCast);
466
467 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000468 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000469 // C++ [over.ics.user]p4:
470 // A conversion of an expression of class type to the same class
471 // type is given Exact Match rank, and a conversion of an
472 // expression of class type to a base class of that type is
473 // given Conversion rank, in spite of the fact that a copy
474 // constructor (i.e., a user-defined conversion function) is
475 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000476 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000477 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000478 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000479 = Context.getCanonicalType(From->getType().getUnqualifiedType());
480 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000481 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000482 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000483 // Turn this into a "standard" conversion sequence, so that it
484 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000485 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000486 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000487 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000488 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000489 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000490 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000491 ICS.Standard.Second = ICK_Derived_To_Base;
492 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000493 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000494
495 // C++ [over.best.ics]p4:
496 // However, when considering the argument of a user-defined
497 // conversion function that is a candidate by 13.3.1.3 when
498 // invoked for the copying of the temporary in the second step
499 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
500 // 13.3.1.6 in all cases, only standard conversion sequences and
501 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000502 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall0d1da222010-01-12 00:44:57 +0000503 ICS.setBad();
John McCall6a61b522010-01-13 09:16:55 +0000504 ICS.Bad.init(BadConversionSequence::suppressed_user, From, ToType);
505 }
John McCalle8c8cd22010-01-13 22:30:33 +0000506 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000507 ICS.setAmbiguous();
508 ICS.Ambiguous.setFromType(From->getType());
509 ICS.Ambiguous.setToType(ToType);
510 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
511 Cand != Conversions.end(); ++Cand)
512 if (Cand->Viable)
513 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000514 } else {
John McCall0d1da222010-01-12 00:44:57 +0000515 ICS.setBad();
John McCall6a61b522010-01-13 09:16:55 +0000516 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000517 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000518
519 return ICS;
520}
521
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000522/// \brief Determine whether the conversion from FromType to ToType is a valid
523/// conversion that strips "noreturn" off the nested function type.
524static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
525 QualType ToType, QualType &ResultTy) {
526 if (Context.hasSameUnqualifiedType(FromType, ToType))
527 return false;
528
529 // Strip the noreturn off the type we're converting from; noreturn can
530 // safely be removed.
531 FromType = Context.getNoReturnType(FromType, false);
532 if (!Context.hasSameUnqualifiedType(FromType, ToType))
533 return false;
534
535 ResultTy = FromType;
536 return true;
537}
538
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000539/// IsStandardConversion - Determines whether there is a standard
540/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
541/// expression From to the type ToType. Standard conversion sequences
542/// only consider non-class types; for conversions that involve class
543/// types, use TryImplicitConversion. If a conversion exists, SCS will
544/// contain the standard conversion sequence required to perform this
545/// conversion and this routine will return true. Otherwise, this
546/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000547bool
548Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000549 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000550 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000551 QualType FromType = From->getType();
552
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000553 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000554 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000555 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000556 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000557 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000558 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000559
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000560 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000561 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000562 if (FromType->isRecordType() || ToType->isRecordType()) {
563 if (getLangOptions().CPlusPlus)
564 return false;
565
Mike Stump11289f42009-09-09 15:08:12 +0000566 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000567 }
568
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000569 // The first conversion can be an lvalue-to-rvalue conversion,
570 // array-to-pointer conversion, or function-to-pointer conversion
571 // (C++ 4p1).
572
Mike Stump11289f42009-09-09 15:08:12 +0000573 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000574 // An lvalue (3.10) of a non-function, non-array type T can be
575 // converted to an rvalue.
576 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000577 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000578 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000579 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000580 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000581
582 // If T is a non-class type, the type of the rvalue is the
583 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000584 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
585 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000586 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000587 } else if (FromType->isArrayType()) {
588 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000589 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000590
591 // An lvalue or rvalue of type "array of N T" or "array of unknown
592 // bound of T" can be converted to an rvalue of type "pointer to
593 // T" (C++ 4.2p1).
594 FromType = Context.getArrayDecayedType(FromType);
595
596 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
597 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000598 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000599
600 // For the purpose of ranking in overload resolution
601 // (13.3.3.1.1), this conversion is considered an
602 // array-to-pointer conversion followed by a qualification
603 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000604 SCS.Second = ICK_Identity;
605 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000606 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000607 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000608 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000609 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
610 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000611 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000612
613 // An lvalue of function type T can be converted to an rvalue of
614 // type "pointer to T." The result is a pointer to the
615 // function. (C++ 4.3p1).
616 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000617 } else if (FunctionDecl *Fn
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000618 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000619 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000620 SCS.First = ICK_Function_To_Pointer;
621
622 // We were able to resolve the address of the overloaded function,
623 // so we can convert to the type of that function.
624 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000625 if (ToType->isLValueReferenceType())
626 FromType = Context.getLValueReferenceType(FromType);
627 else if (ToType->isRValueReferenceType())
628 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000629 else if (ToType->isMemberPointerType()) {
630 // Resolve address only succeeds if both sides are member pointers,
631 // but it doesn't have to be the same class. See DR 247.
632 // Note that this means that the type of &Derived::fn can be
633 // Ret (Base::*)(Args) if the fn overload actually found is from the
634 // base class, even if it was brought into the derived class via a
635 // using declaration. The standard isn't clear on this issue at all.
636 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
637 FromType = Context.getMemberPointerType(FromType,
638 Context.getTypeDeclType(M->getParent()).getTypePtr());
639 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000640 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000641 } else {
642 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000643 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000644 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000645 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000646
647 // The second conversion can be an integral promotion, floating
648 // point promotion, integral conversion, floating point conversion,
649 // floating-integral conversion, pointer conversion,
650 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000651 // For overloading in C, this can also be a "compatible-type"
652 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000653 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000654 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000655 // The unqualified versions of the types are the same: there's no
656 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000657 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000658 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000659 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000660 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000661 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000662 } else if (IsFloatingPointPromotion(FromType, ToType)) {
663 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000664 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000665 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000666 } else if (IsComplexPromotion(FromType, ToType)) {
667 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000668 SCS.Second = ICK_Complex_Promotion;
669 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000670 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000671 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000672 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000673 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000674 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000675 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
676 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000677 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000678 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000679 } else if (FromType->isComplexType() && ToType->isComplexType()) {
680 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000681 SCS.Second = ICK_Complex_Conversion;
682 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000683 } else if ((FromType->isFloatingType() &&
684 ToType->isIntegralType() && (!ToType->isBooleanType() &&
685 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000686 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000687 ToType->isFloatingType())) {
688 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000689 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000690 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000691 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
692 (ToType->isComplexType() && FromType->isArithmeticType())) {
693 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000694 SCS.Second = ICK_Complex_Real;
695 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000696 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
697 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000698 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000699 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000700 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000701 } else if (IsMemberPointerConversion(From, FromType, ToType,
702 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000703 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000704 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000705 } else if (ToType->isBooleanType() &&
706 (FromType->isArithmeticType() ||
707 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000708 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000709 FromType->isBlockPointerType() ||
710 FromType->isMemberPointerType() ||
711 FromType->isNullPtrType())) {
712 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000713 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000714 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000715 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000716 Context.typesAreCompatible(ToType, FromType)) {
717 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000718 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000719 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
720 // Treat a conversion that strips "noreturn" as an identity conversion.
721 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000722 } else {
723 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000724 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000725 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000726 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000727
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000728 QualType CanonFrom;
729 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000730 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000731 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000732 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000733 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000734 CanonFrom = Context.getCanonicalType(FromType);
735 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000736 } else {
737 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000738 SCS.Third = ICK_Identity;
739
Mike Stump11289f42009-09-09 15:08:12 +0000740 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000741 // [...] Any difference in top-level cv-qualification is
742 // subsumed by the initialization itself and does not constitute
743 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000744 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000745 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000746 if (CanonFrom.getLocalUnqualifiedType()
747 == CanonTo.getLocalUnqualifiedType() &&
748 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000749 FromType = ToType;
750 CanonFrom = CanonTo;
751 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000752 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000753 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000754
755 // If we have not converted the argument type to the parameter type,
756 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000757 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000758 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000759
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000760 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000761}
762
763/// IsIntegralPromotion - Determines whether the conversion from the
764/// expression From (whose potentially-adjusted type is FromType) to
765/// ToType is an integral promotion (C++ 4.5). If so, returns true and
766/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000767bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000768 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000769 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000770 if (!To) {
771 return false;
772 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000773
774 // An rvalue of type char, signed char, unsigned char, short int, or
775 // unsigned short int can be converted to an rvalue of type int if
776 // int can represent all the values of the source type; otherwise,
777 // the source rvalue can be converted to an rvalue of type unsigned
778 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +0000779 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
780 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000781 if (// We can promote any signed, promotable integer type to an int
782 (FromType->isSignedIntegerType() ||
783 // We can promote any unsigned integer type whose size is
784 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000785 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000786 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000787 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000788 }
789
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000790 return To->getKind() == BuiltinType::UInt;
791 }
792
793 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
794 // can be converted to an rvalue of the first of the following types
795 // that can represent all the values of its underlying type: int,
796 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000797
798 // We pre-calculate the promotion type for enum types.
799 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
800 if (ToType->isIntegerType())
801 return Context.hasSameUnqualifiedType(ToType,
802 FromEnumType->getDecl()->getPromotionType());
803
804 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000805 // Determine whether the type we're converting from is signed or
806 // unsigned.
807 bool FromIsSigned;
808 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000809
810 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
811 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000812
813 // The types we'll try to promote to, in the appropriate
814 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000815 QualType PromoteTypes[6] = {
816 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000817 Context.LongTy, Context.UnsignedLongTy ,
818 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000819 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000820 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000821 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
822 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000823 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000824 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
825 // We found the type that we can promote to. If this is the
826 // type we wanted, we have a promotion. Otherwise, no
827 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000828 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000829 }
830 }
831 }
832
833 // An rvalue for an integral bit-field (9.6) can be converted to an
834 // rvalue of type int if int can represent all the values of the
835 // bit-field; otherwise, it can be converted to unsigned int if
836 // unsigned int can represent all the values of the bit-field. If
837 // the bit-field is larger yet, no integral promotion applies to
838 // it. If the bit-field has an enumerated type, it is treated as any
839 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000840 // FIXME: We should delay checking of bit-fields until we actually perform the
841 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000842 using llvm::APSInt;
843 if (From)
844 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000845 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000846 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
847 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
848 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
849 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000850
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000851 // Are we promoting to an int from a bitfield that fits in an int?
852 if (BitWidth < ToSize ||
853 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
854 return To->getKind() == BuiltinType::Int;
855 }
Mike Stump11289f42009-09-09 15:08:12 +0000856
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000857 // Are we promoting to an unsigned int from an unsigned bitfield
858 // that fits into an unsigned int?
859 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
860 return To->getKind() == BuiltinType::UInt;
861 }
Mike Stump11289f42009-09-09 15:08:12 +0000862
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000863 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000864 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000865 }
Mike Stump11289f42009-09-09 15:08:12 +0000866
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000867 // An rvalue of type bool can be converted to an rvalue of type int,
868 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000869 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000870 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000871 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000872
873 return false;
874}
875
876/// IsFloatingPointPromotion - Determines whether the conversion from
877/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
878/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000879bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000880 /// An rvalue of type float can be converted to an rvalue of type
881 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000882 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
883 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000884 if (FromBuiltin->getKind() == BuiltinType::Float &&
885 ToBuiltin->getKind() == BuiltinType::Double)
886 return true;
887
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000888 // C99 6.3.1.5p1:
889 // When a float is promoted to double or long double, or a
890 // double is promoted to long double [...].
891 if (!getLangOptions().CPlusPlus &&
892 (FromBuiltin->getKind() == BuiltinType::Float ||
893 FromBuiltin->getKind() == BuiltinType::Double) &&
894 (ToBuiltin->getKind() == BuiltinType::LongDouble))
895 return true;
896 }
897
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000898 return false;
899}
900
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000901/// \brief Determine if a conversion is a complex promotion.
902///
903/// A complex promotion is defined as a complex -> complex conversion
904/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000905/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000906bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000907 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000908 if (!FromComplex)
909 return false;
910
John McCall9dd450b2009-09-21 23:43:11 +0000911 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000912 if (!ToComplex)
913 return false;
914
915 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000916 ToComplex->getElementType()) ||
917 IsIntegralPromotion(0, FromComplex->getElementType(),
918 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000919}
920
Douglas Gregor237f96c2008-11-26 23:31:11 +0000921/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
922/// the pointer type FromPtr to a pointer to type ToPointee, with the
923/// same type qualifiers as FromPtr has on its pointee type. ToType,
924/// if non-empty, will be a pointer to ToType that may or may not have
925/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000926static QualType
927BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000928 QualType ToPointee, QualType ToType,
929 ASTContext &Context) {
930 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
931 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000932 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000933
934 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000935 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000936 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000937 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000938 return ToType;
939
940 // Build a pointer to ToPointee. It has the right qualifiers
941 // already.
942 return Context.getPointerType(ToPointee);
943 }
944
945 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000946 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000947 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
948 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000949}
950
Fariborz Jahanian01cbe442009-12-16 23:13:33 +0000951/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
952/// the FromType, which is an objective-c pointer, to ToType, which may or may
953/// not have the right set of qualifiers.
954static QualType
955BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
956 QualType ToType,
957 ASTContext &Context) {
958 QualType CanonFromType = Context.getCanonicalType(FromType);
959 QualType CanonToType = Context.getCanonicalType(ToType);
960 Qualifiers Quals = CanonFromType.getQualifiers();
961
962 // Exact qualifier match -> return the pointer type we're converting to.
963 if (CanonToType.getLocalQualifiers() == Quals)
964 return ToType;
965
966 // Just build a canonical type that has the right qualifiers.
967 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
968}
969
Mike Stump11289f42009-09-09 15:08:12 +0000970static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000971 bool InOverloadResolution,
972 ASTContext &Context) {
973 // Handle value-dependent integral null pointer constants correctly.
974 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
975 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
976 Expr->getType()->isIntegralType())
977 return !InOverloadResolution;
978
Douglas Gregor56751b52009-09-25 04:25:58 +0000979 return Expr->isNullPointerConstant(Context,
980 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
981 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000982}
Mike Stump11289f42009-09-09 15:08:12 +0000983
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000984/// IsPointerConversion - Determines whether the conversion of the
985/// expression From, which has the (possibly adjusted) type FromType,
986/// can be converted to the type ToType via a pointer conversion (C++
987/// 4.10). If so, returns true and places the converted type (that
988/// might differ from ToType in its cv-qualifiers at some level) into
989/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000990///
Douglas Gregora29dc052008-11-27 01:19:21 +0000991/// This routine also supports conversions to and from block pointers
992/// and conversions with Objective-C's 'id', 'id<protocols...>', and
993/// pointers to interfaces. FIXME: Once we've determined the
994/// appropriate overloading rules for Objective-C, we may want to
995/// split the Objective-C checks into a different routine; however,
996/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000997/// conversions, so for now they live here. IncompatibleObjC will be
998/// set if the conversion is an allowed Objective-C conversion that
999/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001000bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001001 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001002 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001003 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001004 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001005 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1006 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001007
Mike Stump11289f42009-09-09 15:08:12 +00001008 // Conversion from a null pointer constant to any Objective-C pointer type.
1009 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001010 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001011 ConvertedType = ToType;
1012 return true;
1013 }
1014
Douglas Gregor231d1c62008-11-27 00:15:41 +00001015 // Blocks: Block pointers can be converted to void*.
1016 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001017 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001018 ConvertedType = ToType;
1019 return true;
1020 }
1021 // Blocks: A null pointer constant can be converted to a block
1022 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001023 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001024 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001025 ConvertedType = ToType;
1026 return true;
1027 }
1028
Sebastian Redl576fd422009-05-10 18:38:11 +00001029 // If the left-hand-side is nullptr_t, the right side can be a null
1030 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001031 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001032 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001033 ConvertedType = ToType;
1034 return true;
1035 }
1036
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001037 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001038 if (!ToTypePtr)
1039 return false;
1040
1041 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001042 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001043 ConvertedType = ToType;
1044 return true;
1045 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001046
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001047 // Beyond this point, both types need to be pointers
1048 // , including objective-c pointers.
1049 QualType ToPointeeType = ToTypePtr->getPointeeType();
1050 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1051 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1052 ToType, Context);
1053 return true;
1054
1055 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001056 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001057 if (!FromTypePtr)
1058 return false;
1059
1060 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001061
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062 // An rvalue of type "pointer to cv T," where T is an object type,
1063 // can be converted to an rvalue of type "pointer to cv void" (C++
1064 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001065 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001066 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001067 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001068 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001069 return true;
1070 }
1071
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001072 // When we're overloading in C, we allow a special kind of pointer
1073 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001074 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001075 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001076 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001077 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001078 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001079 return true;
1080 }
1081
Douglas Gregor5c407d92008-10-23 00:40:37 +00001082 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001083 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001084 // An rvalue of type "pointer to cv D," where D is a class type,
1085 // can be converted to an rvalue of type "pointer to cv B," where
1086 // B is a base class (clause 10) of D. If B is an inaccessible
1087 // (clause 11) or ambiguous (10.2) base class of D, a program that
1088 // necessitates this conversion is ill-formed. The result of the
1089 // conversion is a pointer to the base class sub-object of the
1090 // derived class object. The null pointer value is converted to
1091 // the null pointer value of the destination type.
1092 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001093 // Note that we do not check for ambiguity or inaccessibility
1094 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001095 if (getLangOptions().CPlusPlus &&
1096 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001097 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001098 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001099 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001100 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001101 ToType, Context);
1102 return true;
1103 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001104
Douglas Gregora119f102008-12-19 19:13:09 +00001105 return false;
1106}
1107
1108/// isObjCPointerConversion - Determines whether this is an
1109/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1110/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001111bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001112 QualType& ConvertedType,
1113 bool &IncompatibleObjC) {
1114 if (!getLangOptions().ObjC1)
1115 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001116
Steve Naroff7cae42b2009-07-10 23:34:53 +00001117 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001118 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001119 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001120 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001121
Steve Naroff7cae42b2009-07-10 23:34:53 +00001122 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001123 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001124 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001125 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001126 ConvertedType = ToType;
1127 return true;
1128 }
1129 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001130 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001131 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001132 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001133 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001134 ConvertedType = ToType;
1135 return true;
1136 }
1137 // Objective C++: We're able to convert from a pointer to an
1138 // interface to a pointer to a different interface.
1139 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1140 ConvertedType = ToType;
1141 return true;
1142 }
1143
1144 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1145 // Okay: this is some kind of implicit downcast of Objective-C
1146 // interfaces, which is permitted. However, we're going to
1147 // complain about it.
1148 IncompatibleObjC = true;
1149 ConvertedType = FromType;
1150 return true;
1151 }
Mike Stump11289f42009-09-09 15:08:12 +00001152 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001153 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001154 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001155 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001156 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001157 else if (const BlockPointerType *ToBlockPtr =
1158 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001159 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001160 // to a block pointer type.
1161 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1162 ConvertedType = ToType;
1163 return true;
1164 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001165 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001166 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001167 else if (FromType->getAs<BlockPointerType>() &&
1168 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1169 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001170 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001171 ConvertedType = ToType;
1172 return true;
1173 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001174 else
Douglas Gregora119f102008-12-19 19:13:09 +00001175 return false;
1176
Douglas Gregor033f56d2008-12-23 00:53:59 +00001177 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001178 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001179 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001180 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001181 FromPointeeType = FromBlockPtr->getPointeeType();
1182 else
Douglas Gregora119f102008-12-19 19:13:09 +00001183 return false;
1184
Douglas Gregora119f102008-12-19 19:13:09 +00001185 // If we have pointers to pointers, recursively check whether this
1186 // is an Objective-C conversion.
1187 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1188 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1189 IncompatibleObjC)) {
1190 // We always complain about this conversion.
1191 IncompatibleObjC = true;
1192 ConvertedType = ToType;
1193 return true;
1194 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001195 // Allow conversion of pointee being objective-c pointer to another one;
1196 // as in I* to id.
1197 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1198 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1199 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1200 IncompatibleObjC)) {
1201 ConvertedType = ToType;
1202 return true;
1203 }
1204
Douglas Gregor033f56d2008-12-23 00:53:59 +00001205 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001206 // differences in the argument and result types are in Objective-C
1207 // pointer conversions. If so, we permit the conversion (but
1208 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001209 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001210 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001211 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001212 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001213 if (FromFunctionType && ToFunctionType) {
1214 // If the function types are exactly the same, this isn't an
1215 // Objective-C pointer conversion.
1216 if (Context.getCanonicalType(FromPointeeType)
1217 == Context.getCanonicalType(ToPointeeType))
1218 return false;
1219
1220 // Perform the quick checks that will tell us whether these
1221 // function types are obviously different.
1222 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1223 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1224 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1225 return false;
1226
1227 bool HasObjCConversion = false;
1228 if (Context.getCanonicalType(FromFunctionType->getResultType())
1229 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1230 // Okay, the types match exactly. Nothing to do.
1231 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1232 ToFunctionType->getResultType(),
1233 ConvertedType, IncompatibleObjC)) {
1234 // Okay, we have an Objective-C pointer conversion.
1235 HasObjCConversion = true;
1236 } else {
1237 // Function types are too different. Abort.
1238 return false;
1239 }
Mike Stump11289f42009-09-09 15:08:12 +00001240
Douglas Gregora119f102008-12-19 19:13:09 +00001241 // Check argument types.
1242 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1243 ArgIdx != NumArgs; ++ArgIdx) {
1244 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1245 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1246 if (Context.getCanonicalType(FromArgType)
1247 == Context.getCanonicalType(ToArgType)) {
1248 // Okay, the types match exactly. Nothing to do.
1249 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1250 ConvertedType, IncompatibleObjC)) {
1251 // Okay, we have an Objective-C pointer conversion.
1252 HasObjCConversion = true;
1253 } else {
1254 // Argument types are too different. Abort.
1255 return false;
1256 }
1257 }
1258
1259 if (HasObjCConversion) {
1260 // We had an Objective-C conversion. Allow this pointer
1261 // conversion, but complain about it.
1262 ConvertedType = ToType;
1263 IncompatibleObjC = true;
1264 return true;
1265 }
1266 }
1267
Sebastian Redl72b597d2009-01-25 19:43:20 +00001268 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001269}
1270
Douglas Gregor39c16d42008-10-24 04:54:22 +00001271/// CheckPointerConversion - Check the pointer conversion from the
1272/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001273/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001274/// conversions for which IsPointerConversion has already returned
1275/// true. It returns true and produces a diagnostic if there was an
1276/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001277bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001278 CastExpr::CastKind &Kind,
1279 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001280 QualType FromType = From->getType();
1281
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001282 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1283 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001284 QualType FromPointeeType = FromPtrType->getPointeeType(),
1285 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001286
Douglas Gregor39c16d42008-10-24 04:54:22 +00001287 if (FromPointeeType->isRecordType() &&
1288 ToPointeeType->isRecordType()) {
1289 // We must have a derived-to-base conversion. Check an
1290 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001291 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1292 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001293 From->getSourceRange(),
1294 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001295 return true;
1296
1297 // The conversion was successful.
1298 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001299 }
1300 }
Mike Stump11289f42009-09-09 15:08:12 +00001301 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001302 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001303 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001304 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001305 // Objective-C++ conversions are always okay.
1306 // FIXME: We should have a different class of conversions for the
1307 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001308 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001309 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001310
Steve Naroff7cae42b2009-07-10 23:34:53 +00001311 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001312 return false;
1313}
1314
Sebastian Redl72b597d2009-01-25 19:43:20 +00001315/// IsMemberPointerConversion - Determines whether the conversion of the
1316/// expression From, which has the (possibly adjusted) type FromType, can be
1317/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1318/// If so, returns true and places the converted type (that might differ from
1319/// ToType in its cv-qualifiers at some level) into ConvertedType.
1320bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001321 QualType ToType,
1322 bool InOverloadResolution,
1323 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001324 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001325 if (!ToTypePtr)
1326 return false;
1327
1328 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001329 if (From->isNullPointerConstant(Context,
1330 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1331 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001332 ConvertedType = ToType;
1333 return true;
1334 }
1335
1336 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001337 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001338 if (!FromTypePtr)
1339 return false;
1340
1341 // A pointer to member of B can be converted to a pointer to member of D,
1342 // where D is derived from B (C++ 4.11p2).
1343 QualType FromClass(FromTypePtr->getClass(), 0);
1344 QualType ToClass(ToTypePtr->getClass(), 0);
1345 // FIXME: What happens when these are dependent? Is this function even called?
1346
1347 if (IsDerivedFrom(ToClass, FromClass)) {
1348 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1349 ToClass.getTypePtr());
1350 return true;
1351 }
1352
1353 return false;
1354}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001355
Sebastian Redl72b597d2009-01-25 19:43:20 +00001356/// CheckMemberPointerConversion - Check the member pointer conversion from the
1357/// expression From to the type ToType. This routine checks for ambiguous or
1358/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1359/// for which IsMemberPointerConversion has already returned true. It returns
1360/// true and produces a diagnostic if there was an error, or returns false
1361/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001362bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001363 CastExpr::CastKind &Kind,
1364 bool IgnoreBaseAccess) {
1365 (void)IgnoreBaseAccess;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001366 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001367 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001368 if (!FromPtrType) {
1369 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001370 assert(From->isNullPointerConstant(Context,
1371 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001372 "Expr must be null pointer constant!");
1373 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001374 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001375 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001376
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001377 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001378 assert(ToPtrType && "No member pointer cast has a target type "
1379 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001380
Sebastian Redled8f2002009-01-28 18:33:18 +00001381 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1382 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001383
Sebastian Redled8f2002009-01-28 18:33:18 +00001384 // FIXME: What about dependent types?
1385 assert(FromClass->isRecordType() && "Pointer into non-class.");
1386 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001387
Douglas Gregor36d1b142009-10-06 17:59:45 +00001388 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1389 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001390 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1391 assert(DerivationOkay &&
1392 "Should not have been called if derivation isn't OK.");
1393 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001394
Sebastian Redled8f2002009-01-28 18:33:18 +00001395 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1396 getUnqualifiedType())) {
1397 // Derivation is ambiguous. Redo the check to find the exact paths.
1398 Paths.clear();
1399 Paths.setRecordingPaths(true);
1400 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1401 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1402 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001403
Sebastian Redled8f2002009-01-28 18:33:18 +00001404 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1405 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1406 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1407 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001408 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001409
Douglas Gregor89ee6822009-02-28 01:32:25 +00001410 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001411 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1412 << FromClass << ToClass << QualType(VBase, 0)
1413 << From->getSourceRange();
1414 return true;
1415 }
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:
2002 if (SCS1.Deprecated)
2003 Result = ImplicitConversionSequence::Indistinguishable;
2004 break;
2005
2006 case ImplicitConversionSequence::Indistinguishable:
2007 break;
2008
2009 case ImplicitConversionSequence::Worse:
2010 if (SCS2.Deprecated)
2011 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
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002103 // Compare based on reference bindings.
2104 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
2105 SCS1.Second == ICK_Derived_To_Base) {
2106 // -- binding of an expression of type C to a reference of type
2107 // B& is better than binding an expression of type C to a
2108 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002109 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2110 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002111 if (IsDerivedFrom(ToType1, ToType2))
2112 return ImplicitConversionSequence::Better;
2113 else if (IsDerivedFrom(ToType2, ToType1))
2114 return ImplicitConversionSequence::Worse;
2115 }
2116
Douglas Gregor2fe98832008-11-03 19:09:14 +00002117 // -- binding of an expression of type B to a reference of type
2118 // A& is better than binding an expression of type C to a
2119 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002120 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2121 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002122 if (IsDerivedFrom(FromType2, FromType1))
2123 return ImplicitConversionSequence::Better;
2124 else if (IsDerivedFrom(FromType1, FromType2))
2125 return ImplicitConversionSequence::Worse;
2126 }
2127 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002128
2129 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002130 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2131 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2132 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2133 const MemberPointerType * FromMemPointer1 =
2134 FromType1->getAs<MemberPointerType>();
2135 const MemberPointerType * ToMemPointer1 =
2136 ToType1->getAs<MemberPointerType>();
2137 const MemberPointerType * FromMemPointer2 =
2138 FromType2->getAs<MemberPointerType>();
2139 const MemberPointerType * ToMemPointer2 =
2140 ToType2->getAs<MemberPointerType>();
2141 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2142 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2143 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2144 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2145 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2146 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2147 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2148 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002149 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002150 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2151 if (IsDerivedFrom(ToPointee1, ToPointee2))
2152 return ImplicitConversionSequence::Worse;
2153 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2154 return ImplicitConversionSequence::Better;
2155 }
2156 // conversion of B::* to C::* is better than conversion of A::* to C::*
2157 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2158 if (IsDerivedFrom(FromPointee1, FromPointee2))
2159 return ImplicitConversionSequence::Better;
2160 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2161 return ImplicitConversionSequence::Worse;
2162 }
2163 }
2164
Douglas Gregor2fe98832008-11-03 19:09:14 +00002165 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2166 SCS1.Second == ICK_Derived_To_Base) {
2167 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002168 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2169 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002170 if (IsDerivedFrom(ToType1, ToType2))
2171 return ImplicitConversionSequence::Better;
2172 else if (IsDerivedFrom(ToType2, ToType1))
2173 return ImplicitConversionSequence::Worse;
2174 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002175
Douglas Gregor2fe98832008-11-03 19:09:14 +00002176 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002177 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2178 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002179 if (IsDerivedFrom(FromType2, FromType1))
2180 return ImplicitConversionSequence::Better;
2181 else if (IsDerivedFrom(FromType1, FromType2))
2182 return ImplicitConversionSequence::Worse;
2183 }
2184 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002185
Douglas Gregor5c407d92008-10-23 00:40:37 +00002186 return ImplicitConversionSequence::Indistinguishable;
2187}
2188
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002189/// TryCopyInitialization - Try to copy-initialize a value of type
2190/// ToType from the expression From. Return the implicit conversion
2191/// sequence required to pass this argument, which may be a bad
2192/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002193/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002194/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2195/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002196ImplicitConversionSequence
2197Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002198 bool SuppressUserConversions, bool ForceRValue,
2199 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002200 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002201 ImplicitConversionSequence ICS;
John McCall6a61b522010-01-13 09:16:55 +00002202 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002203 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002204 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002205 SuppressUserConversions,
2206 /*AllowExplicit=*/false,
2207 ForceRValue,
2208 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002209 return ICS;
2210 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002211 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002212 SuppressUserConversions,
2213 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002214 ForceRValue,
2215 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002216 }
2217}
2218
Sebastian Redl42e92c42009-04-12 17:16:29 +00002219/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2220/// the expression @p From. Returns true (and emits a diagnostic) if there was
2221/// an error, returns false if the initialization succeeded. Elidable should
2222/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2223/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002224bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002225 AssignmentAction Action, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002226 if (!getLangOptions().CPlusPlus) {
2227 // In C, argument passing is the same as performing an assignment.
2228 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002229
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002230 AssignConvertType ConvTy =
2231 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002232 if (ConvTy != Compatible &&
2233 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2234 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002235
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002236 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002237 FromType, From, Action);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002238 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002239
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002240 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002241 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002242 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002243 /*SuppressUserConversions=*/false,
2244 /*AllowExplicit=*/false,
2245 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002246
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002247 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002248 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002249 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002250 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002251 return Diag(From->getSourceRange().getBegin(),
2252 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002253 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002254 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002255}
2256
Douglas Gregor436424c2008-11-18 23:14:02 +00002257/// TryObjectArgumentInitialization - Try to initialize the object
2258/// parameter of the given member function (@c Method) from the
2259/// expression @p From.
2260ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002261Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002262 CXXMethodDecl *Method,
2263 CXXRecordDecl *ActingContext) {
2264 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002265 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2266 // const volatile object.
2267 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2268 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2269 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002270
2271 // Set up the conversion sequence as a "bad" conversion, to allow us
2272 // to exit early.
2273 ImplicitConversionSequence ICS;
2274 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002275 ICS.setBad();
Douglas Gregor436424c2008-11-18 23:14:02 +00002276
2277 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002278 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002279 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002280 FromType = PT->getPointeeType();
2281
2282 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002283
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002284 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002285 // where X is the class of which the function is a member
2286 // (C++ [over.match.funcs]p4). However, when finding an implicit
2287 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002288 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002289 // (C++ [over.match.funcs]p5). We perform a simplified version of
2290 // reference binding here, that allows class rvalues to bind to
2291 // non-constant references.
2292
2293 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2294 // with the implicit object parameter (C++ [over.match.funcs]p5).
2295 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002296 if (ImplicitParamType.getCVRQualifiers()
2297 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002298 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall47000992010-01-14 03:28:57 +00002299 ICS.Bad.init(BadConversionSequence::bad_qualifiers,
2300 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002301 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002302 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002303
2304 // Check that we have either the same type or a derived type. It
2305 // affects the conversion rank.
2306 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002307 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002308 ICS.Standard.Second = ICK_Identity;
2309 else if (IsDerivedFrom(FromType, ClassType))
2310 ICS.Standard.Second = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002311 else {
2312 ICS.Bad.init(BadConversionSequence::unrelated_class, FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002313 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002314 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002315
2316 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002317 ICS.setStandard();
2318 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002319 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002320 ICS.Standard.ReferenceBinding = true;
2321 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002322 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002323 return ICS;
2324}
2325
2326/// PerformObjectArgumentInitialization - Perform initialization of
2327/// the implicit object parameter for the given Method with the given
2328/// expression.
2329bool
2330Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002331 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002332 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002333 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002334
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002335 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002336 FromRecordType = PT->getPointeeType();
2337 DestType = Method->getThisType(Context);
2338 } else {
2339 FromRecordType = From->getType();
2340 DestType = ImplicitParamRecordType;
2341 }
2342
John McCall6e9f8f62009-12-03 04:06:58 +00002343 // Note that we always use the true parent context when performing
2344 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002345 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002346 = TryObjectArgumentInitialization(From->getType(), Method,
2347 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002348 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002349 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002350 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002351 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002352
Douglas Gregor436424c2008-11-18 23:14:02 +00002353 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002354 CheckDerivedToBaseConversion(FromRecordType,
2355 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002356 From->getSourceRange().getBegin(),
2357 From->getSourceRange()))
2358 return true;
2359
Mike Stump11289f42009-09-09 15:08:12 +00002360 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002361 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002362 return false;
2363}
2364
Douglas Gregor5fb53972009-01-14 15:45:31 +00002365/// TryContextuallyConvertToBool - Attempt to contextually convert the
2366/// expression From to bool (C++0x [conv]p3).
2367ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002368 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002369 // FIXME: Are these flags correct?
2370 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002371 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002372 /*ForceRValue=*/false,
2373 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002374}
2375
2376/// PerformContextuallyConvertToBool - Perform a contextual conversion
2377/// of the expression From to bool (C++0x [conv]p3).
2378bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2379 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002380 if (!ICS.isBad())
2381 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002382
Fariborz Jahanian76197412009-11-18 18:26:29 +00002383 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002384 return Diag(From->getSourceRange().getBegin(),
2385 diag::err_typecheck_bool_condition)
2386 << From->getType() << From->getSourceRange();
2387 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002388}
2389
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002390/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002391/// candidate functions, using the given function call arguments. If
2392/// @p SuppressUserConversions, then don't allow user-defined
2393/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002394/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2395/// hacky way to implement the overloading rules for elidable copy
2396/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002397///
2398/// \para PartialOverloading true if we are performing "partial" overloading
2399/// based on an incomplete set of function arguments. This feature is used by
2400/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002401void
2402Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCallb89836b2010-01-26 01:37:31 +00002403 AccessSpecifier Access,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002404 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002405 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002406 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002407 bool ForceRValue,
2408 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002409 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002410 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002411 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002412 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002413 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002414
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002415 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002416 if (!isa<CXXConstructorDecl>(Method)) {
2417 // If we get here, it's because we're calling a member function
2418 // that is named without a member access expression (e.g.,
2419 // "this->f") that was either written explicitly or created
2420 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002421 // function, e.g., X::f(). We use an empty type for the implied
2422 // object argument (C++ [over.call.func]p3), and the acting context
2423 // is irrelevant.
John McCallb89836b2010-01-26 01:37:31 +00002424 AddMethodCandidate(Method, Access, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002425 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002426 SuppressUserConversions, ForceRValue);
2427 return;
2428 }
2429 // We treat a constructor like a non-member function, since its object
2430 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002431 }
2432
Douglas Gregorff7028a2009-11-13 23:59:09 +00002433 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002434 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002435
Douglas Gregor27381f32009-11-23 12:27:39 +00002436 // Overload resolution is always an unevaluated context.
2437 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2438
Douglas Gregorffe14e32009-11-14 01:20:54 +00002439 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2440 // C++ [class.copy]p3:
2441 // A member function template is never instantiated to perform the copy
2442 // of a class object to an object of its class type.
2443 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2444 if (NumArgs == 1 &&
2445 Constructor->isCopyConstructorLikeSpecialization() &&
2446 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2447 return;
2448 }
2449
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002450 // Add this candidate
2451 CandidateSet.push_back(OverloadCandidate());
2452 OverloadCandidate& Candidate = CandidateSet.back();
2453 Candidate.Function = Function;
John McCallb89836b2010-01-26 01:37:31 +00002454 Candidate.Access = Access;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002455 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002456 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002457 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002458
2459 unsigned NumArgsInProto = Proto->getNumArgs();
2460
2461 // (C++ 13.3.2p2): A candidate function having fewer than m
2462 // parameters is viable only if it has an ellipsis in its parameter
2463 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002464 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2465 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002466 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002467 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002468 return;
2469 }
2470
2471 // (C++ 13.3.2p2): A candidate function having more than m parameters
2472 // is viable only if the (m+1)st parameter has a default argument
2473 // (8.3.6). For the purposes of overload resolution, the
2474 // parameter list is truncated on the right, so that there are
2475 // exactly m parameters.
2476 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002477 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002478 // Not enough arguments.
2479 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002480 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002481 return;
2482 }
2483
2484 // Determine the implicit conversion sequences for each of the
2485 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002486 Candidate.Conversions.resize(NumArgs);
2487 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2488 if (ArgIdx < NumArgsInProto) {
2489 // (C++ 13.3.2p3): for F to be a viable function, there shall
2490 // exist for each argument an implicit conversion sequence
2491 // (13.3.3.1) that converts that argument to the corresponding
2492 // parameter of F.
2493 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002494 Candidate.Conversions[ArgIdx]
2495 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002496 SuppressUserConversions, ForceRValue,
2497 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002498 if (Candidate.Conversions[ArgIdx].isBad()) {
2499 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002500 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002501 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002502 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002503 } else {
2504 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2505 // argument for which there is no corresponding parameter is
2506 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002507 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002508 }
2509 }
2510}
2511
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002512/// \brief Add all of the function declarations in the given function set to
2513/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00002514void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002515 Expr **Args, unsigned NumArgs,
2516 OverloadCandidateSet& CandidateSet,
2517 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00002518 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002519 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002520 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2521 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall4c4c1df2010-01-26 03:27:55 +00002522 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getAccess(),
John McCall6e9f8f62009-12-03 04:06:58 +00002523 cast<CXXMethodDecl>(FD)->getParent(),
2524 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002525 CandidateSet, SuppressUserConversions);
2526 else
John McCallb89836b2010-01-26 01:37:31 +00002527 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002528 SuppressUserConversions);
2529 } else {
2530 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2531 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2532 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall4c4c1df2010-01-26 03:27:55 +00002533 AddMethodTemplateCandidate(FunTmpl, F.getAccess(),
John McCall6e9f8f62009-12-03 04:06:58 +00002534 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002535 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002536 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002537 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002538 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002539 else
John McCallb89836b2010-01-26 01:37:31 +00002540 AddTemplateOverloadCandidate(FunTmpl, AS_none,
John McCall6b51f282009-11-23 01:53:49 +00002541 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002542 Args, NumArgs, CandidateSet,
2543 SuppressUserConversions);
2544 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002545 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002546}
2547
John McCallf0f1cf02009-11-17 07:50:12 +00002548/// AddMethodCandidate - Adds a named decl (which is some kind of
2549/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002550void Sema::AddMethodCandidate(NamedDecl *Decl,
John McCallb89836b2010-01-26 01:37:31 +00002551 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002552 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002553 Expr **Args, unsigned NumArgs,
2554 OverloadCandidateSet& CandidateSet,
2555 bool SuppressUserConversions, bool ForceRValue) {
John McCall6e9f8f62009-12-03 04:06:58 +00002556 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002557
2558 if (isa<UsingShadowDecl>(Decl))
2559 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2560
2561 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2562 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2563 "Expected a member function template");
John McCallb89836b2010-01-26 01:37:31 +00002564 AddMethodTemplateCandidate(TD, Access, ActingContext, /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002565 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002566 CandidateSet,
2567 SuppressUserConversions,
2568 ForceRValue);
2569 } else {
John McCallb89836b2010-01-26 01:37:31 +00002570 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Access, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00002571 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002572 CandidateSet, SuppressUserConversions, ForceRValue);
2573 }
2574}
2575
Douglas Gregor436424c2008-11-18 23:14:02 +00002576/// AddMethodCandidate - Adds the given C++ member function to the set
2577/// of candidate functions, using the given function call arguments
2578/// and the object argument (@c Object). For example, in a call
2579/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2580/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2581/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002582/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2583/// a slightly hacky way to implement the overloading rules for elidable copy
2584/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002585void
John McCallb89836b2010-01-26 01:37:31 +00002586Sema::AddMethodCandidate(CXXMethodDecl *Method, AccessSpecifier Access,
2587 CXXRecordDecl *ActingContext, QualType ObjectType,
2588 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002589 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002590 bool SuppressUserConversions, bool ForceRValue) {
2591 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002592 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002593 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002594 assert(!isa<CXXConstructorDecl>(Method) &&
2595 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002596
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002597 if (!CandidateSet.isNewCandidate(Method))
2598 return;
2599
Douglas Gregor27381f32009-11-23 12:27:39 +00002600 // Overload resolution is always an unevaluated context.
2601 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2602
Douglas Gregor436424c2008-11-18 23:14:02 +00002603 // Add this candidate
2604 CandidateSet.push_back(OverloadCandidate());
2605 OverloadCandidate& Candidate = CandidateSet.back();
2606 Candidate.Function = Method;
John McCallb89836b2010-01-26 01:37:31 +00002607 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002608 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002609 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002610
2611 unsigned NumArgsInProto = Proto->getNumArgs();
2612
2613 // (C++ 13.3.2p2): A candidate function having fewer than m
2614 // parameters is viable only if it has an ellipsis in its parameter
2615 // list (8.3.5).
2616 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2617 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002618 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002619 return;
2620 }
2621
2622 // (C++ 13.3.2p2): A candidate function having more than m parameters
2623 // is viable only if the (m+1)st parameter has a default argument
2624 // (8.3.6). For the purposes of overload resolution, the
2625 // parameter list is truncated on the right, so that there are
2626 // exactly m parameters.
2627 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2628 if (NumArgs < MinRequiredArgs) {
2629 // Not enough arguments.
2630 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002631 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002632 return;
2633 }
2634
2635 Candidate.Viable = true;
2636 Candidate.Conversions.resize(NumArgs + 1);
2637
John McCall6e9f8f62009-12-03 04:06:58 +00002638 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002639 // The implicit object argument is ignored.
2640 Candidate.IgnoreObjectArgument = true;
2641 else {
2642 // Determine the implicit conversion sequence for the object
2643 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002644 Candidate.Conversions[0]
2645 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002646 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002647 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002648 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002649 return;
2650 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002651 }
2652
2653 // Determine the implicit conversion sequences for each of the
2654 // arguments.
2655 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2656 if (ArgIdx < NumArgsInProto) {
2657 // (C++ 13.3.2p3): for F to be a viable function, there shall
2658 // exist for each argument an implicit conversion sequence
2659 // (13.3.3.1) that converts that argument to the corresponding
2660 // parameter of F.
2661 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002662 Candidate.Conversions[ArgIdx + 1]
2663 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002664 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002665 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002666 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002667 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002668 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002669 break;
2670 }
2671 } else {
2672 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2673 // argument for which there is no corresponding parameter is
2674 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002675 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002676 }
2677 }
2678}
2679
Douglas Gregor97628d62009-08-21 00:16:32 +00002680/// \brief Add a C++ member function template as a candidate to the candidate
2681/// set, using template argument deduction to produce an appropriate member
2682/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002683void
Douglas Gregor97628d62009-08-21 00:16:32 +00002684Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCallb89836b2010-01-26 01:37:31 +00002685 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002686 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002687 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002688 QualType ObjectType,
2689 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002690 OverloadCandidateSet& CandidateSet,
2691 bool SuppressUserConversions,
2692 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002693 if (!CandidateSet.isNewCandidate(MethodTmpl))
2694 return;
2695
Douglas Gregor97628d62009-08-21 00:16:32 +00002696 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002697 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002698 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002699 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002700 // candidate functions in the usual way.113) A given name can refer to one
2701 // or more function templates and also to a set of overloaded non-template
2702 // functions. In such a case, the candidate functions generated from each
2703 // function template are combined with the set of non-template candidate
2704 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00002705 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00002706 FunctionDecl *Specialization = 0;
2707 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002708 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002709 Args, NumArgs, Specialization, Info)) {
2710 // FIXME: Record what happened with template argument deduction, so
2711 // that we can give the user a beautiful diagnostic.
2712 (void)Result;
2713 return;
2714 }
Mike Stump11289f42009-09-09 15:08:12 +00002715
Douglas Gregor97628d62009-08-21 00:16:32 +00002716 // Add the function template specialization produced by template argument
2717 // deduction as a candidate.
2718 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002719 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002720 "Specialization is not a member function?");
John McCallb89836b2010-01-26 01:37:31 +00002721 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Access,
2722 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002723 CandidateSet, SuppressUserConversions, ForceRValue);
2724}
2725
Douglas Gregor05155d82009-08-21 23:19:43 +00002726/// \brief Add a C++ function template specialization as a candidate
2727/// in the candidate set, using template argument deduction to produce
2728/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002729void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002730Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCallb89836b2010-01-26 01:37:31 +00002731 AccessSpecifier Access,
John McCall6b51f282009-11-23 01:53:49 +00002732 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002733 Expr **Args, unsigned NumArgs,
2734 OverloadCandidateSet& CandidateSet,
2735 bool SuppressUserConversions,
2736 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002737 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2738 return;
2739
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002740 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002741 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002742 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002743 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002744 // candidate functions in the usual way.113) A given name can refer to one
2745 // or more function templates and also to a set of overloaded non-template
2746 // functions. In such a case, the candidate functions generated from each
2747 // function template are combined with the set of non-template candidate
2748 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00002749 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002750 FunctionDecl *Specialization = 0;
2751 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002752 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002753 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00002754 CandidateSet.push_back(OverloadCandidate());
2755 OverloadCandidate &Candidate = CandidateSet.back();
2756 Candidate.Function = FunctionTemplate->getTemplatedDecl();
John McCallb89836b2010-01-26 01:37:31 +00002757 Candidate.Access = Access;
John McCalld681c392009-12-16 08:11:27 +00002758 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002759 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00002760 Candidate.IsSurrogate = false;
2761 Candidate.IgnoreObjectArgument = false;
John McCall8b9ed552010-02-01 18:53:26 +00002762
2763 // TODO: record more information about failed template arguments
2764 Candidate.DeductionFailure.Result = Result;
2765 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002766 return;
2767 }
Mike Stump11289f42009-09-09 15:08:12 +00002768
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002769 // Add the function template specialization produced by template argument
2770 // deduction as a candidate.
2771 assert(Specialization && "Missing function template specialization?");
John McCallb89836b2010-01-26 01:37:31 +00002772 AddOverloadCandidate(Specialization, Access, Args, NumArgs, CandidateSet,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002773 SuppressUserConversions, ForceRValue);
2774}
Mike Stump11289f42009-09-09 15:08:12 +00002775
Douglas Gregora1f013e2008-11-07 22:36:19 +00002776/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002777/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002778/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002779/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002780/// (which may or may not be the same type as the type that the
2781/// conversion function produces).
2782void
2783Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCallb89836b2010-01-26 01:37:31 +00002784 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002785 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002786 Expr *From, QualType ToType,
2787 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002788 assert(!Conversion->getDescribedFunctionTemplate() &&
2789 "Conversion function templates use AddTemplateConversionCandidate");
2790
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002791 if (!CandidateSet.isNewCandidate(Conversion))
2792 return;
2793
Douglas Gregor27381f32009-11-23 12:27:39 +00002794 // Overload resolution is always an unevaluated context.
2795 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2796
Douglas Gregora1f013e2008-11-07 22:36:19 +00002797 // Add this candidate
2798 CandidateSet.push_back(OverloadCandidate());
2799 OverloadCandidate& Candidate = CandidateSet.back();
2800 Candidate.Function = Conversion;
John McCallb89836b2010-01-26 01:37:31 +00002801 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002802 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002803 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002804 Candidate.FinalConversion.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002805 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002806 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00002807
Douglas Gregor436424c2008-11-18 23:14:02 +00002808 // Determine the implicit conversion sequence for the implicit
2809 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002810 Candidate.Viable = true;
2811 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002812 Candidate.Conversions[0]
2813 = TryObjectArgumentInitialization(From->getType(), Conversion,
2814 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002815 // Conversion functions to a different type in the base class is visible in
2816 // the derived class. So, a derived to base conversion should not participate
2817 // in overload resolution.
2818 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2819 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00002820 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002821 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002822 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002823 return;
2824 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002825
2826 // We won't go through a user-define type conversion function to convert a
2827 // derived to base as such conversions are given Conversion Rank. They only
2828 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2829 QualType FromCanon
2830 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2831 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2832 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2833 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00002834 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002835 return;
2836 }
2837
Douglas Gregora1f013e2008-11-07 22:36:19 +00002838
2839 // To determine what the conversion from the result of calling the
2840 // conversion function to the type we're eventually trying to
2841 // convert to (ToType), we need to synthesize a call to the
2842 // conversion function and attempt copy initialization from it. This
2843 // makes sure that we get the right semantics with respect to
2844 // lvalues/rvalues and the type. Fortunately, we can allocate this
2845 // call on the stack and we don't need its arguments to be
2846 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002847 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002848 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002849 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002850 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002851 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002852
2853 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002854 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2855 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002856 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002857 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002858 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002859 ImplicitConversionSequence ICS =
2860 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002861 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002862 /*ForceRValue=*/false,
2863 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002864
John McCall0d1da222010-01-12 00:44:57 +00002865 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002866 case ImplicitConversionSequence::StandardConversion:
2867 Candidate.FinalConversion = ICS.Standard;
2868 break;
2869
2870 case ImplicitConversionSequence::BadConversion:
2871 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00002872 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002873 break;
2874
2875 default:
Mike Stump11289f42009-09-09 15:08:12 +00002876 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002877 "Can only end up with a standard conversion sequence or failure");
2878 }
2879}
2880
Douglas Gregor05155d82009-08-21 23:19:43 +00002881/// \brief Adds a conversion function template specialization
2882/// candidate to the overload set, using template argument deduction
2883/// to deduce the template arguments of the conversion function
2884/// template from the type that we are converting to (C++
2885/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002886void
Douglas Gregor05155d82009-08-21 23:19:43 +00002887Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCallb89836b2010-01-26 01:37:31 +00002888 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002889 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002890 Expr *From, QualType ToType,
2891 OverloadCandidateSet &CandidateSet) {
2892 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2893 "Only conversion function templates permitted here");
2894
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002895 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2896 return;
2897
John McCallbc077cf2010-02-08 23:07:23 +00002898 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00002899 CXXConversionDecl *Specialization = 0;
2900 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002901 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002902 Specialization, Info)) {
2903 // FIXME: Record what happened with template argument deduction, so
2904 // that we can give the user a beautiful diagnostic.
2905 (void)Result;
2906 return;
2907 }
Mike Stump11289f42009-09-09 15:08:12 +00002908
Douglas Gregor05155d82009-08-21 23:19:43 +00002909 // Add the conversion function template specialization produced by
2910 // template argument deduction as a candidate.
2911 assert(Specialization && "Missing function template specialization?");
John McCallb89836b2010-01-26 01:37:31 +00002912 AddConversionCandidate(Specialization, Access, ActingDC, From, ToType,
2913 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002914}
2915
Douglas Gregorab7897a2008-11-19 22:57:39 +00002916/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2917/// converts the given @c Object to a function pointer via the
2918/// conversion function @c Conversion, and then attempts to call it
2919/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2920/// the type of function that we'll eventually be calling.
2921void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCallb89836b2010-01-26 01:37:31 +00002922 AccessSpecifier Access,
John McCall6e9f8f62009-12-03 04:06:58 +00002923 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002924 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002925 QualType ObjectType,
2926 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002927 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002928 if (!CandidateSet.isNewCandidate(Conversion))
2929 return;
2930
Douglas Gregor27381f32009-11-23 12:27:39 +00002931 // Overload resolution is always an unevaluated context.
2932 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2933
Douglas Gregorab7897a2008-11-19 22:57:39 +00002934 CandidateSet.push_back(OverloadCandidate());
2935 OverloadCandidate& Candidate = CandidateSet.back();
2936 Candidate.Function = 0;
John McCallb89836b2010-01-26 01:37:31 +00002937 Candidate.Access = Access;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002938 Candidate.Surrogate = Conversion;
2939 Candidate.Viable = true;
2940 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002941 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002942 Candidate.Conversions.resize(NumArgs + 1);
2943
2944 // Determine the implicit conversion sequence for the implicit
2945 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002946 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002947 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002948 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002949 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002950 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00002951 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002952 return;
2953 }
2954
2955 // The first conversion is actually a user-defined conversion whose
2956 // first conversion is ObjectInit's standard conversion (which is
2957 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00002958 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002959 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002960 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002961 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002962 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002963 = Candidate.Conversions[0].UserDefined.Before;
2964 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2965
Mike Stump11289f42009-09-09 15:08:12 +00002966 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002967 unsigned NumArgsInProto = Proto->getNumArgs();
2968
2969 // (C++ 13.3.2p2): A candidate function having fewer than m
2970 // parameters is viable only if it has an ellipsis in its parameter
2971 // list (8.3.5).
2972 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2973 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002974 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002975 return;
2976 }
2977
2978 // Function types don't have any default arguments, so just check if
2979 // we have enough arguments.
2980 if (NumArgs < NumArgsInProto) {
2981 // Not enough arguments.
2982 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002983 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002984 return;
2985 }
2986
2987 // Determine the implicit conversion sequences for each of the
2988 // arguments.
2989 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2990 if (ArgIdx < NumArgsInProto) {
2991 // (C++ 13.3.2p3): for F to be a viable function, there shall
2992 // exist for each argument an implicit conversion sequence
2993 // (13.3.3.1) that converts that argument to the corresponding
2994 // parameter of F.
2995 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002996 Candidate.Conversions[ArgIdx + 1]
2997 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002998 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002999 /*ForceRValue=*/false,
3000 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003001 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003002 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003003 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003004 break;
3005 }
3006 } else {
3007 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3008 // argument for which there is no corresponding parameter is
3009 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003010 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003011 }
3012 }
3013}
3014
Mike Stump87c57ac2009-05-16 07:39:55 +00003015// FIXME: This will eventually be removed, once we've migrated all of the
3016// operator overloading logic over to the scheme used by binary operators, which
3017// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003018void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003019 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00003020 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003021 OverloadCandidateSet& CandidateSet,
3022 SourceRange OpRange) {
John McCall4c4c1df2010-01-26 03:27:55 +00003023 UnresolvedSet<16> Fns;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003024
3025 QualType T1 = Args[0]->getType();
3026 QualType T2;
3027 if (NumArgs > 1)
3028 T2 = Args[1]->getType();
3029
3030 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003031 if (S)
John McCall4c4c1df2010-01-26 03:27:55 +00003032 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3033 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3034 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3035 CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003036 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003037 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003038}
3039
3040/// \brief Add overload candidates for overloaded operators that are
3041/// member functions.
3042///
3043/// Add the overloaded operator candidates that are member functions
3044/// for the operator Op that was used in an operator expression such
3045/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3046/// CandidateSet will store the added overload candidates. (C++
3047/// [over.match.oper]).
3048void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3049 SourceLocation OpLoc,
3050 Expr **Args, unsigned NumArgs,
3051 OverloadCandidateSet& CandidateSet,
3052 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003053 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3054
3055 // C++ [over.match.oper]p3:
3056 // For a unary operator @ with an operand of a type whose
3057 // cv-unqualified version is T1, and for a binary operator @ with
3058 // a left operand of a type whose cv-unqualified version is T1 and
3059 // a right operand of a type whose cv-unqualified version is T2,
3060 // three sets of candidate functions, designated member
3061 // candidates, non-member candidates and built-in candidates, are
3062 // constructed as follows:
3063 QualType T1 = Args[0]->getType();
3064 QualType T2;
3065 if (NumArgs > 1)
3066 T2 = Args[1]->getType();
3067
3068 // -- If T1 is a class type, the set of member candidates is the
3069 // result of the qualified lookup of T1::operator@
3070 // (13.3.1.1.1); otherwise, the set of member candidates is
3071 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003072 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003073 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003074 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003075 return;
Mike Stump11289f42009-09-09 15:08:12 +00003076
John McCall27b18f82009-11-17 02:14:36 +00003077 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3078 LookupQualifiedName(Operators, T1Rec->getDecl());
3079 Operators.suppressDiagnostics();
3080
Mike Stump11289f42009-09-09 15:08:12 +00003081 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003082 OperEnd = Operators.end();
3083 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003084 ++Oper)
John McCallb89836b2010-01-26 01:37:31 +00003085 AddMethodCandidate(*Oper, Oper.getAccess(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003086 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003087 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003088 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003089}
3090
Douglas Gregora11693b2008-11-12 17:17:38 +00003091/// AddBuiltinCandidate - Add a candidate for a built-in
3092/// operator. ResultTy and ParamTys are the result and parameter types
3093/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003094/// arguments being passed to the candidate. IsAssignmentOperator
3095/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003096/// operator. NumContextualBoolArguments is the number of arguments
3097/// (at the beginning of the argument list) that will be contextually
3098/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003099void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003100 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003101 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003102 bool IsAssignmentOperator,
3103 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003104 // Overload resolution is always an unevaluated context.
3105 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3106
Douglas Gregora11693b2008-11-12 17:17:38 +00003107 // Add this candidate
3108 CandidateSet.push_back(OverloadCandidate());
3109 OverloadCandidate& Candidate = CandidateSet.back();
3110 Candidate.Function = 0;
John McCallb89836b2010-01-26 01:37:31 +00003111 Candidate.Access = AS_none;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003112 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003113 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003114 Candidate.BuiltinTypes.ResultTy = ResultTy;
3115 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3116 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3117
3118 // Determine the implicit conversion sequences for each of the
3119 // arguments.
3120 Candidate.Viable = true;
3121 Candidate.Conversions.resize(NumArgs);
3122 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003123 // C++ [over.match.oper]p4:
3124 // For the built-in assignment operators, conversions of the
3125 // left operand are restricted as follows:
3126 // -- no temporaries are introduced to hold the left operand, and
3127 // -- no user-defined conversions are applied to the left
3128 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003129 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003130 //
3131 // We block these conversions by turning off user-defined
3132 // conversions, since that is the only way that initialization of
3133 // a reference to a non-class type can occur from something that
3134 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003135 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003136 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003137 "Contextual conversion to bool requires bool type");
3138 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3139 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003140 Candidate.Conversions[ArgIdx]
3141 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003142 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003143 /*ForceRValue=*/false,
3144 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003145 }
John McCall0d1da222010-01-12 00:44:57 +00003146 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003147 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003148 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003149 break;
3150 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003151 }
3152}
3153
3154/// BuiltinCandidateTypeSet - A set of types that will be used for the
3155/// candidate operator functions for built-in operators (C++
3156/// [over.built]). The types are separated into pointer types and
3157/// enumeration types.
3158class BuiltinCandidateTypeSet {
3159 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003160 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003161
3162 /// PointerTypes - The set of pointer types that will be used in the
3163 /// built-in candidates.
3164 TypeSet PointerTypes;
3165
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003166 /// MemberPointerTypes - The set of member pointer types that will be
3167 /// used in the built-in candidates.
3168 TypeSet MemberPointerTypes;
3169
Douglas Gregora11693b2008-11-12 17:17:38 +00003170 /// EnumerationTypes - The set of enumeration types that will be
3171 /// used in the built-in candidates.
3172 TypeSet EnumerationTypes;
3173
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003174 /// Sema - The semantic analysis instance where we are building the
3175 /// candidate type set.
3176 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003177
Douglas Gregora11693b2008-11-12 17:17:38 +00003178 /// Context - The AST context in which we will build the type sets.
3179 ASTContext &Context;
3180
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003181 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3182 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003183 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003184
3185public:
3186 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003187 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003188
Mike Stump11289f42009-09-09 15:08:12 +00003189 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003190 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003191
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003192 void AddTypesConvertedFrom(QualType Ty,
3193 SourceLocation Loc,
3194 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003195 bool AllowExplicitConversions,
3196 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003197
3198 /// pointer_begin - First pointer type found;
3199 iterator pointer_begin() { return PointerTypes.begin(); }
3200
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003201 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003202 iterator pointer_end() { return PointerTypes.end(); }
3203
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003204 /// member_pointer_begin - First member pointer type found;
3205 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3206
3207 /// member_pointer_end - Past the last member pointer type found;
3208 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3209
Douglas Gregora11693b2008-11-12 17:17:38 +00003210 /// enumeration_begin - First enumeration type found;
3211 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3212
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003213 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003214 iterator enumeration_end() { return EnumerationTypes.end(); }
3215};
3216
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003217/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003218/// the set of pointer types along with any more-qualified variants of
3219/// that type. For example, if @p Ty is "int const *", this routine
3220/// will add "int const *", "int const volatile *", "int const
3221/// restrict *", and "int const volatile restrict *" to the set of
3222/// pointer types. Returns true if the add of @p Ty itself succeeded,
3223/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003224///
3225/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003226bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003227BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3228 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003229
Douglas Gregora11693b2008-11-12 17:17:38 +00003230 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003231 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003232 return false;
3233
John McCall8ccfcb52009-09-24 19:53:00 +00003234 const PointerType *PointerTy = Ty->getAs<PointerType>();
3235 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003236
John McCall8ccfcb52009-09-24 19:53:00 +00003237 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003238 // Don't add qualified variants of arrays. For one, they're not allowed
3239 // (the qualifier would sink to the element type), and for another, the
3240 // only overload situation where it matters is subscript or pointer +- int,
3241 // and those shouldn't have qualifier variants anyway.
3242 if (PointeeTy->isArrayType())
3243 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003244 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003245 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003246 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003247 bool hasVolatile = VisibleQuals.hasVolatile();
3248 bool hasRestrict = VisibleQuals.hasRestrict();
3249
John McCall8ccfcb52009-09-24 19:53:00 +00003250 // Iterate through all strict supersets of BaseCVR.
3251 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3252 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003253 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3254 // in the types.
3255 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3256 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003257 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3258 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003259 }
3260
3261 return true;
3262}
3263
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003264/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3265/// to the set of pointer types along with any more-qualified variants of
3266/// that type. For example, if @p Ty is "int const *", this routine
3267/// will add "int const *", "int const volatile *", "int const
3268/// restrict *", and "int const volatile restrict *" to the set of
3269/// pointer types. Returns true if the add of @p Ty itself succeeded,
3270/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003271///
3272/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003273bool
3274BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3275 QualType Ty) {
3276 // Insert this type.
3277 if (!MemberPointerTypes.insert(Ty))
3278 return false;
3279
John McCall8ccfcb52009-09-24 19:53:00 +00003280 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3281 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003282
John McCall8ccfcb52009-09-24 19:53:00 +00003283 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003284 // Don't add qualified variants of arrays. For one, they're not allowed
3285 // (the qualifier would sink to the element type), and for another, the
3286 // only overload situation where it matters is subscript or pointer +- int,
3287 // and those shouldn't have qualifier variants anyway.
3288 if (PointeeTy->isArrayType())
3289 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003290 const Type *ClassTy = PointerTy->getClass();
3291
3292 // Iterate through all strict supersets of the pointee type's CVR
3293 // qualifiers.
3294 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3295 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3296 if ((CVR | BaseCVR) != CVR) continue;
3297
3298 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3299 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003300 }
3301
3302 return true;
3303}
3304
Douglas Gregora11693b2008-11-12 17:17:38 +00003305/// AddTypesConvertedFrom - Add each of the types to which the type @p
3306/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003307/// primarily interested in pointer types and enumeration types. We also
3308/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003309/// AllowUserConversions is true if we should look at the conversion
3310/// functions of a class type, and AllowExplicitConversions if we
3311/// should also include the explicit conversion functions of a class
3312/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003313void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003314BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003315 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003316 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003317 bool AllowExplicitConversions,
3318 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003319 // Only deal with canonical types.
3320 Ty = Context.getCanonicalType(Ty);
3321
3322 // Look through reference types; they aren't part of the type of an
3323 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003324 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003325 Ty = RefTy->getPointeeType();
3326
3327 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003328 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003329
Sebastian Redl65ae2002009-11-05 16:36:20 +00003330 // If we're dealing with an array type, decay to the pointer.
3331 if (Ty->isArrayType())
3332 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3333
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003334 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003335 QualType PointeeTy = PointerTy->getPointeeType();
3336
3337 // Insert our type, and its more-qualified variants, into the set
3338 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003339 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003340 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003341 } else if (Ty->isMemberPointerType()) {
3342 // Member pointers are far easier, since the pointee can't be converted.
3343 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3344 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003345 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003346 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003347 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003348 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003349 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003350 // No conversion functions in incomplete types.
3351 return;
3352 }
Mike Stump11289f42009-09-09 15:08:12 +00003353
Douglas Gregora11693b2008-11-12 17:17:38 +00003354 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003355 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003356 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003357 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003358 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003359
Mike Stump11289f42009-09-09 15:08:12 +00003360 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003361 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003362 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003363 continue;
3364
John McCalld14a8642009-11-21 08:51:07 +00003365 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003366 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003367 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003368 VisibleQuals);
3369 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003370 }
3371 }
3372 }
3373}
3374
Douglas Gregor84605ae2009-08-24 13:43:27 +00003375/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3376/// the volatile- and non-volatile-qualified assignment operators for the
3377/// given type to the candidate set.
3378static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3379 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003380 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003381 unsigned NumArgs,
3382 OverloadCandidateSet &CandidateSet) {
3383 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003384
Douglas Gregor84605ae2009-08-24 13:43:27 +00003385 // T& operator=(T&, T)
3386 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3387 ParamTypes[1] = T;
3388 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3389 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003390
Douglas Gregor84605ae2009-08-24 13:43:27 +00003391 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3392 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003393 ParamTypes[0]
3394 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003395 ParamTypes[1] = T;
3396 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003397 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003398 }
3399}
Mike Stump11289f42009-09-09 15:08:12 +00003400
Sebastian Redl1054fae2009-10-25 17:03:50 +00003401/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3402/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003403static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3404 Qualifiers VRQuals;
3405 const RecordType *TyRec;
3406 if (const MemberPointerType *RHSMPType =
3407 ArgExpr->getType()->getAs<MemberPointerType>())
3408 TyRec = cast<RecordType>(RHSMPType->getClass());
3409 else
3410 TyRec = ArgExpr->getType()->getAs<RecordType>();
3411 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003412 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003413 VRQuals.addVolatile();
3414 VRQuals.addRestrict();
3415 return VRQuals;
3416 }
3417
3418 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003419 if (!ClassDecl->hasDefinition())
3420 return VRQuals;
3421
John McCallad371252010-01-20 00:46:10 +00003422 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003423 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003424
John McCallad371252010-01-20 00:46:10 +00003425 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003426 E = Conversions->end(); I != E; ++I) {
3427 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003428 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3429 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3430 CanTy = ResTypeRef->getPointeeType();
3431 // Need to go down the pointer/mempointer chain and add qualifiers
3432 // as see them.
3433 bool done = false;
3434 while (!done) {
3435 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3436 CanTy = ResTypePtr->getPointeeType();
3437 else if (const MemberPointerType *ResTypeMPtr =
3438 CanTy->getAs<MemberPointerType>())
3439 CanTy = ResTypeMPtr->getPointeeType();
3440 else
3441 done = true;
3442 if (CanTy.isVolatileQualified())
3443 VRQuals.addVolatile();
3444 if (CanTy.isRestrictQualified())
3445 VRQuals.addRestrict();
3446 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3447 return VRQuals;
3448 }
3449 }
3450 }
3451 return VRQuals;
3452}
3453
Douglas Gregord08452f2008-11-19 15:42:04 +00003454/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3455/// operator overloads to the candidate set (C++ [over.built]), based
3456/// on the operator @p Op and the arguments given. For example, if the
3457/// operator is a binary '+', this routine might add "int
3458/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003459void
Mike Stump11289f42009-09-09 15:08:12 +00003460Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003461 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003462 Expr **Args, unsigned NumArgs,
3463 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003464 // The set of "promoted arithmetic types", which are the arithmetic
3465 // types are that preserved by promotion (C++ [over.built]p2). Note
3466 // that the first few of these types are the promoted integral
3467 // types; these types need to be first.
3468 // FIXME: What about complex?
3469 const unsigned FirstIntegralType = 0;
3470 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003471 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003472 LastPromotedIntegralType = 13;
3473 const unsigned FirstPromotedArithmeticType = 7,
3474 LastPromotedArithmeticType = 16;
3475 const unsigned NumArithmeticTypes = 16;
3476 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003477 Context.BoolTy, Context.CharTy, Context.WCharTy,
3478// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003479 Context.SignedCharTy, Context.ShortTy,
3480 Context.UnsignedCharTy, Context.UnsignedShortTy,
3481 Context.IntTy, Context.LongTy, Context.LongLongTy,
3482 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3483 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3484 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003485 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3486 "Invalid first promoted integral type");
3487 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3488 == Context.UnsignedLongLongTy &&
3489 "Invalid last promoted integral type");
3490 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3491 "Invalid first promoted arithmetic type");
3492 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3493 == Context.LongDoubleTy &&
3494 "Invalid last promoted arithmetic type");
3495
Douglas Gregora11693b2008-11-12 17:17:38 +00003496 // Find all of the types that the arguments can convert to, but only
3497 // if the operator we're looking at has built-in operator candidates
3498 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003499 Qualifiers VisibleTypeConversionsQuals;
3500 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003501 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3502 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3503
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003504 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003505 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3506 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003507 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003508 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003509 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003510 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003511 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003512 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003513 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003514 true,
3515 (Op == OO_Exclaim ||
3516 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003517 Op == OO_PipePipe),
3518 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003519 }
3520
3521 bool isComparison = false;
3522 switch (Op) {
3523 case OO_None:
3524 case NUM_OVERLOADED_OPERATORS:
3525 assert(false && "Expected an overloaded operator");
3526 break;
3527
Douglas Gregord08452f2008-11-19 15:42:04 +00003528 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003529 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003530 goto UnaryStar;
3531 else
3532 goto BinaryStar;
3533 break;
3534
3535 case OO_Plus: // '+' is either unary or binary
3536 if (NumArgs == 1)
3537 goto UnaryPlus;
3538 else
3539 goto BinaryPlus;
3540 break;
3541
3542 case OO_Minus: // '-' is either unary or binary
3543 if (NumArgs == 1)
3544 goto UnaryMinus;
3545 else
3546 goto BinaryMinus;
3547 break;
3548
3549 case OO_Amp: // '&' is either unary or binary
3550 if (NumArgs == 1)
3551 goto UnaryAmp;
3552 else
3553 goto BinaryAmp;
3554
3555 case OO_PlusPlus:
3556 case OO_MinusMinus:
3557 // C++ [over.built]p3:
3558 //
3559 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3560 // is either volatile or empty, there exist candidate operator
3561 // functions of the form
3562 //
3563 // VQ T& operator++(VQ T&);
3564 // T operator++(VQ T&, int);
3565 //
3566 // C++ [over.built]p4:
3567 //
3568 // For every pair (T, VQ), where T is an arithmetic type other
3569 // than bool, and VQ is either volatile or empty, there exist
3570 // candidate operator functions of the form
3571 //
3572 // VQ T& operator--(VQ T&);
3573 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003574 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003575 Arith < NumArithmeticTypes; ++Arith) {
3576 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003577 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003578 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003579
3580 // Non-volatile version.
3581 if (NumArgs == 1)
3582 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3583 else
3584 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003585 // heuristic to reduce number of builtin candidates in the set.
3586 // Add volatile version only if there are conversions to a volatile type.
3587 if (VisibleTypeConversionsQuals.hasVolatile()) {
3588 // Volatile version
3589 ParamTypes[0]
3590 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3591 if (NumArgs == 1)
3592 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3593 else
3594 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3595 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003596 }
3597
3598 // C++ [over.built]p5:
3599 //
3600 // For every pair (T, VQ), where T is a cv-qualified or
3601 // cv-unqualified object type, and VQ is either volatile or
3602 // empty, there exist candidate operator functions of the form
3603 //
3604 // T*VQ& operator++(T*VQ&);
3605 // T*VQ& operator--(T*VQ&);
3606 // T* operator++(T*VQ&, int);
3607 // T* operator--(T*VQ&, int);
3608 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3609 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3610 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003611 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003612 continue;
3613
Mike Stump11289f42009-09-09 15:08:12 +00003614 QualType ParamTypes[2] = {
3615 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003616 };
Mike Stump11289f42009-09-09 15:08:12 +00003617
Douglas Gregord08452f2008-11-19 15:42:04 +00003618 // Without volatile
3619 if (NumArgs == 1)
3620 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3621 else
3622 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3623
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003624 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3625 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003626 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003627 ParamTypes[0]
3628 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003629 if (NumArgs == 1)
3630 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3631 else
3632 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3633 }
3634 }
3635 break;
3636
3637 UnaryStar:
3638 // C++ [over.built]p6:
3639 // For every cv-qualified or cv-unqualified object type T, there
3640 // exist candidate operator functions of the form
3641 //
3642 // T& operator*(T*);
3643 //
3644 // C++ [over.built]p7:
3645 // For every function type T, there exist candidate operator
3646 // functions of the form
3647 // T& operator*(T*);
3648 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3649 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3650 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003651 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003652 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003653 &ParamTy, Args, 1, CandidateSet);
3654 }
3655 break;
3656
3657 UnaryPlus:
3658 // C++ [over.built]p8:
3659 // For every type T, there exist candidate operator functions of
3660 // the form
3661 //
3662 // T* operator+(T*);
3663 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3664 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3665 QualType ParamTy = *Ptr;
3666 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3667 }
Mike Stump11289f42009-09-09 15:08:12 +00003668
Douglas Gregord08452f2008-11-19 15:42:04 +00003669 // Fall through
3670
3671 UnaryMinus:
3672 // C++ [over.built]p9:
3673 // For every promoted arithmetic type T, there exist candidate
3674 // operator functions of the form
3675 //
3676 // T operator+(T);
3677 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003678 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003679 Arith < LastPromotedArithmeticType; ++Arith) {
3680 QualType ArithTy = ArithmeticTypes[Arith];
3681 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3682 }
3683 break;
3684
3685 case OO_Tilde:
3686 // C++ [over.built]p10:
3687 // For every promoted integral type T, there exist candidate
3688 // operator functions of the form
3689 //
3690 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003691 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003692 Int < LastPromotedIntegralType; ++Int) {
3693 QualType IntTy = ArithmeticTypes[Int];
3694 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3695 }
3696 break;
3697
Douglas Gregora11693b2008-11-12 17:17:38 +00003698 case OO_New:
3699 case OO_Delete:
3700 case OO_Array_New:
3701 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003702 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003703 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003704 break;
3705
3706 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003707 UnaryAmp:
3708 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003709 // C++ [over.match.oper]p3:
3710 // -- For the operator ',', the unary operator '&', or the
3711 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003712 break;
3713
Douglas Gregor84605ae2009-08-24 13:43:27 +00003714 case OO_EqualEqual:
3715 case OO_ExclaimEqual:
3716 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003717 // For every pointer to member type T, there exist candidate operator
3718 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003719 //
3720 // bool operator==(T,T);
3721 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003722 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003723 MemPtr = CandidateTypes.member_pointer_begin(),
3724 MemPtrEnd = CandidateTypes.member_pointer_end();
3725 MemPtr != MemPtrEnd;
3726 ++MemPtr) {
3727 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3728 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3729 }
Mike Stump11289f42009-09-09 15:08:12 +00003730
Douglas Gregor84605ae2009-08-24 13:43:27 +00003731 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003732
Douglas Gregora11693b2008-11-12 17:17:38 +00003733 case OO_Less:
3734 case OO_Greater:
3735 case OO_LessEqual:
3736 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003737 // C++ [over.built]p15:
3738 //
3739 // For every pointer or enumeration type T, there exist
3740 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003741 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003742 // bool operator<(T, T);
3743 // bool operator>(T, T);
3744 // bool operator<=(T, T);
3745 // bool operator>=(T, T);
3746 // bool operator==(T, T);
3747 // bool operator!=(T, T);
3748 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3749 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3750 QualType ParamTypes[2] = { *Ptr, *Ptr };
3751 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3752 }
Mike Stump11289f42009-09-09 15:08:12 +00003753 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003754 = CandidateTypes.enumeration_begin();
3755 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3756 QualType ParamTypes[2] = { *Enum, *Enum };
3757 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3758 }
3759
3760 // Fall through.
3761 isComparison = true;
3762
Douglas Gregord08452f2008-11-19 15:42:04 +00003763 BinaryPlus:
3764 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003765 if (!isComparison) {
3766 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3767
3768 // C++ [over.built]p13:
3769 //
3770 // For every cv-qualified or cv-unqualified object type T
3771 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003772 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003773 // T* operator+(T*, ptrdiff_t);
3774 // T& operator[](T*, ptrdiff_t); [BELOW]
3775 // T* operator-(T*, ptrdiff_t);
3776 // T* operator+(ptrdiff_t, T*);
3777 // T& operator[](ptrdiff_t, T*); [BELOW]
3778 //
3779 // C++ [over.built]p14:
3780 //
3781 // For every T, where T is a pointer to object type, there
3782 // exist candidate operator functions of the form
3783 //
3784 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003785 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003786 = CandidateTypes.pointer_begin();
3787 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3788 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3789
3790 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3791 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3792
3793 if (Op == OO_Plus) {
3794 // T* operator+(ptrdiff_t, T*);
3795 ParamTypes[0] = ParamTypes[1];
3796 ParamTypes[1] = *Ptr;
3797 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3798 } else {
3799 // ptrdiff_t operator-(T, T);
3800 ParamTypes[1] = *Ptr;
3801 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3802 Args, 2, CandidateSet);
3803 }
3804 }
3805 }
3806 // Fall through
3807
Douglas Gregora11693b2008-11-12 17:17:38 +00003808 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003809 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003810 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003811 // C++ [over.built]p12:
3812 //
3813 // For every pair of promoted arithmetic types L and R, there
3814 // exist candidate operator functions of the form
3815 //
3816 // LR operator*(L, R);
3817 // LR operator/(L, R);
3818 // LR operator+(L, R);
3819 // LR operator-(L, R);
3820 // bool operator<(L, R);
3821 // bool operator>(L, R);
3822 // bool operator<=(L, R);
3823 // bool operator>=(L, R);
3824 // bool operator==(L, R);
3825 // bool operator!=(L, R);
3826 //
3827 // where LR is the result of the usual arithmetic conversions
3828 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003829 //
3830 // C++ [over.built]p24:
3831 //
3832 // For every pair of promoted arithmetic types L and R, there exist
3833 // candidate operator functions of the form
3834 //
3835 // LR operator?(bool, L, R);
3836 //
3837 // where LR is the result of the usual arithmetic conversions
3838 // between types L and R.
3839 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003840 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003841 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003842 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003843 Right < LastPromotedArithmeticType; ++Right) {
3844 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003845 QualType Result
3846 = isComparison
3847 ? Context.BoolTy
3848 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003849 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3850 }
3851 }
3852 break;
3853
3854 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003855 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003856 case OO_Caret:
3857 case OO_Pipe:
3858 case OO_LessLess:
3859 case OO_GreaterGreater:
3860 // C++ [over.built]p17:
3861 //
3862 // For every pair of promoted integral types L and R, there
3863 // exist candidate operator functions of the form
3864 //
3865 // LR operator%(L, R);
3866 // LR operator&(L, R);
3867 // LR operator^(L, R);
3868 // LR operator|(L, R);
3869 // L operator<<(L, R);
3870 // L operator>>(L, R);
3871 //
3872 // where LR is the result of the usual arithmetic conversions
3873 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003874 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003875 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003876 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003877 Right < LastPromotedIntegralType; ++Right) {
3878 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3879 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3880 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003881 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003882 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3883 }
3884 }
3885 break;
3886
3887 case OO_Equal:
3888 // C++ [over.built]p20:
3889 //
3890 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003891 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003892 // empty, there exist candidate operator functions of the form
3893 //
3894 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003895 for (BuiltinCandidateTypeSet::iterator
3896 Enum = CandidateTypes.enumeration_begin(),
3897 EnumEnd = CandidateTypes.enumeration_end();
3898 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003899 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003900 CandidateSet);
3901 for (BuiltinCandidateTypeSet::iterator
3902 MemPtr = CandidateTypes.member_pointer_begin(),
3903 MemPtrEnd = CandidateTypes.member_pointer_end();
3904 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003905 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003906 CandidateSet);
3907 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003908
3909 case OO_PlusEqual:
3910 case OO_MinusEqual:
3911 // C++ [over.built]p19:
3912 //
3913 // For every pair (T, VQ), where T is any type and VQ is either
3914 // volatile or empty, there exist candidate operator functions
3915 // of the form
3916 //
3917 // T*VQ& operator=(T*VQ&, T*);
3918 //
3919 // C++ [over.built]p21:
3920 //
3921 // For every pair (T, VQ), where T is a cv-qualified or
3922 // cv-unqualified object type and VQ is either volatile or
3923 // empty, there exist candidate operator functions of the form
3924 //
3925 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3926 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3927 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3928 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3929 QualType ParamTypes[2];
3930 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3931
3932 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003933 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003934 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3935 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003936
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003937 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3938 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003939 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003940 ParamTypes[0]
3941 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003942 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3943 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003944 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003945 }
3946 // Fall through.
3947
3948 case OO_StarEqual:
3949 case OO_SlashEqual:
3950 // C++ [over.built]p18:
3951 //
3952 // For every triple (L, VQ, R), where L is an arithmetic type,
3953 // VQ is either volatile or empty, and R is a promoted
3954 // arithmetic type, there exist candidate operator functions of
3955 // the form
3956 //
3957 // VQ L& operator=(VQ L&, R);
3958 // VQ L& operator*=(VQ L&, R);
3959 // VQ L& operator/=(VQ L&, R);
3960 // VQ L& operator+=(VQ L&, R);
3961 // VQ L& operator-=(VQ L&, R);
3962 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003963 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003964 Right < LastPromotedArithmeticType; ++Right) {
3965 QualType ParamTypes[2];
3966 ParamTypes[1] = ArithmeticTypes[Right];
3967
3968 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003969 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003970 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3971 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003972
3973 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003974 if (VisibleTypeConversionsQuals.hasVolatile()) {
3975 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3976 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3977 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3978 /*IsAssigmentOperator=*/Op == OO_Equal);
3979 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003980 }
3981 }
3982 break;
3983
3984 case OO_PercentEqual:
3985 case OO_LessLessEqual:
3986 case OO_GreaterGreaterEqual:
3987 case OO_AmpEqual:
3988 case OO_CaretEqual:
3989 case OO_PipeEqual:
3990 // C++ [over.built]p22:
3991 //
3992 // For every triple (L, VQ, R), where L is an integral type, VQ
3993 // is either volatile or empty, and R is a promoted integral
3994 // type, there exist candidate operator functions of the form
3995 //
3996 // VQ L& operator%=(VQ L&, R);
3997 // VQ L& operator<<=(VQ L&, R);
3998 // VQ L& operator>>=(VQ L&, R);
3999 // VQ L& operator&=(VQ L&, R);
4000 // VQ L& operator^=(VQ L&, R);
4001 // VQ L& operator|=(VQ L&, R);
4002 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004003 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004004 Right < LastPromotedIntegralType; ++Right) {
4005 QualType ParamTypes[2];
4006 ParamTypes[1] = ArithmeticTypes[Right];
4007
4008 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004009 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004010 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004011 if (VisibleTypeConversionsQuals.hasVolatile()) {
4012 // Add this built-in operator as a candidate (VQ is 'volatile').
4013 ParamTypes[0] = ArithmeticTypes[Left];
4014 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4015 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4016 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4017 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004018 }
4019 }
4020 break;
4021
Douglas Gregord08452f2008-11-19 15:42:04 +00004022 case OO_Exclaim: {
4023 // C++ [over.operator]p23:
4024 //
4025 // There also exist candidate operator functions of the form
4026 //
Mike Stump11289f42009-09-09 15:08:12 +00004027 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004028 // bool operator&&(bool, bool); [BELOW]
4029 // bool operator||(bool, bool); [BELOW]
4030 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004031 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4032 /*IsAssignmentOperator=*/false,
4033 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004034 break;
4035 }
4036
Douglas Gregora11693b2008-11-12 17:17:38 +00004037 case OO_AmpAmp:
4038 case OO_PipePipe: {
4039 // C++ [over.operator]p23:
4040 //
4041 // There also exist candidate operator functions of the form
4042 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004043 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004044 // bool operator&&(bool, bool);
4045 // bool operator||(bool, bool);
4046 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004047 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4048 /*IsAssignmentOperator=*/false,
4049 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004050 break;
4051 }
4052
4053 case OO_Subscript:
4054 // C++ [over.built]p13:
4055 //
4056 // For every cv-qualified or cv-unqualified object type T there
4057 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004058 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004059 // T* operator+(T*, ptrdiff_t); [ABOVE]
4060 // T& operator[](T*, ptrdiff_t);
4061 // T* operator-(T*, ptrdiff_t); [ABOVE]
4062 // T* operator+(ptrdiff_t, T*); [ABOVE]
4063 // T& operator[](ptrdiff_t, T*);
4064 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4065 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4066 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004067 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004068 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004069
4070 // T& operator[](T*, ptrdiff_t)
4071 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4072
4073 // T& operator[](ptrdiff_t, T*);
4074 ParamTypes[0] = ParamTypes[1];
4075 ParamTypes[1] = *Ptr;
4076 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4077 }
4078 break;
4079
4080 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004081 // C++ [over.built]p11:
4082 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4083 // C1 is the same type as C2 or is a derived class of C2, T is an object
4084 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4085 // there exist candidate operator functions of the form
4086 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4087 // where CV12 is the union of CV1 and CV2.
4088 {
4089 for (BuiltinCandidateTypeSet::iterator Ptr =
4090 CandidateTypes.pointer_begin();
4091 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4092 QualType C1Ty = (*Ptr);
4093 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004094 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004095 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004096 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004097 if (!isa<RecordType>(C1))
4098 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004099 // heuristic to reduce number of builtin candidates in the set.
4100 // Add volatile/restrict version only if there are conversions to a
4101 // volatile/restrict type.
4102 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4103 continue;
4104 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4105 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004106 }
4107 for (BuiltinCandidateTypeSet::iterator
4108 MemPtr = CandidateTypes.member_pointer_begin(),
4109 MemPtrEnd = CandidateTypes.member_pointer_end();
4110 MemPtr != MemPtrEnd; ++MemPtr) {
4111 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4112 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004113 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004114 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4115 break;
4116 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4117 // build CV12 T&
4118 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004119 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4120 T.isVolatileQualified())
4121 continue;
4122 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4123 T.isRestrictQualified())
4124 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004125 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004126 QualType ResultTy = Context.getLValueReferenceType(T);
4127 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4128 }
4129 }
4130 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004131 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004132
4133 case OO_Conditional:
4134 // Note that we don't consider the first argument, since it has been
4135 // contextually converted to bool long ago. The candidates below are
4136 // therefore added as binary.
4137 //
4138 // C++ [over.built]p24:
4139 // For every type T, where T is a pointer or pointer-to-member type,
4140 // there exist candidate operator functions of the form
4141 //
4142 // T operator?(bool, T, T);
4143 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004144 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4145 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4146 QualType ParamTypes[2] = { *Ptr, *Ptr };
4147 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4148 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004149 for (BuiltinCandidateTypeSet::iterator Ptr =
4150 CandidateTypes.member_pointer_begin(),
4151 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4152 QualType ParamTypes[2] = { *Ptr, *Ptr };
4153 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4154 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004155 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004156 }
4157}
4158
Douglas Gregore254f902009-02-04 00:32:51 +00004159/// \brief Add function candidates found via argument-dependent lookup
4160/// to the set of overloading candidates.
4161///
4162/// This routine performs argument-dependent name lookup based on the
4163/// given function name (which may also be an operator name) and adds
4164/// all of the overload candidates found by ADL to the overload
4165/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004166void
Douglas Gregore254f902009-02-04 00:32:51 +00004167Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004168 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004169 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004170 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004171 OverloadCandidateSet& CandidateSet,
4172 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004173 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004174
John McCall91f61fc2010-01-26 06:04:06 +00004175 // FIXME: This approach for uniquing ADL results (and removing
4176 // redundant candidates from the set) relies on pointer-equality,
4177 // which means we need to key off the canonical decl. However,
4178 // always going back to the canonical decl might not get us the
4179 // right set of default arguments. What default arguments are
4180 // we supposed to consider on ADL candidates, anyway?
4181
Douglas Gregorcabea402009-09-22 15:41:20 +00004182 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004183 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004184
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004185 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004186 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4187 CandEnd = CandidateSet.end();
4188 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004189 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004190 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004191 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004192 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004193 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004194
4195 // For each of the ADL candidates we found, add it to the overload
4196 // set.
John McCall8fe68082010-01-26 07:16:45 +00004197 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00004198 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004199 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004200 continue;
4201
John McCallb89836b2010-01-26 01:37:31 +00004202 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00004203 false, false, PartialOverloading);
4204 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004205 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCallb89836b2010-01-26 01:37:31 +00004206 AS_none, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004207 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004208 }
Douglas Gregore254f902009-02-04 00:32:51 +00004209}
4210
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004211/// isBetterOverloadCandidate - Determines whether the first overload
4212/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004213bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004214Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004215 const OverloadCandidate& Cand2,
4216 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004217 // Define viable functions to be better candidates than non-viable
4218 // functions.
4219 if (!Cand2.Viable)
4220 return Cand1.Viable;
4221 else if (!Cand1.Viable)
4222 return false;
4223
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004224 // C++ [over.match.best]p1:
4225 //
4226 // -- if F is a static member function, ICS1(F) is defined such
4227 // that ICS1(F) is neither better nor worse than ICS1(G) for
4228 // any function G, and, symmetrically, ICS1(G) is neither
4229 // better nor worse than ICS1(F).
4230 unsigned StartArg = 0;
4231 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4232 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004233
Douglas Gregord3cb3562009-07-07 23:38:56 +00004234 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004235 // A viable function F1 is defined to be a better function than another
4236 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004237 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004238 unsigned NumArgs = Cand1.Conversions.size();
4239 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4240 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004241 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004242 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4243 Cand2.Conversions[ArgIdx])) {
4244 case ImplicitConversionSequence::Better:
4245 // Cand1 has a better conversion sequence.
4246 HasBetterConversion = true;
4247 break;
4248
4249 case ImplicitConversionSequence::Worse:
4250 // Cand1 can't be better than Cand2.
4251 return false;
4252
4253 case ImplicitConversionSequence::Indistinguishable:
4254 // Do nothing.
4255 break;
4256 }
4257 }
4258
Mike Stump11289f42009-09-09 15:08:12 +00004259 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004260 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004261 if (HasBetterConversion)
4262 return true;
4263
Mike Stump11289f42009-09-09 15:08:12 +00004264 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004265 // specialization, or, if not that,
4266 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4267 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4268 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004269
4270 // -- F1 and F2 are function template specializations, and the function
4271 // template for F1 is more specialized than the template for F2
4272 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004273 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004274 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4275 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004276 if (FunctionTemplateDecl *BetterTemplate
4277 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4278 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004279 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004280 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4281 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004282 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004283
Douglas Gregora1f013e2008-11-07 22:36:19 +00004284 // -- the context is an initialization by user-defined conversion
4285 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4286 // from the return type of F1 to the destination type (i.e.,
4287 // the type of the entity being initialized) is a better
4288 // conversion sequence than the standard conversion sequence
4289 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004290 if (Cand1.Function && Cand2.Function &&
4291 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004292 isa<CXXConversionDecl>(Cand2.Function)) {
4293 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4294 Cand2.FinalConversion)) {
4295 case ImplicitConversionSequence::Better:
4296 // Cand1 has a better conversion sequence.
4297 return true;
4298
4299 case ImplicitConversionSequence::Worse:
4300 // Cand1 can't be better than Cand2.
4301 return false;
4302
4303 case ImplicitConversionSequence::Indistinguishable:
4304 // Do nothing
4305 break;
4306 }
4307 }
4308
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004309 return false;
4310}
4311
Mike Stump11289f42009-09-09 15:08:12 +00004312/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004313/// within an overload candidate set.
4314///
4315/// \param CandidateSet the set of candidate functions.
4316///
4317/// \param Loc the location of the function name (or operator symbol) for
4318/// which overload resolution occurs.
4319///
Mike Stump11289f42009-09-09 15:08:12 +00004320/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004321/// function, Best points to the candidate function found.
4322///
4323/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004324OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4325 SourceLocation Loc,
4326 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004327 // Find the best viable function.
4328 Best = CandidateSet.end();
4329 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4330 Cand != CandidateSet.end(); ++Cand) {
4331 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004332 if (Best == CandidateSet.end() ||
4333 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004334 Best = Cand;
4335 }
4336 }
4337
4338 // If we didn't find any viable functions, abort.
4339 if (Best == CandidateSet.end())
4340 return OR_No_Viable_Function;
4341
4342 // Make sure that this function is better than every other viable
4343 // function. If not, we have an ambiguity.
4344 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4345 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004346 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004347 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004348 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004349 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004350 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004351 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004352 }
Mike Stump11289f42009-09-09 15:08:12 +00004353
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004354 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004355 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004356 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004357 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004358 return OR_Deleted;
4359
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004360 // C++ [basic.def.odr]p2:
4361 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004362 // when referred to from a potentially-evaluated expression. [Note: this
4363 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004364 // (clause 13), user-defined conversions (12.3.2), allocation function for
4365 // placement new (5.3.4), as well as non-default initialization (8.5).
4366 if (Best->Function)
4367 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004368 return OR_Success;
4369}
4370
John McCall53262c92010-01-12 02:15:36 +00004371namespace {
4372
4373enum OverloadCandidateKind {
4374 oc_function,
4375 oc_method,
4376 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004377 oc_function_template,
4378 oc_method_template,
4379 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004380 oc_implicit_default_constructor,
4381 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004382 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004383};
4384
John McCalle1ac8d12010-01-13 00:25:19 +00004385OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4386 FunctionDecl *Fn,
4387 std::string &Description) {
4388 bool isTemplate = false;
4389
4390 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4391 isTemplate = true;
4392 Description = S.getTemplateArgumentBindingsText(
4393 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4394 }
John McCallfd0b2f82010-01-06 09:43:14 +00004395
4396 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004397 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004398 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004399
John McCall53262c92010-01-12 02:15:36 +00004400 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4401 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004402 }
4403
4404 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4405 // This actually gets spelled 'candidate function' for now, but
4406 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004407 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004408 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004409
4410 assert(Meth->isCopyAssignment()
4411 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004412 return oc_implicit_copy_assignment;
4413 }
4414
John McCalle1ac8d12010-01-13 00:25:19 +00004415 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004416}
4417
4418} // end anonymous namespace
4419
4420// Notes the location of an overload candidate.
4421void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004422 std::string FnDesc;
4423 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4424 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4425 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004426}
4427
John McCall0d1da222010-01-12 00:44:57 +00004428/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4429/// "lead" diagnostic; it will be given two arguments, the source and
4430/// target types of the conversion.
4431void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4432 SourceLocation CaretLoc,
4433 const PartialDiagnostic &PDiag) {
4434 Diag(CaretLoc, PDiag)
4435 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4436 for (AmbiguousConversionSequence::const_iterator
4437 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4438 NoteOverloadCandidate(*I);
4439 }
John McCall12f97bc2010-01-08 04:41:39 +00004440}
4441
John McCall0d1da222010-01-12 00:44:57 +00004442namespace {
4443
John McCall6a61b522010-01-13 09:16:55 +00004444void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4445 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4446 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004447 assert(Cand->Function && "for now, candidate must be a function");
4448 FunctionDecl *Fn = Cand->Function;
4449
4450 // There's a conversion slot for the object argument if this is a
4451 // non-constructor method. Note that 'I' corresponds the
4452 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004453 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004454 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004455 if (I == 0)
4456 isObjectArgument = true;
4457 else
4458 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004459 }
4460
John McCalle1ac8d12010-01-13 00:25:19 +00004461 std::string FnDesc;
4462 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4463
John McCall6a61b522010-01-13 09:16:55 +00004464 Expr *FromExpr = Conv.Bad.FromExpr;
4465 QualType FromTy = Conv.Bad.getFromType();
4466 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004467
John McCallfb7ad0f2010-02-02 02:42:52 +00004468 if (FromTy == S.Context.OverloadTy) {
4469 assert(FromExpr);
4470 Expr *E = FromExpr->IgnoreParens();
4471 if (isa<UnaryOperator>(E))
4472 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004473 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004474
4475 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4476 << (unsigned) FnKind << FnDesc
4477 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4478 << ToTy << Name << I+1;
4479 return;
4480 }
4481
John McCall6d174642010-01-23 08:10:49 +00004482 // Do some hand-waving analysis to see if the non-viability is due
4483 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004484 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4485 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4486 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4487 CToTy = RT->getPointeeType();
4488 else {
4489 // TODO: detect and diagnose the full richness of const mismatches.
4490 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4491 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4492 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4493 }
4494
4495 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4496 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4497 // It is dumb that we have to do this here.
4498 while (isa<ArrayType>(CFromTy))
4499 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4500 while (isa<ArrayType>(CToTy))
4501 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4502
4503 Qualifiers FromQs = CFromTy.getQualifiers();
4504 Qualifiers ToQs = CToTy.getQualifiers();
4505
4506 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4507 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4508 << (unsigned) FnKind << FnDesc
4509 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4510 << FromTy
4511 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4512 << (unsigned) isObjectArgument << I+1;
4513 return;
4514 }
4515
4516 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4517 assert(CVR && "unexpected qualifiers mismatch");
4518
4519 if (isObjectArgument) {
4520 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4521 << (unsigned) FnKind << FnDesc
4522 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4523 << FromTy << (CVR - 1);
4524 } else {
4525 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4526 << (unsigned) FnKind << FnDesc
4527 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4528 << FromTy << (CVR - 1) << I+1;
4529 }
4530 return;
4531 }
4532
John McCall6d174642010-01-23 08:10:49 +00004533 // Diagnose references or pointers to incomplete types differently,
4534 // since it's far from impossible that the incompleteness triggered
4535 // the failure.
4536 QualType TempFromTy = FromTy.getNonReferenceType();
4537 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4538 TempFromTy = PTy->getPointeeType();
4539 if (TempFromTy->isIncompleteType()) {
4540 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4541 << (unsigned) FnKind << FnDesc
4542 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4543 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4544 return;
4545 }
4546
John McCall47000992010-01-14 03:28:57 +00004547 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004548 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4549 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004550 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004551 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004552}
4553
4554void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4555 unsigned NumFormalArgs) {
4556 // TODO: treat calls to a missing default constructor as a special case
4557
4558 FunctionDecl *Fn = Cand->Function;
4559 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4560
4561 unsigned MinParams = Fn->getMinRequiredArguments();
4562
4563 // at least / at most / exactly
4564 unsigned mode, modeCount;
4565 if (NumFormalArgs < MinParams) {
4566 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4567 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4568 mode = 0; // "at least"
4569 else
4570 mode = 2; // "exactly"
4571 modeCount = MinParams;
4572 } else {
4573 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4574 if (MinParams != FnTy->getNumArgs())
4575 mode = 1; // "at most"
4576 else
4577 mode = 2; // "exactly"
4578 modeCount = FnTy->getNumArgs();
4579 }
4580
4581 std::string Description;
4582 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4583
4584 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4585 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004586}
4587
John McCall8b9ed552010-02-01 18:53:26 +00004588/// Diagnose a failed template-argument deduction.
4589void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4590 Expr **Args, unsigned NumArgs) {
4591 FunctionDecl *Fn = Cand->Function; // pattern
4592
4593 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4594 Cand->DeductionFailure.TemplateParameter);
4595
4596 switch (Cand->DeductionFailure.Result) {
4597 case Sema::TDK_Success:
4598 llvm_unreachable("TDK_success while diagnosing bad deduction");
4599
4600 case Sema::TDK_Incomplete: {
4601 NamedDecl *ParamD;
4602 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4603 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4604 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4605 assert(ParamD && "no parameter found for incomplete deduction result");
4606 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4607 << ParamD->getDeclName();
4608 return;
4609 }
4610
4611 // TODO: diagnose these individually, then kill off
4612 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4613 case Sema::TDK_InstantiationDepth:
4614 case Sema::TDK_Inconsistent:
4615 case Sema::TDK_InconsistentQuals:
4616 case Sema::TDK_SubstitutionFailure:
4617 case Sema::TDK_NonDeducedMismatch:
4618 case Sema::TDK_TooManyArguments:
4619 case Sema::TDK_TooFewArguments:
4620 case Sema::TDK_InvalidExplicitArguments:
4621 case Sema::TDK_FailedOverloadResolution:
4622 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4623 return;
4624 }
4625}
4626
4627/// Generates a 'note' diagnostic for an overload candidate. We've
4628/// already generated a primary error at the call site.
4629///
4630/// It really does need to be a single diagnostic with its caret
4631/// pointed at the candidate declaration. Yes, this creates some
4632/// major challenges of technical writing. Yes, this makes pointing
4633/// out problems with specific arguments quite awkward. It's still
4634/// better than generating twenty screens of text for every failed
4635/// overload.
4636///
4637/// It would be great to be able to express per-candidate problems
4638/// more richly for those diagnostic clients that cared, but we'd
4639/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00004640void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4641 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004642 FunctionDecl *Fn = Cand->Function;
4643
John McCall12f97bc2010-01-08 04:41:39 +00004644 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004645 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004646 std::string FnDesc;
4647 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004648
4649 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004650 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004651 return;
John McCall12f97bc2010-01-08 04:41:39 +00004652 }
4653
John McCalle1ac8d12010-01-13 00:25:19 +00004654 // We don't really have anything else to say about viable candidates.
4655 if (Cand->Viable) {
4656 S.NoteOverloadCandidate(Fn);
4657 return;
4658 }
John McCall0d1da222010-01-12 00:44:57 +00004659
John McCall6a61b522010-01-13 09:16:55 +00004660 switch (Cand->FailureKind) {
4661 case ovl_fail_too_many_arguments:
4662 case ovl_fail_too_few_arguments:
4663 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004664
John McCall6a61b522010-01-13 09:16:55 +00004665 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00004666 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4667
John McCallfe796dd2010-01-23 05:17:32 +00004668 case ovl_fail_trivial_conversion:
4669 case ovl_fail_bad_final_conversion:
John McCall6a61b522010-01-13 09:16:55 +00004670 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004671
John McCall6a61b522010-01-13 09:16:55 +00004672 case ovl_fail_bad_conversion:
4673 for (unsigned I = 0, N = Cand->Conversions.size(); I != N; ++I)
4674 if (Cand->Conversions[I].isBad())
4675 return DiagnoseBadConversion(S, Cand, I);
4676
4677 // FIXME: this currently happens when we're called from SemaInit
4678 // when user-conversion overload fails. Figure out how to handle
4679 // those conditions and diagnose them well.
4680 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004681 }
John McCalld3224162010-01-08 00:58:21 +00004682}
4683
4684void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4685 // Desugar the type of the surrogate down to a function type,
4686 // retaining as many typedefs as possible while still showing
4687 // the function type (and, therefore, its parameter types).
4688 QualType FnType = Cand->Surrogate->getConversionType();
4689 bool isLValueReference = false;
4690 bool isRValueReference = false;
4691 bool isPointer = false;
4692 if (const LValueReferenceType *FnTypeRef =
4693 FnType->getAs<LValueReferenceType>()) {
4694 FnType = FnTypeRef->getPointeeType();
4695 isLValueReference = true;
4696 } else if (const RValueReferenceType *FnTypeRef =
4697 FnType->getAs<RValueReferenceType>()) {
4698 FnType = FnTypeRef->getPointeeType();
4699 isRValueReference = true;
4700 }
4701 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4702 FnType = FnTypePtr->getPointeeType();
4703 isPointer = true;
4704 }
4705 // Desugar down to a function type.
4706 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4707 // Reconstruct the pointer/reference as appropriate.
4708 if (isPointer) FnType = S.Context.getPointerType(FnType);
4709 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4710 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4711
4712 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4713 << FnType;
4714}
4715
4716void NoteBuiltinOperatorCandidate(Sema &S,
4717 const char *Opc,
4718 SourceLocation OpLoc,
4719 OverloadCandidate *Cand) {
4720 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4721 std::string TypeStr("operator");
4722 TypeStr += Opc;
4723 TypeStr += "(";
4724 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4725 if (Cand->Conversions.size() == 1) {
4726 TypeStr += ")";
4727 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4728 } else {
4729 TypeStr += ", ";
4730 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4731 TypeStr += ")";
4732 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4733 }
4734}
4735
4736void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4737 OverloadCandidate *Cand) {
4738 unsigned NoOperands = Cand->Conversions.size();
4739 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4740 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00004741 if (ICS.isBad()) break; // all meaningless after first invalid
4742 if (!ICS.isAmbiguous()) continue;
4743
4744 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4745 PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00004746 }
4747}
4748
John McCall3712d9e2010-01-15 23:32:50 +00004749SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4750 if (Cand->Function)
4751 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00004752 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00004753 return Cand->Surrogate->getLocation();
4754 return SourceLocation();
4755}
4756
John McCallad2587a2010-01-12 00:48:53 +00004757struct CompareOverloadCandidatesForDisplay {
4758 Sema &S;
4759 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00004760
4761 bool operator()(const OverloadCandidate *L,
4762 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00004763 // Fast-path this check.
4764 if (L == R) return false;
4765
John McCall12f97bc2010-01-08 04:41:39 +00004766 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00004767 if (L->Viable) {
4768 if (!R->Viable) return true;
4769
4770 // TODO: introduce a tri-valued comparison for overload
4771 // candidates. Would be more worthwhile if we had a sort
4772 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00004773 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
4774 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00004775 } else if (R->Viable)
4776 return false;
John McCall12f97bc2010-01-08 04:41:39 +00004777
John McCall3712d9e2010-01-15 23:32:50 +00004778 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00004779
John McCall3712d9e2010-01-15 23:32:50 +00004780 // Criteria by which we can sort non-viable candidates:
4781 if (!L->Viable) {
4782 // 1. Arity mismatches come after other candidates.
4783 if (L->FailureKind == ovl_fail_too_many_arguments ||
4784 L->FailureKind == ovl_fail_too_few_arguments)
4785 return false;
4786 if (R->FailureKind == ovl_fail_too_many_arguments ||
4787 R->FailureKind == ovl_fail_too_few_arguments)
4788 return true;
John McCall12f97bc2010-01-08 04:41:39 +00004789
John McCallfe796dd2010-01-23 05:17:32 +00004790 // 2. Bad conversions come first and are ordered by the number
4791 // of bad conversions and quality of good conversions.
4792 if (L->FailureKind == ovl_fail_bad_conversion) {
4793 if (R->FailureKind != ovl_fail_bad_conversion)
4794 return true;
4795
4796 // If there's any ordering between the defined conversions...
4797 // FIXME: this might not be transitive.
4798 assert(L->Conversions.size() == R->Conversions.size());
4799
4800 int leftBetter = 0;
4801 for (unsigned I = 0, E = L->Conversions.size(); I != E; ++I) {
4802 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
4803 R->Conversions[I])) {
4804 case ImplicitConversionSequence::Better:
4805 leftBetter++;
4806 break;
4807
4808 case ImplicitConversionSequence::Worse:
4809 leftBetter--;
4810 break;
4811
4812 case ImplicitConversionSequence::Indistinguishable:
4813 break;
4814 }
4815 }
4816 if (leftBetter > 0) return true;
4817 if (leftBetter < 0) return false;
4818
4819 } else if (R->FailureKind == ovl_fail_bad_conversion)
4820 return false;
4821
John McCall3712d9e2010-01-15 23:32:50 +00004822 // TODO: others?
4823 }
4824
4825 // Sort everything else by location.
4826 SourceLocation LLoc = GetLocationForCandidate(L);
4827 SourceLocation RLoc = GetLocationForCandidate(R);
4828
4829 // Put candidates without locations (e.g. builtins) at the end.
4830 if (LLoc.isInvalid()) return false;
4831 if (RLoc.isInvalid()) return true;
4832
4833 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00004834 }
4835};
4836
John McCallfe796dd2010-01-23 05:17:32 +00004837/// CompleteNonViableCandidate - Normally, overload resolution only
4838/// computes up to the first
4839void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
4840 Expr **Args, unsigned NumArgs) {
4841 assert(!Cand->Viable);
4842
4843 // Don't do anything on failures other than bad conversion.
4844 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
4845
4846 // Skip forward to the first bad conversion.
4847 unsigned ConvIdx = 0;
4848 unsigned ConvCount = Cand->Conversions.size();
4849 while (true) {
4850 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
4851 ConvIdx++;
4852 if (Cand->Conversions[ConvIdx - 1].isBad())
4853 break;
4854 }
4855
4856 if (ConvIdx == ConvCount)
4857 return;
4858
4859 // FIXME: these should probably be preserved from the overload
4860 // operation somehow.
4861 bool SuppressUserConversions = false;
4862 bool ForceRValue = false;
4863
4864 const FunctionProtoType* Proto;
4865 unsigned ArgIdx = ConvIdx;
4866
4867 if (Cand->IsSurrogate) {
4868 QualType ConvType
4869 = Cand->Surrogate->getConversionType().getNonReferenceType();
4870 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4871 ConvType = ConvPtrType->getPointeeType();
4872 Proto = ConvType->getAs<FunctionProtoType>();
4873 ArgIdx--;
4874 } else if (Cand->Function) {
4875 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
4876 if (isa<CXXMethodDecl>(Cand->Function) &&
4877 !isa<CXXConstructorDecl>(Cand->Function))
4878 ArgIdx--;
4879 } else {
4880 // Builtin binary operator with a bad first conversion.
4881 assert(ConvCount <= 3);
4882 for (; ConvIdx != ConvCount; ++ConvIdx)
4883 Cand->Conversions[ConvIdx]
4884 = S.TryCopyInitialization(Args[ConvIdx],
4885 Cand->BuiltinTypes.ParamTypes[ConvIdx],
4886 SuppressUserConversions, ForceRValue,
4887 /*InOverloadResolution*/ true);
4888 return;
4889 }
4890
4891 // Fill in the rest of the conversions.
4892 unsigned NumArgsInProto = Proto->getNumArgs();
4893 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
4894 if (ArgIdx < NumArgsInProto)
4895 Cand->Conversions[ConvIdx]
4896 = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx),
4897 SuppressUserConversions, ForceRValue,
4898 /*InOverloadResolution=*/true);
4899 else
4900 Cand->Conversions[ConvIdx].setEllipsis();
4901 }
4902}
4903
John McCalld3224162010-01-08 00:58:21 +00004904} // end anonymous namespace
4905
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004906/// PrintOverloadCandidates - When overload resolution fails, prints
4907/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00004908/// set.
Mike Stump11289f42009-09-09 15:08:12 +00004909void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004910Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00004911 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00004912 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004913 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004914 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00004915 // Sort the candidates by viability and position. Sorting directly would
4916 // be prohibitive, so we make a set of pointers and sort those.
4917 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4918 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4919 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4920 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00004921 Cand != LastCand; ++Cand) {
4922 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00004923 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00004924 else if (OCD == OCD_AllCandidates) {
4925 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
4926 Cands.push_back(Cand);
4927 }
4928 }
4929
John McCallad2587a2010-01-12 00:48:53 +00004930 std::sort(Cands.begin(), Cands.end(),
4931 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00004932
John McCall0d1da222010-01-12 00:44:57 +00004933 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00004934
John McCall12f97bc2010-01-08 04:41:39 +00004935 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4936 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4937 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004938
John McCalld3224162010-01-08 00:58:21 +00004939 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00004940 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00004941 else if (Cand->IsSurrogate)
4942 NoteSurrogateCandidate(*this, Cand);
4943
4944 // This a builtin candidate. We do not, in general, want to list
4945 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00004946 else if (Cand->Viable) {
4947 // Generally we only see ambiguities including viable builtin
4948 // operators if overload resolution got screwed up by an
4949 // ambiguous user-defined conversion.
4950 //
4951 // FIXME: It's quite possible for different conversions to see
4952 // different ambiguities, though.
4953 if (!ReportedAmbiguousConversions) {
4954 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4955 ReportedAmbiguousConversions = true;
4956 }
John McCalld3224162010-01-08 00:58:21 +00004957
John McCall0d1da222010-01-12 00:44:57 +00004958 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00004959 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00004960 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004961 }
4962}
4963
John McCall1acbbb52010-02-02 06:20:04 +00004964static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, NamedDecl *D,
John McCall58cc69d2010-01-27 01:50:18 +00004965 AccessSpecifier AS) {
4966 if (isa<UnresolvedLookupExpr>(E))
4967 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D, AS);
4968
4969 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D, AS);
4970}
4971
Douglas Gregorcd695e52008-11-10 20:40:00 +00004972/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4973/// an overloaded function (C++ [over.over]), where @p From is an
4974/// expression with overloaded function type and @p ToType is the type
4975/// we're trying to resolve to. For example:
4976///
4977/// @code
4978/// int f(double);
4979/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004980///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004981/// int (*pfd)(double) = f; // selects f(double)
4982/// @endcode
4983///
4984/// This routine returns the resulting FunctionDecl if it could be
4985/// resolved, and NULL otherwise. When @p Complain is true, this
4986/// routine will emit diagnostics if there is an error.
4987FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004988Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004989 bool Complain) {
4990 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004991 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004992 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004993 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004994 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004995 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004996 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004997 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004998 FunctionType = MemTypePtr->getPointeeType();
4999 IsMember = true;
5000 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005001
5002 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00005003 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00005004 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005005 return 0;
5006
5007 // Find the actual overloaded function declaration.
John McCall1acbbb52010-02-02 06:20:04 +00005008 if (From->getType() != Context.OverloadTy)
5009 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005010
Douglas Gregorcd695e52008-11-10 20:40:00 +00005011 // C++ [over.over]p1:
5012 // [...] [Note: any redundant set of parentheses surrounding the
5013 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005014 // C++ [over.over]p1:
5015 // [...] The overloaded function name can be preceded by the &
5016 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005017 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5018 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5019 if (OvlExpr->hasExplicitTemplateArgs()) {
5020 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5021 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005022 }
5023
Douglas Gregorcd695e52008-11-10 20:40:00 +00005024 // Look through all of the overloaded functions, searching for one
5025 // whose type matches exactly.
John McCall58cc69d2010-01-27 01:50:18 +00005026 UnresolvedSet<4> Matches; // contains only FunctionDecls
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005027 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005028 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5029 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005030 // Look through any using declarations to find the underlying function.
5031 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5032
Douglas Gregorcd695e52008-11-10 20:40:00 +00005033 // C++ [over.over]p3:
5034 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005035 // targets of type "pointer-to-function" or "reference-to-function."
5036 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005037 // type "pointer-to-member-function."
5038 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005039
Mike Stump11289f42009-09-09 15:08:12 +00005040 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005041 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005042 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005043 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005044 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005045 // static when converting to member pointer.
5046 if (Method->isStatic() == IsMember)
5047 continue;
5048 } else if (IsMember)
5049 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005050
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005051 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005052 // If the name is a function template, template argument deduction is
5053 // done (14.8.2.2), and if the argument deduction succeeds, the
5054 // resulting template argument list is used to generate a single
5055 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005056 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005057 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005058 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005059 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005060 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005061 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005062 FunctionType, Specialization, Info)) {
5063 // FIXME: make a note of the failed deduction for diagnostics.
5064 (void)Result;
5065 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005066 // FIXME: If the match isn't exact, shouldn't we just drop this as
5067 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005068 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005069 == Context.getCanonicalType(Specialization->getType()));
John McCall58cc69d2010-01-27 01:50:18 +00005070 Matches.addDecl(cast<FunctionDecl>(Specialization->getCanonicalDecl()),
5071 I.getAccess());
Douglas Gregor9b146582009-07-08 20:55:45 +00005072 }
John McCalld14a8642009-11-21 08:51:07 +00005073
5074 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005075 }
Mike Stump11289f42009-09-09 15:08:12 +00005076
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005077 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005078 // Skip non-static functions when converting to pointer, and static
5079 // when converting to member pointer.
5080 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005081 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005082
5083 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005084 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005085 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005086 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005087 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005088
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005089 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005090 QualType ResultTy;
5091 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5092 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5093 ResultTy)) {
John McCall58cc69d2010-01-27 01:50:18 +00005094 Matches.addDecl(cast<FunctionDecl>(FunDecl->getCanonicalDecl()),
5095 I.getAccess());
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005096 FoundNonTemplateFunction = true;
5097 }
Mike Stump11289f42009-09-09 15:08:12 +00005098 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005099 }
5100
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005101 // If there were 0 or 1 matches, we're done.
5102 if (Matches.empty())
5103 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005104 else if (Matches.size() == 1) {
John McCall58cc69d2010-01-27 01:50:18 +00005105 FunctionDecl *Result = cast<FunctionDecl>(*Matches.begin());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005106 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005107 if (Complain)
5108 CheckUnresolvedAccess(*this, OvlExpr, Result, Matches.begin().getAccess());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005109 return Result;
5110 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005111
5112 // C++ [over.over]p4:
5113 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005114 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005115 // [...] and any given function template specialization F1 is
5116 // eliminated if the set contains a second function template
5117 // specialization whose function template is more specialized
5118 // than the function template of F1 according to the partial
5119 // ordering rules of 14.5.5.2.
5120
5121 // The algorithm specified above is quadratic. We instead use a
5122 // two-pass algorithm (similar to the one used to identify the
5123 // best viable function in an overload set) that identifies the
5124 // best function template (if it exists).
John McCall58cc69d2010-01-27 01:50:18 +00005125
5126 UnresolvedSetIterator Result =
5127 getMostSpecialized(Matches.begin(), Matches.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005128 TPOC_Other, From->getLocStart(),
5129 PDiag(),
5130 PDiag(diag::err_addr_ovl_ambiguous)
John McCall58cc69d2010-01-27 01:50:18 +00005131 << Matches[0]->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005132 PDiag(diag::note_ovl_candidate)
5133 << (unsigned) oc_function_template);
John McCall58cc69d2010-01-27 01:50:18 +00005134 assert(Result != Matches.end() && "no most-specialized template");
5135 MarkDeclarationReferenced(From->getLocStart(), *Result);
5136 if (Complain)
5137 CheckUnresolvedAccess(*this, OvlExpr, *Result, Result.getAccess());
5138 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005139 }
Mike Stump11289f42009-09-09 15:08:12 +00005140
Douglas Gregorfae1d712009-09-26 03:56:17 +00005141 // [...] any function template specializations in the set are
5142 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005143 for (unsigned I = 0, N = Matches.size(); I != N; ) {
5144 if (cast<FunctionDecl>(Matches[I].getDecl())->getPrimaryTemplate() == 0)
5145 ++I;
5146 else {
5147 Matches.erase(I);
5148 --N;
5149 }
5150 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005151
Mike Stump11289f42009-09-09 15:08:12 +00005152 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005153 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005154 if (Matches.size() == 1) {
5155 UnresolvedSetIterator Match = Matches.begin();
5156 MarkDeclarationReferenced(From->getLocStart(), *Match);
5157 if (Complain)
5158 CheckUnresolvedAccess(*this, OvlExpr, *Match, Match.getAccess());
5159 return cast<FunctionDecl>(*Match);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005160 }
Mike Stump11289f42009-09-09 15:08:12 +00005161
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005162 // FIXME: We should probably return the same thing that BestViableFunction
5163 // returns (even if we issue the diagnostics here).
5164 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall58cc69d2010-01-27 01:50:18 +00005165 << Matches[0]->getDeclName();
5166 for (UnresolvedSetIterator I = Matches.begin(),
5167 E = Matches.end(); I != E; ++I)
5168 NoteOverloadCandidate(cast<FunctionDecl>(*I));
Douglas Gregorcd695e52008-11-10 20:40:00 +00005169 return 0;
5170}
5171
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005172/// \brief Given an expression that refers to an overloaded function, try to
5173/// resolve that overloaded function expression down to a single function.
5174///
5175/// This routine can only resolve template-ids that refer to a single function
5176/// template, where that template-id refers to a single template whose template
5177/// arguments are either provided by the template-id or have defaults,
5178/// as described in C++0x [temp.arg.explicit]p3.
5179FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5180 // C++ [over.over]p1:
5181 // [...] [Note: any redundant set of parentheses surrounding the
5182 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005183 // C++ [over.over]p1:
5184 // [...] The overloaded function name can be preceded by the &
5185 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005186
5187 if (From->getType() != Context.OverloadTy)
5188 return 0;
5189
5190 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005191
5192 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005193 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005194 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005195
5196 TemplateArgumentListInfo ExplicitTemplateArgs;
5197 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005198
5199 // Look through all of the overloaded functions, searching for one
5200 // whose type matches exactly.
5201 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005202 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5203 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005204 // C++0x [temp.arg.explicit]p3:
5205 // [...] In contexts where deduction is done and fails, or in contexts
5206 // where deduction is not done, if a template argument list is
5207 // specified and it, along with any default template arguments,
5208 // identifies a single function template specialization, then the
5209 // template-id is an lvalue for the function template specialization.
5210 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5211
5212 // C++ [over.over]p2:
5213 // If the name is a function template, template argument deduction is
5214 // done (14.8.2.2), and if the argument deduction succeeds, the
5215 // resulting template argument list is used to generate a single
5216 // function template specialization, which is added to the set of
5217 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005218 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005219 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005220 if (TemplateDeductionResult Result
5221 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5222 Specialization, Info)) {
5223 // FIXME: make a note of the failed deduction for diagnostics.
5224 (void)Result;
5225 continue;
5226 }
5227
5228 // Multiple matches; we can't resolve to a single declaration.
5229 if (Matched)
5230 return 0;
5231
5232 Matched = Specialization;
5233 }
5234
5235 return Matched;
5236}
5237
Douglas Gregorcabea402009-09-22 15:41:20 +00005238/// \brief Add a single candidate to the overload set.
5239static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00005240 NamedDecl *Callee,
John McCallb89836b2010-01-26 01:37:31 +00005241 AccessSpecifier Access,
John McCall6b51f282009-11-23 01:53:49 +00005242 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005243 Expr **Args, unsigned NumArgs,
5244 OverloadCandidateSet &CandidateSet,
5245 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005246 if (isa<UsingShadowDecl>(Callee))
5247 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5248
Douglas Gregorcabea402009-09-22 15:41:20 +00005249 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005250 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCallb89836b2010-01-26 01:37:31 +00005251 S.AddOverloadCandidate(Func, Access, Args, NumArgs, CandidateSet,
5252 false, false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005253 return;
John McCalld14a8642009-11-21 08:51:07 +00005254 }
5255
5256 if (FunctionTemplateDecl *FuncTemplate
5257 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCallb89836b2010-01-26 01:37:31 +00005258 S.AddTemplateOverloadCandidate(FuncTemplate, Access, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005259 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005260 return;
5261 }
5262
5263 assert(false && "unhandled case in overloaded call candidate");
5264
5265 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005266}
5267
5268/// \brief Add the overload candidates named by callee and/or found by argument
5269/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005270void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005271 Expr **Args, unsigned NumArgs,
5272 OverloadCandidateSet &CandidateSet,
5273 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005274
5275#ifndef NDEBUG
5276 // Verify that ArgumentDependentLookup is consistent with the rules
5277 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005278 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005279 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5280 // and let Y be the lookup set produced by argument dependent
5281 // lookup (defined as follows). If X contains
5282 //
5283 // -- a declaration of a class member, or
5284 //
5285 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005286 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005287 //
5288 // -- a declaration that is neither a function or a function
5289 // template
5290 //
5291 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005292
John McCall57500772009-12-16 12:17:52 +00005293 if (ULE->requiresADL()) {
5294 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5295 E = ULE->decls_end(); I != E; ++I) {
5296 assert(!(*I)->getDeclContext()->isRecord());
5297 assert(isa<UsingShadowDecl>(*I) ||
5298 !(*I)->getDeclContext()->isFunctionOrMethod());
5299 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005300 }
5301 }
5302#endif
5303
John McCall57500772009-12-16 12:17:52 +00005304 // It would be nice to avoid this copy.
5305 TemplateArgumentListInfo TABuffer;
5306 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5307 if (ULE->hasExplicitTemplateArgs()) {
5308 ULE->copyTemplateArgumentsInto(TABuffer);
5309 ExplicitTemplateArgs = &TABuffer;
5310 }
5311
5312 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5313 E = ULE->decls_end(); I != E; ++I)
John McCallb89836b2010-01-26 01:37:31 +00005314 AddOverloadedCallCandidate(*this, *I, I.getAccess(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005315 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005316 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005317
John McCall57500772009-12-16 12:17:52 +00005318 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005319 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5320 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005321 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005322 CandidateSet,
5323 PartialOverloading);
5324}
John McCalld681c392009-12-16 08:11:27 +00005325
John McCall57500772009-12-16 12:17:52 +00005326static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5327 Expr **Args, unsigned NumArgs) {
5328 Fn->Destroy(SemaRef.Context);
5329 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5330 Args[Arg]->Destroy(SemaRef.Context);
5331 return SemaRef.ExprError();
5332}
5333
John McCalld681c392009-12-16 08:11:27 +00005334/// Attempts to recover from a call where no functions were found.
5335///
5336/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005337static Sema::OwningExprResult
5338BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5339 UnresolvedLookupExpr *ULE,
5340 SourceLocation LParenLoc,
5341 Expr **Args, unsigned NumArgs,
5342 SourceLocation *CommaLocs,
5343 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005344
5345 CXXScopeSpec SS;
5346 if (ULE->getQualifier()) {
5347 SS.setScopeRep(ULE->getQualifier());
5348 SS.setRange(ULE->getQualifierRange());
5349 }
5350
John McCall57500772009-12-16 12:17:52 +00005351 TemplateArgumentListInfo TABuffer;
5352 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5353 if (ULE->hasExplicitTemplateArgs()) {
5354 ULE->copyTemplateArgumentsInto(TABuffer);
5355 ExplicitTemplateArgs = &TABuffer;
5356 }
5357
John McCalld681c392009-12-16 08:11:27 +00005358 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5359 Sema::LookupOrdinaryName);
Douglas Gregor598b08f2009-12-31 05:20:13 +00005360 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall57500772009-12-16 12:17:52 +00005361 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005362
John McCall57500772009-12-16 12:17:52 +00005363 assert(!R.empty() && "lookup results empty despite recovery");
5364
5365 // Build an implicit member call if appropriate. Just drop the
5366 // casts and such from the call, we don't really care.
5367 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5368 if ((*R.begin())->isCXXClassMember())
5369 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5370 else if (ExplicitTemplateArgs)
5371 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5372 else
5373 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5374
5375 if (NewFn.isInvalid())
5376 return Destroy(SemaRef, Fn, Args, NumArgs);
5377
5378 Fn->Destroy(SemaRef.Context);
5379
5380 // This shouldn't cause an infinite loop because we're giving it
5381 // an expression with non-empty lookup results, which should never
5382 // end up here.
5383 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5384 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5385 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005386}
Douglas Gregorcabea402009-09-22 15:41:20 +00005387
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005388/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005389/// (which eventually refers to the declaration Func) and the call
5390/// arguments Args/NumArgs, attempt to resolve the function call down
5391/// to a specific function. If overload resolution succeeds, returns
5392/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005393/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005394/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005395Sema::OwningExprResult
5396Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5397 SourceLocation LParenLoc,
5398 Expr **Args, unsigned NumArgs,
5399 SourceLocation *CommaLocs,
5400 SourceLocation RParenLoc) {
5401#ifndef NDEBUG
5402 if (ULE->requiresADL()) {
5403 // To do ADL, we must have found an unqualified name.
5404 assert(!ULE->getQualifier() && "qualified name with ADL");
5405
5406 // We don't perform ADL for implicit declarations of builtins.
5407 // Verify that this was correctly set up.
5408 FunctionDecl *F;
5409 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5410 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5411 F->getBuiltinID() && F->isImplicit())
5412 assert(0 && "performing ADL for builtin");
5413
5414 // We don't perform ADL in C.
5415 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5416 }
5417#endif
5418
John McCallbc077cf2010-02-08 23:07:23 +00005419 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005420
John McCall57500772009-12-16 12:17:52 +00005421 // Add the functions denoted by the callee to the set of candidate
5422 // functions, including those from argument-dependent lookup.
5423 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005424
5425 // If we found nothing, try to recover.
5426 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5427 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005428 if (CandidateSet.empty())
5429 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5430 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005431
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005432 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005433 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005434 case OR_Success: {
5435 FunctionDecl *FDecl = Best->Function;
John McCall58cc69d2010-01-27 01:50:18 +00005436 CheckUnresolvedLookupAccess(ULE, FDecl, Best->getAccess());
John McCall57500772009-12-16 12:17:52 +00005437 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5438 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5439 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005440
5441 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005442 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005443 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005444 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005445 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005446 break;
5447
5448 case OR_Ambiguous:
5449 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005450 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005451 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005452 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005453
5454 case OR_Deleted:
5455 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5456 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005457 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005458 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005459 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005460 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005461 }
5462
5463 // Overload resolution failed. Destroy all of the subexpressions and
5464 // return NULL.
5465 Fn->Destroy(Context);
5466 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5467 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005468 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005469}
5470
John McCall4c4c1df2010-01-26 03:27:55 +00005471static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00005472 return Functions.size() > 1 ||
5473 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5474}
5475
Douglas Gregor084d8552009-03-13 23:49:33 +00005476/// \brief Create a unary operation that may resolve to an overloaded
5477/// operator.
5478///
5479/// \param OpLoc The location of the operator itself (e.g., '*').
5480///
5481/// \param OpcIn The UnaryOperator::Opcode that describes this
5482/// operator.
5483///
5484/// \param Functions The set of non-member functions that will be
5485/// considered by overload resolution. The caller needs to build this
5486/// set based on the context using, e.g.,
5487/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5488/// set should not contain any member functions; those will be added
5489/// by CreateOverloadedUnaryOp().
5490///
5491/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00005492Sema::OwningExprResult
5493Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5494 const UnresolvedSetImpl &Fns,
5495 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005496 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5497 Expr *Input = (Expr *)input.get();
5498
5499 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5500 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5501 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5502
5503 Expr *Args[2] = { Input, 0 };
5504 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005505
Douglas Gregor084d8552009-03-13 23:49:33 +00005506 // For post-increment and post-decrement, add the implicit '0' as
5507 // the second argument, so that we know this is a post-increment or
5508 // post-decrement.
5509 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5510 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005511 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005512 SourceLocation());
5513 NumArgs = 2;
5514 }
5515
5516 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00005517 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005518 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005519 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005520 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005521 /*ADL*/ true, IsOverloaded(Fns));
5522 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00005523
Douglas Gregor084d8552009-03-13 23:49:33 +00005524 input.release();
5525 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5526 &Args[0], NumArgs,
5527 Context.DependentTy,
5528 OpLoc));
5529 }
5530
5531 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005532 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005533
5534 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005535 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00005536
5537 // Add operator candidates that are member functions.
5538 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5539
John McCall4c4c1df2010-01-26 03:27:55 +00005540 // Add candidates from ADL.
5541 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00005542 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00005543 /*ExplicitTemplateArgs*/ 0,
5544 CandidateSet);
5545
Douglas Gregor084d8552009-03-13 23:49:33 +00005546 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005547 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005548
5549 // Perform overload resolution.
5550 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005551 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005552 case OR_Success: {
5553 // We found a built-in operator or an overloaded operator.
5554 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005555
Douglas Gregor084d8552009-03-13 23:49:33 +00005556 if (FnDecl) {
5557 // We matched an overloaded operator. Build a call to that
5558 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005559
Douglas Gregor084d8552009-03-13 23:49:33 +00005560 // Convert the arguments.
5561 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00005562 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5563
Douglas Gregor084d8552009-03-13 23:49:33 +00005564 if (PerformObjectArgumentInitialization(Input, Method))
5565 return ExprError();
5566 } else {
5567 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005568 OwningExprResult InputInit
5569 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005570 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005571 SourceLocation(),
5572 move(input));
5573 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005574 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005575
Douglas Gregore6600372009-12-23 17:40:29 +00005576 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005577 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005578 }
5579
5580 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005581 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005582
Douglas Gregor084d8552009-03-13 23:49:33 +00005583 // Build the actual expression node.
5584 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5585 SourceLocation());
5586 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005587
Douglas Gregor084d8552009-03-13 23:49:33 +00005588 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005589 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005590 ExprOwningPtr<CallExpr> TheCall(this,
5591 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005592 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005593
5594 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5595 FnDecl))
5596 return ExprError();
5597
5598 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005599 } else {
5600 // We matched a built-in operator. Convert the arguments, then
5601 // break out so that we will build the appropriate built-in
5602 // operator node.
5603 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005604 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005605 return ExprError();
5606
5607 break;
5608 }
5609 }
5610
5611 case OR_No_Viable_Function:
5612 // No viable function; fall through to handling this as a
5613 // built-in operator, which will produce an error message for us.
5614 break;
5615
5616 case OR_Ambiguous:
5617 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5618 << UnaryOperator::getOpcodeStr(Opc)
5619 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005620 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005621 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005622 return ExprError();
5623
5624 case OR_Deleted:
5625 Diag(OpLoc, diag::err_ovl_deleted_oper)
5626 << Best->Function->isDeleted()
5627 << UnaryOperator::getOpcodeStr(Opc)
5628 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005629 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005630 return ExprError();
5631 }
5632
5633 // Either we found no viable overloaded operator or we matched a
5634 // built-in operator. In either case, fall through to trying to
5635 // build a built-in operation.
5636 input.release();
5637 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5638}
5639
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005640/// \brief Create a binary operation that may resolve to an overloaded
5641/// operator.
5642///
5643/// \param OpLoc The location of the operator itself (e.g., '+').
5644///
5645/// \param OpcIn The BinaryOperator::Opcode that describes this
5646/// operator.
5647///
5648/// \param Functions The set of non-member functions that will be
5649/// considered by overload resolution. The caller needs to build this
5650/// set based on the context using, e.g.,
5651/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5652/// set should not contain any member functions; those will be added
5653/// by CreateOverloadedBinOp().
5654///
5655/// \param LHS Left-hand argument.
5656/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005657Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005658Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005659 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00005660 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005661 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005662 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005663 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005664
5665 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5666 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5667 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5668
5669 // If either side is type-dependent, create an appropriate dependent
5670 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005671 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00005672 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005673 // If there are no functions to store, just build a dependent
5674 // BinaryOperator or CompoundAssignment.
5675 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5676 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5677 Context.DependentTy, OpLoc));
5678
5679 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5680 Context.DependentTy,
5681 Context.DependentTy,
5682 Context.DependentTy,
5683 OpLoc));
5684 }
John McCall4c4c1df2010-01-26 03:27:55 +00005685
5686 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00005687 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005688 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005689 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005690 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005691 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00005692
John McCall4c4c1df2010-01-26 03:27:55 +00005693 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005694 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00005695 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005696 Context.DependentTy,
5697 OpLoc));
5698 }
5699
5700 // If this is the .* operator, which is not overloadable, just
5701 // create a built-in binary operator.
5702 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00005703 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005704
Sebastian Redl6a96bf72009-11-18 23:10:33 +00005705 // If this is the assignment operator, we only perform overload resolution
5706 // if the left-hand side is a class or enumeration type. This is actually
5707 // a hack. The standard requires that we do overload resolution between the
5708 // various built-in candidates, but as DR507 points out, this can lead to
5709 // problems. So we do it this way, which pretty much follows what GCC does.
5710 // Note that we go the traditional code path for compound assignment forms.
5711 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00005712 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005713
Douglas Gregor084d8552009-03-13 23:49:33 +00005714 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005715 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005716
5717 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005718 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005719
5720 // Add operator candidates that are member functions.
5721 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5722
John McCall4c4c1df2010-01-26 03:27:55 +00005723 // Add candidates from ADL.
5724 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5725 Args, 2,
5726 /*ExplicitTemplateArgs*/ 0,
5727 CandidateSet);
5728
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005729 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005730 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005731
5732 // Perform overload resolution.
5733 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005734 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005735 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005736 // We found a built-in operator or an overloaded operator.
5737 FunctionDecl *FnDecl = Best->Function;
5738
5739 if (FnDecl) {
5740 // We matched an overloaded operator. Build a call to that
5741 // operator.
5742
5743 // Convert the arguments.
5744 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00005745 // Best->Access is only meaningful for class members.
5746 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5747
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005748 OwningExprResult Arg1
5749 = PerformCopyInitialization(
5750 InitializedEntity::InitializeParameter(
5751 FnDecl->getParamDecl(0)),
5752 SourceLocation(),
5753 Owned(Args[1]));
5754 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005755 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005756
5757 if (PerformObjectArgumentInitialization(Args[0], Method))
5758 return ExprError();
5759
5760 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005761 } else {
5762 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005763 OwningExprResult Arg0
5764 = PerformCopyInitialization(
5765 InitializedEntity::InitializeParameter(
5766 FnDecl->getParamDecl(0)),
5767 SourceLocation(),
5768 Owned(Args[0]));
5769 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005770 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005771
5772 OwningExprResult Arg1
5773 = PerformCopyInitialization(
5774 InitializedEntity::InitializeParameter(
5775 FnDecl->getParamDecl(1)),
5776 SourceLocation(),
5777 Owned(Args[1]));
5778 if (Arg1.isInvalid())
5779 return ExprError();
5780 Args[0] = LHS = Arg0.takeAs<Expr>();
5781 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005782 }
5783
5784 // Determine the result type
5785 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00005786 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005787 ResultTy = ResultTy.getNonReferenceType();
5788
5789 // Build the actual expression node.
5790 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00005791 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005792 UsualUnaryConversions(FnExpr);
5793
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005794 ExprOwningPtr<CXXOperatorCallExpr>
5795 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5796 Args, 2, ResultTy,
5797 OpLoc));
5798
5799 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5800 FnDecl))
5801 return ExprError();
5802
5803 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005804 } else {
5805 // We matched a built-in operator. Convert the arguments, then
5806 // break out so that we will build the appropriate built-in
5807 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00005808 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005809 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00005810 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005811 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005812 return ExprError();
5813
5814 break;
5815 }
5816 }
5817
Douglas Gregor66950a32009-09-30 21:46:01 +00005818 case OR_No_Viable_Function: {
5819 // C++ [over.match.oper]p9:
5820 // If the operator is the operator , [...] and there are no
5821 // viable functions, then the operator is assumed to be the
5822 // built-in operator and interpreted according to clause 5.
5823 if (Opc == BinaryOperator::Comma)
5824 break;
5825
Sebastian Redl027de2a2009-05-21 11:50:50 +00005826 // For class as left operand for assignment or compound assigment operator
5827 // do not fall through to handling in built-in, but report that no overloaded
5828 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005829 OwningExprResult Result = ExprError();
5830 if (Args[0]->getType()->isRecordType() &&
5831 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005832 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5833 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005834 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005835 } else {
5836 // No viable function; try to create a built-in operation, which will
5837 // produce an error. Then, show the non-viable candidates.
5838 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005839 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005840 assert(Result.isInvalid() &&
5841 "C++ binary operator overloading is missing candidates!");
5842 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00005843 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005844 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005845 return move(Result);
5846 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005847
5848 case OR_Ambiguous:
5849 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5850 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005851 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005852 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005853 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005854 return ExprError();
5855
5856 case OR_Deleted:
5857 Diag(OpLoc, diag::err_ovl_deleted_oper)
5858 << Best->Function->isDeleted()
5859 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005860 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005861 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005862 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00005863 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005864
Douglas Gregor66950a32009-09-30 21:46:01 +00005865 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005866 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005867}
5868
Sebastian Redladba46e2009-10-29 20:17:01 +00005869Action::OwningExprResult
5870Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5871 SourceLocation RLoc,
5872 ExprArg Base, ExprArg Idx) {
5873 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5874 static_cast<Expr*>(Idx.get()) };
5875 DeclarationName OpName =
5876 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5877
5878 // If either side is type-dependent, create an appropriate dependent
5879 // expression.
5880 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5881
John McCall58cc69d2010-01-27 01:50:18 +00005882 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005883 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005884 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005885 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005886 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005887 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005888
5889 Base.release();
5890 Idx.release();
5891 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5892 Args, 2,
5893 Context.DependentTy,
5894 RLoc));
5895 }
5896
5897 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005898 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005899
5900 // Subscript can only be overloaded as a member function.
5901
5902 // Add operator candidates that are member functions.
5903 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5904
5905 // Add builtin operator candidates.
5906 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5907
5908 // Perform overload resolution.
5909 OverloadCandidateSet::iterator Best;
5910 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5911 case OR_Success: {
5912 // We found a built-in operator or an overloaded operator.
5913 FunctionDecl *FnDecl = Best->Function;
5914
5915 if (FnDecl) {
5916 // We matched an overloaded operator. Build a call to that
5917 // operator.
5918
John McCallb3a44002010-01-28 01:42:12 +00005919 CheckMemberOperatorAccess(LLoc, Args[0], FnDecl, Best->getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005920
Sebastian Redladba46e2009-10-29 20:17:01 +00005921 // Convert the arguments.
5922 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Anders Carlssona68e51e2010-01-29 18:37:50 +00005923 if (PerformObjectArgumentInitialization(Args[0], Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00005924 return ExprError();
5925
Anders Carlssona68e51e2010-01-29 18:37:50 +00005926 // Convert the arguments.
5927 OwningExprResult InputInit
5928 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5929 FnDecl->getParamDecl(0)),
5930 SourceLocation(),
5931 Owned(Args[1]));
5932 if (InputInit.isInvalid())
5933 return ExprError();
5934
5935 Args[1] = InputInit.takeAs<Expr>();
5936
Sebastian Redladba46e2009-10-29 20:17:01 +00005937 // Determine the result type
5938 QualType ResultTy
5939 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5940 ResultTy = ResultTy.getNonReferenceType();
5941
5942 // Build the actual expression node.
5943 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5944 LLoc);
5945 UsualUnaryConversions(FnExpr);
5946
5947 Base.release();
5948 Idx.release();
5949 ExprOwningPtr<CXXOperatorCallExpr>
5950 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5951 FnExpr, Args, 2,
5952 ResultTy, RLoc));
5953
5954 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5955 FnDecl))
5956 return ExprError();
5957
5958 return MaybeBindToTemporary(TheCall.release());
5959 } else {
5960 // We matched a built-in operator. Convert the arguments, then
5961 // break out so that we will build the appropriate built-in
5962 // operator node.
5963 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005964 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00005965 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005966 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005967 return ExprError();
5968
5969 break;
5970 }
5971 }
5972
5973 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00005974 if (CandidateSet.empty())
5975 Diag(LLoc, diag::err_ovl_no_oper)
5976 << Args[0]->getType() << /*subscript*/ 0
5977 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5978 else
5979 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5980 << Args[0]->getType()
5981 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005982 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00005983 "[]", LLoc);
5984 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00005985 }
5986
5987 case OR_Ambiguous:
5988 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5989 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005990 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00005991 "[]", LLoc);
5992 return ExprError();
5993
5994 case OR_Deleted:
5995 Diag(LLoc, diag::err_ovl_deleted_oper)
5996 << Best->Function->isDeleted() << "[]"
5997 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005998 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00005999 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006000 return ExprError();
6001 }
6002
6003 // We matched a built-in operator; build it.
6004 Base.release();
6005 Idx.release();
6006 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6007 Owned(Args[1]), RLoc);
6008}
6009
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006010/// BuildCallToMemberFunction - Build a call to a member
6011/// function. MemExpr is the expression that refers to the member
6012/// function (and includes the object parameter), Args/NumArgs are the
6013/// arguments to the function call (not including the object
6014/// parameter). The caller needs to validate that the member
6015/// expression refers to a member function or an overloaded member
6016/// function.
John McCall2d74de92009-12-01 22:10:20 +00006017Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006018Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6019 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006020 unsigned NumArgs, SourceLocation *CommaLocs,
6021 SourceLocation RParenLoc) {
6022 // Dig out the member expression. This holds both the object
6023 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006024 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6025
John McCall10eae182009-11-30 22:42:35 +00006026 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006027 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00006028 if (isa<MemberExpr>(NakedMemExpr)) {
6029 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006030 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
6031 } else {
6032 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCall2d74de92009-12-01 22:10:20 +00006033
John McCall6e9f8f62009-12-03 04:06:58 +00006034 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006035
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006036 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006037 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006038
John McCall2d74de92009-12-01 22:10:20 +00006039 // FIXME: avoid copy.
6040 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6041 if (UnresExpr->hasExplicitTemplateArgs()) {
6042 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6043 TemplateArgs = &TemplateArgsBuffer;
6044 }
6045
John McCall10eae182009-11-30 22:42:35 +00006046 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6047 E = UnresExpr->decls_end(); I != E; ++I) {
6048
John McCall6e9f8f62009-12-03 04:06:58 +00006049 NamedDecl *Func = *I;
6050 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6051 if (isa<UsingShadowDecl>(Func))
6052 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6053
John McCall10eae182009-11-30 22:42:35 +00006054 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006055 // If explicit template arguments were provided, we can't call a
6056 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006057 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006058 continue;
6059
John McCallb89836b2010-01-26 01:37:31 +00006060 AddMethodCandidate(Method, I.getAccess(), ActingDC, ObjectType,
6061 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006062 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006063 } else {
John McCall10eae182009-11-30 22:42:35 +00006064 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCallb89836b2010-01-26 01:37:31 +00006065 I.getAccess(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006066 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006067 CandidateSet,
6068 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006069 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006070 }
Mike Stump11289f42009-09-09 15:08:12 +00006071
John McCall10eae182009-11-30 22:42:35 +00006072 DeclarationName DeclName = UnresExpr->getMemberName();
6073
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006074 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006075 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006076 case OR_Success:
6077 Method = cast<CXXMethodDecl>(Best->Function);
John McCall58cc69d2010-01-27 01:50:18 +00006078 CheckUnresolvedMemberAccess(UnresExpr, Method, Best->getAccess());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006079 break;
6080
6081 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006082 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006083 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006084 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006085 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006086 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006087 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006088
6089 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006090 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006091 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006092 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006093 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006094 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006095
6096 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006097 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006098 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006099 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006100 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006101 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006102 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006103 }
6104
Douglas Gregor51c538b2009-11-20 19:42:02 +00006105 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00006106
John McCall2d74de92009-12-01 22:10:20 +00006107 // If overload resolution picked a static member, build a
6108 // non-member call based on that function.
6109 if (Method->isStatic()) {
6110 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6111 Args, NumArgs, RParenLoc);
6112 }
6113
John McCall10eae182009-11-30 22:42:35 +00006114 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006115 }
6116
6117 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006118 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006119 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006120 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006121 Method->getResultType().getNonReferenceType(),
6122 RParenLoc));
6123
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006124 // Check for a valid return type.
6125 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6126 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006127 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006128
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006129 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00006130 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006131 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006132 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCall2d74de92009-12-01 22:10:20 +00006133 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006134 MemExpr->setBase(ObjectArg);
6135
6136 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006137 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00006138 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006139 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006140 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006141
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006142 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006143 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006144
John McCall2d74de92009-12-01 22:10:20 +00006145 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006146}
6147
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006148/// BuildCallToObjectOfClassType - Build a call to an object of class
6149/// type (C++ [over.call.object]), which can end up invoking an
6150/// overloaded function call operator (@c operator()) or performing a
6151/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006152Sema::ExprResult
6153Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006154 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006155 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006156 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006157 SourceLocation RParenLoc) {
6158 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006159 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006160
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006161 // C++ [over.call.object]p1:
6162 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006163 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006164 // candidate functions includes at least the function call
6165 // operators of T. The function call operators of T are obtained by
6166 // ordinary lookup of the name operator() in the context of
6167 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006168 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006169 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006170
6171 if (RequireCompleteType(LParenLoc, Object->getType(),
6172 PartialDiagnostic(diag::err_incomplete_object_call)
6173 << Object->getSourceRange()))
6174 return true;
6175
John McCall27b18f82009-11-17 02:14:36 +00006176 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6177 LookupQualifiedName(R, Record->getDecl());
6178 R.suppressDiagnostics();
6179
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006180 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006181 Oper != OperEnd; ++Oper) {
John McCallb89836b2010-01-26 01:37:31 +00006182 AddMethodCandidate(*Oper, Oper.getAccess(), Object->getType(),
6183 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006184 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006185 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006186
Douglas Gregorab7897a2008-11-19 22:57:39 +00006187 // C++ [over.call.object]p2:
6188 // In addition, for each conversion function declared in T of the
6189 // form
6190 //
6191 // operator conversion-type-id () cv-qualifier;
6192 //
6193 // where cv-qualifier is the same cv-qualification as, or a
6194 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006195 // denotes the type "pointer to function of (P1,...,Pn) returning
6196 // R", or the type "reference to pointer to function of
6197 // (P1,...,Pn) returning R", or the type "reference to function
6198 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006199 // is also considered as a candidate function. Similarly,
6200 // surrogate call functions are added to the set of candidate
6201 // functions for each conversion function declared in an
6202 // accessible base class provided the function is not hidden
6203 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006204 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006205 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006206 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006207 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006208 NamedDecl *D = *I;
6209 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6210 if (isa<UsingShadowDecl>(D))
6211 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6212
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006213 // Skip over templated conversion functions; they aren't
6214 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006215 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006216 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006217
John McCall6e9f8f62009-12-03 04:06:58 +00006218 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006219
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006220 // Strip the reference type (if any) and then the pointer type (if
6221 // any) to get down to what might be a function type.
6222 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6223 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6224 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006225
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006226 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCallb89836b2010-01-26 01:37:31 +00006227 AddSurrogateCandidate(Conv, I.getAccess(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006228 Object->getType(), Args, NumArgs,
6229 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006230 }
Mike Stump11289f42009-09-09 15:08:12 +00006231
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006232 // Perform overload resolution.
6233 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006234 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006235 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006236 // Overload resolution succeeded; we'll build the appropriate call
6237 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006238 break;
6239
6240 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006241 if (CandidateSet.empty())
6242 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6243 << Object->getType() << /*call*/ 1
6244 << Object->getSourceRange();
6245 else
6246 Diag(Object->getSourceRange().getBegin(),
6247 diag::err_ovl_no_viable_object_call)
6248 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006249 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006250 break;
6251
6252 case OR_Ambiguous:
6253 Diag(Object->getSourceRange().getBegin(),
6254 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006255 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006256 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006257 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006258
6259 case OR_Deleted:
6260 Diag(Object->getSourceRange().getBegin(),
6261 diag::err_ovl_deleted_object_call)
6262 << Best->Function->isDeleted()
6263 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006264 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006265 break;
Mike Stump11289f42009-09-09 15:08:12 +00006266 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006267
Douglas Gregorab7897a2008-11-19 22:57:39 +00006268 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006269 // We had an error; delete all of the subexpressions and return
6270 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006271 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006272 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006273 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006274 return true;
6275 }
6276
Douglas Gregorab7897a2008-11-19 22:57:39 +00006277 if (Best->Function == 0) {
6278 // Since there is no function declaration, this is one of the
6279 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006280 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006281 = cast<CXXConversionDecl>(
6282 Best->Conversions[0].UserDefined.ConversionFunction);
6283
John McCall2cb94162010-01-28 07:38:46 +00006284 CheckMemberOperatorAccess(LParenLoc, Object, Conv, Best->getAccess());
John McCall49ec2e62010-01-28 01:54:34 +00006285
Douglas Gregorab7897a2008-11-19 22:57:39 +00006286 // We selected one of the surrogate functions that converts the
6287 // object parameter to a function pointer. Perform the conversion
6288 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006289
6290 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006291 // and then call it.
Eli Friedmana958a012009-12-09 04:52:43 +00006292 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006293
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006294 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006295 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6296 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006297 }
6298
John McCall2cb94162010-01-28 07:38:46 +00006299 CheckMemberOperatorAccess(LParenLoc, Object,
6300 Best->Function, Best->getAccess());
John McCall49ec2e62010-01-28 01:54:34 +00006301
Douglas Gregorab7897a2008-11-19 22:57:39 +00006302 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6303 // that calls this method, using Object for the implicit object
6304 // parameter and passing along the remaining arguments.
6305 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006306 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006307
6308 unsigned NumArgsInProto = Proto->getNumArgs();
6309 unsigned NumArgsToCheck = NumArgs;
6310
6311 // Build the full argument list for the method call (the
6312 // implicit object parameter is placed at the beginning of the
6313 // list).
6314 Expr **MethodArgs;
6315 if (NumArgs < NumArgsInProto) {
6316 NumArgsToCheck = NumArgsInProto;
6317 MethodArgs = new Expr*[NumArgsInProto + 1];
6318 } else {
6319 MethodArgs = new Expr*[NumArgs + 1];
6320 }
6321 MethodArgs[0] = Object;
6322 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6323 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006324
6325 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006326 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006327 UsualUnaryConversions(NewFn);
6328
6329 // Once we've built TheCall, all of the expressions are properly
6330 // owned.
6331 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006332 ExprOwningPtr<CXXOperatorCallExpr>
6333 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006334 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006335 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006336 delete [] MethodArgs;
6337
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006338 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6339 Method))
6340 return true;
6341
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006342 // We may have default arguments. If so, we need to allocate more
6343 // slots in the call for them.
6344 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006345 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006346 else if (NumArgs > NumArgsInProto)
6347 NumArgsToCheck = NumArgsInProto;
6348
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006349 bool IsError = false;
6350
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006351 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006352 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006353 TheCall->setArg(0, Object);
6354
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006355
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006356 // Check the argument types.
6357 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006358 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006359 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006360 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006361
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006362 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006363
6364 OwningExprResult InputInit
6365 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6366 Method->getParamDecl(i)),
6367 SourceLocation(), Owned(Arg));
6368
6369 IsError |= InputInit.isInvalid();
6370 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006371 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006372 OwningExprResult DefArg
6373 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6374 if (DefArg.isInvalid()) {
6375 IsError = true;
6376 break;
6377 }
6378
6379 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006380 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006381
6382 TheCall->setArg(i + 1, Arg);
6383 }
6384
6385 // If this is a variadic call, handle args passed through "...".
6386 if (Proto->isVariadic()) {
6387 // Promote the arguments (C99 6.5.2.2p7).
6388 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6389 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006390 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006391 TheCall->setArg(i + 1, Arg);
6392 }
6393 }
6394
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006395 if (IsError) return true;
6396
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006397 if (CheckFunctionCall(Method, TheCall.get()))
6398 return true;
6399
Anders Carlsson1c83deb2009-08-16 03:53:54 +00006400 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006401}
6402
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006403/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006404/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006405/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006406Sema::OwningExprResult
6407Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6408 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006409 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006410
John McCallbc077cf2010-02-08 23:07:23 +00006411 SourceLocation Loc = Base->getExprLoc();
6412
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006413 // C++ [over.ref]p1:
6414 //
6415 // [...] An expression x->m is interpreted as (x.operator->())->m
6416 // for a class object x of type T if T::operator->() exists and if
6417 // the operator is selected as the best match function by the
6418 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006419 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00006420 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006421 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006422
John McCallbc077cf2010-02-08 23:07:23 +00006423 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00006424 PDiag(diag::err_typecheck_incomplete_tag)
6425 << Base->getSourceRange()))
6426 return ExprError();
6427
John McCall27b18f82009-11-17 02:14:36 +00006428 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6429 LookupQualifiedName(R, BaseRecord->getDecl());
6430 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006431
6432 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006433 Oper != OperEnd; ++Oper) {
6434 NamedDecl *D = *Oper;
6435 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6436 if (isa<UsingShadowDecl>(D))
6437 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6438
John McCallb89836b2010-01-26 01:37:31 +00006439 AddMethodCandidate(cast<CXXMethodDecl>(D), Oper.getAccess(), ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00006440 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006441 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006442 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006443
6444 // Perform overload resolution.
6445 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006446 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006447 case OR_Success:
6448 // Overload resolution succeeded; we'll build the call below.
6449 break;
6450
6451 case OR_No_Viable_Function:
6452 if (CandidateSet.empty())
6453 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006454 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006455 else
6456 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006457 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006458 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006459 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006460
6461 case OR_Ambiguous:
6462 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006463 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006464 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006465 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006466
6467 case OR_Deleted:
6468 Diag(OpLoc, diag::err_ovl_deleted_oper)
6469 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006470 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006471 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006472 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006473 }
6474
6475 // Convert the object parameter.
6476 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00006477 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006478 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006479
6480 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006481 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006482
6483 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006484 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6485 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006486 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006487
6488 QualType ResultTy = Method->getResultType().getNonReferenceType();
6489 ExprOwningPtr<CXXOperatorCallExpr>
6490 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6491 &Base, 1, ResultTy, OpLoc));
6492
6493 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6494 Method))
6495 return ExprError();
6496 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006497}
6498
Douglas Gregorcd695e52008-11-10 20:40:00 +00006499/// FixOverloadedFunctionReference - E is an expression that refers to
6500/// a C++ overloaded function (possibly with some parentheses and
6501/// perhaps a '&' around it). We have resolved the overloaded function
6502/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006503/// refer (possibly indirectly) to Fn. Returns the new expr.
6504Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006505 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00006506 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6507 if (SubExpr == PE->getSubExpr())
6508 return PE->Retain();
6509
6510 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6511 }
6512
6513 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6514 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006515 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006516 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006517 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006518 if (SubExpr == ICE->getSubExpr())
6519 return ICE->Retain();
6520
6521 return new (Context) ImplicitCastExpr(ICE->getType(),
6522 ICE->getCastKind(),
6523 SubExpr,
6524 ICE->isLvalueCast());
6525 }
6526
6527 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006528 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006529 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006530 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6531 if (Method->isStatic()) {
6532 // Do nothing: static member functions aren't any different
6533 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006534 } else {
John McCalle66edc12009-11-24 19:00:30 +00006535 // Fix the sub expression, which really has to be an
6536 // UnresolvedLookupExpr holding an overloaded member function
6537 // or template.
John McCalld14a8642009-11-21 08:51:07 +00006538 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6539 if (SubExpr == UnOp->getSubExpr())
6540 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006541
John McCalld14a8642009-11-21 08:51:07 +00006542 assert(isa<DeclRefExpr>(SubExpr)
6543 && "fixed to something other than a decl ref");
6544 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6545 && "fixed to a member ref with no nested name qualifier");
6546
6547 // We have taken the address of a pointer to member
6548 // function. Perform the computation here so that we get the
6549 // appropriate pointer to member type.
6550 QualType ClassType
6551 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6552 QualType MemPtrType
6553 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6554
6555 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6556 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006557 }
6558 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00006559 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6560 if (SubExpr == UnOp->getSubExpr())
6561 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006562
Douglas Gregor51c538b2009-11-20 19:42:02 +00006563 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6564 Context.getPointerType(SubExpr->getType()),
6565 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006566 }
John McCalld14a8642009-11-21 08:51:07 +00006567
6568 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006569 // FIXME: avoid copy.
6570 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006571 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006572 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6573 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006574 }
6575
John McCalld14a8642009-11-21 08:51:07 +00006576 return DeclRefExpr::Create(Context,
6577 ULE->getQualifier(),
6578 ULE->getQualifierRange(),
6579 Fn,
6580 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006581 Fn->getType(),
6582 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006583 }
6584
John McCall10eae182009-11-30 22:42:35 +00006585 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006586 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006587 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6588 if (MemExpr->hasExplicitTemplateArgs()) {
6589 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6590 TemplateArgs = &TemplateArgsBuffer;
6591 }
John McCall6b51f282009-11-23 01:53:49 +00006592
John McCall2d74de92009-12-01 22:10:20 +00006593 Expr *Base;
6594
6595 // If we're filling in
6596 if (MemExpr->isImplicitAccess()) {
6597 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6598 return DeclRefExpr::Create(Context,
6599 MemExpr->getQualifier(),
6600 MemExpr->getQualifierRange(),
6601 Fn,
6602 MemExpr->getMemberLoc(),
6603 Fn->getType(),
6604 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006605 } else {
6606 SourceLocation Loc = MemExpr->getMemberLoc();
6607 if (MemExpr->getQualifier())
6608 Loc = MemExpr->getQualifierRange().getBegin();
6609 Base = new (Context) CXXThisExpr(Loc,
6610 MemExpr->getBaseType(),
6611 /*isImplicit=*/true);
6612 }
John McCall2d74de92009-12-01 22:10:20 +00006613 } else
6614 Base = MemExpr->getBase()->Retain();
6615
6616 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006617 MemExpr->isArrow(),
6618 MemExpr->getQualifier(),
6619 MemExpr->getQualifierRange(),
6620 Fn,
John McCall6b51f282009-11-23 01:53:49 +00006621 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006622 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006623 Fn->getType());
6624 }
6625
Douglas Gregor51c538b2009-11-20 19:42:02 +00006626 assert(false && "Invalid reference to overloaded function");
6627 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006628}
6629
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006630Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6631 FunctionDecl *Fn) {
6632 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6633}
6634
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006635} // end namespace clang